Chain Animation function using deffer / promise in jquery.

This simple function will let you execute your chain of animations in sequence very easily.

 


//define chain function
$.chain = function() {
    var promise = $.Deferred().resolve().promise();
	// pipe all arguments
    jQuery.each( arguments, function() {
        promise = promise.pipe( this );
    });
    return promise;
};

// Pass the animations as arguments to chain function in a sequence
var animations = $.chain(function() {
    return $('.div1').fadeOut('slow');
}, function() {
    return $('.div2').fadeIn('fast');
}, function() {
    return $('.div3').animate({ left: 500 }, 1500 );
});

// done callback for the promise returned by animations var
$.when( animations ).done(function() {
    // animations completed
});