35

I have an image tag inside of a table cell, that I'd love to move to another table cell, and have that movement animated.

The code looks something like this...

<td id="cell1"><img src="arrow.png" alt="Arrow"/></td>
<td id="cell2"></td>

I'd like to move "arrow.png" to "cell2", and have some kind of transition effect, preferably with JQuery.

Any ideas?

Thanks!

9 Answers 9

56

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.

2
  • you have a "great answer" badge from me :)
    – Sinan
    Sep 13, 2010 at 13:49
  • What if you have a list of items and you need the other items to animate down to make room as well?
    – Chet
    Jan 9, 2015 at 1:08
54

@Pim Jager's answer is pretty good, however if you have object references to the original element they would break since the the original element was replaced with a clone

I came up with what I think is a slightly cleaner solution in that it only has a single clone that show up for animation then goes away, leaving the original in the new location.

function moveAnimate(element, newParent){
    //Allow passing in either a jQuery object or selector
    element = $(element);
    newParent= $(newParent);

    var oldOffset = element.offset();
    element.appendTo(newParent);
    var newOffset = element.offset();

    var temp = element.clone().appendTo('body');
    temp.css({
        'position': 'absolute',
        'left': oldOffset.left,
        'top': oldOffset.top,
        'z-index': 1000
    });
    element.hide();
    temp.animate({'top': newOffset.top, 'left': newOffset.left}, 'slow', function(){
       element.show();
       temp.remove();
    });
}

To use: moveAnimate('#ElementToMove', '#newContainer')

9
  • 1
    Great function. Works very well!
    – Rocky
    Oct 13, 2011 at 16:09
  • I keep getting "Uncaught TypeError: Cannot read property 'left' of undefined " error on that function, happen to know why? i used it just as you said. Oct 21, 2012 at 14:21
  • Ya now works without an error but if i try and use it in a loop the animation seems to be "broken" Oct 22, 2012 at 6:23
  • @eric.itzhak Yeah, since animations happen asynchronously you'll need a way to queue them. The most straightforward way is to add a callback function parameter and set up a recursive call with a proper end way to exit. Fully explaining that is a bit out of scope for this answer, but if you search for how to use callbacks in JS you should be able to figure out the answer. Otherwise you can ask a new question.
    – Davy8
    Oct 22, 2012 at 18:59
  • 2
    I have improved upon your snippet by making it a small jQuery plugin and cleaning it up a bit: gist.github.com/MadLittleMods/7257ee631210215e368e
    – MLM
    Jul 17, 2014 at 5:27
3

You'll need to do this in two steps: (1) animation (2) rehoming.

The animation you can take care of with .animate(), as @Ballsacian points out. The rehoming can be accomplished with .html() - for the example above,

var arrowMarkup = $('#cell1').html(); //grab the arrow
$('#cell1').html(""); //delete it from the first cell
$('#cell2').html(arrowMarkup); //add it to the second cell

Of course, you'll have to complicate that code to integrate the animation. And this way of doing it won't cause the selection (I'm assuming you're selecting a table row?) to activate rows between the old selection and the new one, as the arrow passes by them. That'd be even more complex to achieve.

3

I have extended one of the other answers a little further so that now you can pass an object as a third parameter which serves as a vehicle during the animation. For example, if you want to move some <li> from one <ul> to another, your <ul> likely has a certain class that gives the <li> its styling. So, it would really be handy to animate your <li> inside a temporary vehicle <ul> that provides for the same styling as either the source or the target <ul> of the animation:

//APPENDS AN ELEMENT IN AN ANIMATED FASHION
function animateAppendTo(el, where, float){
    var pos0 = el.offset();
    el.appendTo(where);
    var pos1 = el.offset();
    el.clone().appendTo(float ? float : 'body');
    float.css({
        'position': 'absolute',
        'left': pos0.left,
        'top': pos0.top,
        'zIndex': 1000
    });
    el.hide();
    float.animate(
        {'top': pos1.top,'left': pos1.left},
        'slow',
        function(){
           el.show();
           float.remove();
        });
}
2

I was trying @Davy8's function which is quite good, but I found it quite jarring when the moved element snapped off the page at the start then back in at the end. The other page elements suddenly shifting interrupted an otherwise smooth animation, but this likely would depend on your page layout.

So this is a modified version of @Davy8's function, which should also smoothly shrink and grow space between parents.

