Javascript move multiple elements to separate div's and back

依然范特西╮ 提交于 2019-12-02 02:34:56

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;

function videoClicked(e)
{
    //get a reference to the video clicked
    var 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


}
});

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!