Skip to content Skip to sidebar Skip to footer

Javascript Move Multiple Elements To Separate Div's And Back

There are 3 videos, placed in 3 separate div's. There also are 3 separate div's, but in other position of a page (lets say contA and contB and contC). I want that if I click on the

Solution 1:

Think this is what you're looking for, but it's based on the naming convention used in the example. I also took the liberty of renaming contA/contB and contC to cont1, cont2 and cont3, because it's easier to manipulate.

JSBin demo

//remember last video clicked (you could check last container instead)var lastclicked;

functionvideoClicked(e)
{
    //get a reference to the video clickedvar sender = e.target;
  //get all the videos var $videos = $('.videos');  

    if(sender==lastclicked){
      //reset to original positions

      $.each($videos,function(){
        var ind =     this.id.substring(this.id.length-1); //based on the video + number naming convention
        $(this).appendTo('#vid' + ind);
      });
      lastclicked = null;
      return;
    }

    lastclicked= sender;  

     var i = 1;  
     //place all non clicked videos in cont1/cont2/etc
     $.each($videos.not(sender),function()
     { 
       $(this).appendTo('#cont' + i++ );
     });

     //place the clicked video in the last container
     $(sender).appendTo('#cont' + i ); //always cont3 with fixed divs, but this is dynamic in case you add more


}
});

Solution 2:

I will edit this answer as the desired results become more clear but i think i can give you some info to get you going in the right direction.

the section of code "but i need each video to be put to a diff cont"

I would leverage a data attribute and let each control keep track of itself.

    $video.each(function()
    { 
        var targetdiv = $(this).data('origonal-div');
        $(targetdiv.ToString()).append(this);
                    //optionally update the data value to keep track of the next location to append to.
    }

if you need more info post some questions with an update on the jsbin so i can see where you are having trouble.

Cheers

Post a Comment for "Javascript Move Multiple Elements To Separate Div's And Back"