JQuery – animate moving DOM element to new parent?

This is actually quite difficult because you have to remove and add it to the DOM but keep its position. I think you’re looking for something like this. Basically we don’t animate either the arrow in #cell1 or #cell2. We just create a new one in the body-tag and animate that. That way we don’t have to worry about the table cell positions because we can position relative to the document.

var $old = $('#cell1 img');
//First we copy the arrow to the new table cell and get the offset to the document
var $new = $old.clone().appendTo('#cell2');
var newOffset = $new.offset();
//Get the old position relative to document
var oldOffset = $old.offset();
//we also clone old to the document for the animation
var $temp = $old.clone().appendTo('body');
//hide new and old and move $temp to position
//also big z-index, make sure to edit this to something that works with the page
$temp
  .css('position', 'absolute')
  .css('left', oldOffset.left)
  .css('top', oldOffset.top)
  .css('zIndex', 1000);
$new.hide();
$old.hide();
//animate the $temp to the position of the new img
$temp.animate( {'top': newOffset.top, 'left':newOffset.left}, 'slow', function(){
   //callback function, we remove $old and $temp and show $new
   $new.show();
   $old.remove();
   $temp.remove();
});

I think this should point you in the right direction.

Leave a Comment