function moveAnimate(element, newParent,
                     slideAnimationSpeed/*=800*/, spacerAnimationSpeed/*=600*/)
{
    //Allow passing in either a jQuery object or selector
    element = $(element);
    newParent= $(newParent);
    slideAnimationSpeed=slideAnimationSpeed||800;
    spacerAnimationSpeed=spacerAnimationSpeed||600;

    var oldOffset = element.offset();
    var tempOutgoing=element.clone().insertAfter(element);
    tempOutgoing.hide(); //Don't take up space yet so 'newOffset' can be calculated correctly
    element.appendTo(newParent);
    var newOffset = element.offset();

    var tempMover = element.clone().appendTo('body');
    tempMover.css({
        'position': 'absolute',
        'left': oldOffset.left,
        'top': oldOffset.top,
        'z-index': 1000,
        'margin':0 //Necessary for animation alignment if the source element had margin
    });

    element.hide();
    element.show(spacerAnimationSpeed).css('visibility', 'hidden'); //Smoothly grow space at the target

    tempMover.animate({'top': newOffset.top, 'left': newOffset.left}, slideAnimationSpeed, function(){
       element.css('visibility', 'visible');
       tempMover.remove();
    });
    tempOutgoing.show().css('visibility', 'hidden');
    tempOutgoing.hide(spacerAnimationSpeed, function(){ tempOutgoing.remove() }); //smoothly shrink space at the source
}
0

If the animation doesn't have to be the thing moving, this question which uses fadeIn and fadeOut gives a simple, clean answer with no cloning and still conveys the motion quite well:

Re-ordering div positions with jQuery?

0

For anyone still viewing this, I found the provided examples didn't fit exactly what I wanted and they didn't account for margins, so here's my version:

jQuery.fn.extend({
    moveElement : function (newParent, speed, after) {
        var origEl   = $(this);
        var moveToEl = $(newParent);

        var oldOffset = origEl.offset();
        var temp      = origEl.clone().appendTo('body');

        temp.css({
            'position' : 'absolute',
            'left'     : parseInt(oldOffset.left) - parseInt(origEl.css('margin-left')),
            'margin'   : origEl.css('margin'),
            'top'      : oldOffset.top,
            'z-index'  : 1000,
            'height'   : moveToEl.innerHeight(),
            'width'    : moveToEl.innerWidth()
        });

        var blankEl = $('<div></div>').css({
            height   : moveToEl.innerHeight(),
            margin   : moveToEl.css('margin'),
            position : 'relative',
            width    : moveToEl.innerWidth()
        });

        if (after) {
            origEl.insertAfter(moveToEl);
            blankEl.insertAfter(newParent);
        }
        else {
            origEl.insertBefore(moveToEl);
            blankEl.insertBefore(newParent);
        }
        origEl.hide();

        var newOffset = blankEl.offset();

        temp.animate({
            'top'  : blankEl.offset().top - parseInt(moveToEl.css('margin-top')),
            'left' : newOffset.left - parseInt(moveToEl.css('margin-left'))
        }, speed, function () {
            blankEl.remove();
            origEl.show();
            temp.remove();
        });
    }
});

Move an element before another: $('.elementToFind').moveElement('.targetElement', 1000);

Move an element after another: $('.elementToFind').moveElement('.targetElement', 1000, 'after');

0

If someone is looking for a version without jQuery, this is my vanilla-javascript version

let myAnimation ={
    // https://youmightnotneedjquery.com/ instead of $.offfset()
    offset: function (elementNode) {
        let box = elementNode.getBoundingClientRect();
        let docElem = document.documentElement;
        return {
            top: box.top + window.scrollY - docElem.clientTop,
            left: box.left + window.scrollX - docElem.clientLeft
        };
    },

    testMove: function() {
        let start = document.getElementById('start');
        let end = document.getElementById('end');
        // calculate direct path
        let oldOffset = this.offset(start);
        let newOffset = this.offset(end);
        let startNode = document.querySelector('#start div');
        // drop element at new position
        end.appendChild(startNode); // transfer the element
        let dy = `${oldOffset.top - newOffset.top}px`;
        let dx = `${oldOffset.left - newOffset.left}px`;
        startNode.style.top = dy;
        startNode.style.left = dx;
        // definition of animation keyframe-like
        const offsetMoveAction = [
            { 'left': dx,'top': dy,  },
            {  'left': 0,'top': 0,  },
        ];
        const offsetMoveTiming = {
            duration: 2000,
            iterations: 1,
            easing: 'ease-in-out',
            fill: 'forwards', // unexpected key for `animation-fill-mode` :-(
        };
        startNode.animate(offsetMoveAction, offsetMoveTiming);
    },

}
// do it
myAnimation.testMove();
<div style="width:200px; height: 200px; position:relative; border: solid 1px red;margin: 20px;">
    <div id="start" style="position:absolute; top:0; left:0;width:15ch;">
        <div style="position:relative; ">
            <div style="position:absolute; top:0; left:0;">drag and drop by JS</div>
        </div>
    </div>
    <div id="end" style="position:absolute; right:0; bottom:1rem;width:16ch;"></div>
</div>

-3

JQuery http://docs.jquery.com/Downloading_jQuery
JQuery Effects http://docs.jquery.com/Effects/animate#paramsoptions


Example

 $("#go1").click(function(){
      $("#block1").animate( { width:"90%" }, { queue:false, duration:3000 } )
         .animate( { fontSize:"24px" }, 1500 )
         .animate( { borderRightWidth:"15px" }, 1500);
    });
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.