jQuery: tracking animations

When you have sequential animations in jQuery involving the use of positioning, it's important to keep track of the current position of an element if you want to progressively change its status on the screen. Basically, all jQuery animations that take place during a call to animate() are a one-way process: you trigger the animation, it takes place, it ends. End of the story. Suppose that you have an element and a trigger link that activates an animation. Each time you click on this link, the affected element must be moved leftwards by 100 pixels. One could write something like this:

$('#run').click(function(e) {

    $('#test').animate({
       left: += 100
    });
    
    e.preventDefault();


});

You click once on the link and everything works just fine. You click twice and sometimes nothing happens. Why? Because we need to track the position of the element in order to run sequential animations, like so:

$('#run').click(function(e) {

    var track = $('#test').offset().left;

    $('#test').animate({
       left: track + 100
    });
    
    e.preventDefault();


});

We've stored the current left offset of the element in a variable. On the first click, this value is 0, so the computation is 0 + 100. On the second click, this value is 100, so we'll have 100 + 100. And so on. As you can see, it's all very simple and requires just a single additional step.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.