jQuery .animate/.each chaining

Aaron picture Aaron · Jan 4, 2010 · Viewed 9.3k times · Source

I'm trying to combine matching something like:

$(".item").each(function(i) {
    //animation here
});

with jQuery's inherent chaining functionality that forces the animation to wait until the previous animation has completed, e.g.:

$(".item").each(function(i) {
    $(this).animate({marginLeft:"0"}, 60);
});

And then trigger a .load function after the animations have completed. Basically, I want to fade four items out in order [one after the next, not all at once], then load four new items into the same div, replacing the first four.

How can I do this in a reusable/variable way?

Answer

David Hellsing picture David Hellsing · Jan 4, 2010

How about checking if the element is the last one and then adding a callback?

$(".item").each(function(i, elem) {
    var callback = $(elem).is(':last') ? function() {
        //dosomething
    } : function(){};
    $(this).animate({marginLeft:"0"}, {duration: 60, complete: callback);
});