Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save stevenmg/b7fa34c49cce34f7cadb704f9aabfb6e to your computer and use it in GitHub Desktop.
Save stevenmg/b7fa34c49cce34f7cadb704f9aabfb6e to your computer and use it in GitHub Desktop.
Transition/Animate move to new parent - jQuery plugin
// Usage:
// $('.box').parentToAnimate($('.new-parent'), 200);
// $('.box').parentToAnimate($('.new-parent'), 'slow');
// $('.box').parentToAnimate('.new-parent', 'slow');
jQuery.fn.extend({
// Modified and Updated by MLM
// Origin: Davy8 (http://stackoverflow.com/a/5212193/796832)
parentToAnimate: function(newParent, duration) {
duration = duration || 'slow';
var $element = $(this);
newParent = $(newParent); // Allow passing in either a JQuery object or selector
var oldOffset = $element.offset();
$(this).appendTo(newParent);
var newOffset = $element.offset();
var temp = $element.clone().removeAttr('id').appendTo('body');
temp.css({
'position': 'absolute',
'left': oldOffset.left,
'top': oldOffset.top,
'zIndex': 1000
});
$element.hide();
temp.animate({
'top': newOffset.top,
'left': newOffset.left
}, duration, function() {
$element.show();
temp.remove();
});
}
});
@Symmetronic
Copy link

The element's size could change depending on the old and new parent (e.g. if the element has a size of 100%). To show a smooth transition, I added a few lines:
https://gist.github.com/Symmetronic/a52d6ff79900986e70b025817366875b

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment