Skip to content

Instantly share code, notes, and snippets.

@MadLittleMods
Last active June 4, 2021 11:52
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save MadLittleMods/7257ee631210215e368e to your computer and use it in GitHub Desktop.
Save MadLittleMods/7257ee631210215e368e 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().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();
});
}
});
@stevenmg
Copy link

Could be cleaned up a little by removing the element ID which could potentially cause code conflicts. See line #19 at https://gist.github.com/stevenmg/b7fa34c49cce34f7cadb704f9aabfb6e

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