Chaining jQuery animations that affect different elements

fadeIn takes a callback as its second parameter. That callback is executed as soon as the animation is complete. If you want the elements to fade in sequentially, you could chain the callbacks:

$(document).ready(function() {
    $("#div1").fadeIn("slow", function(){
        $("#div2").fadeIn("slow", function(){
            $("#div3").fadeIn("slow", function(){
                $("#div4").fadeIn("slow");
            });
        });
    });
});

This could be re-written using an array of selectors and a single method, if you felt like it:

var chain = function(toAnimate, ix){
    if(toAnimate[ix]){
        $(toAnimate[ix]).fadeIn('slow', function(){ chain(toAnimate, ix + 1 )});
    }
};

$(document).ready(function(){
    chain(['#div1', '#div2', '#div3', '#div4'], 0);
});

See this last one in action at JSBin.

Leave a Comment