Darcy Clarkebuilding products / experiences / communities & culture

Toggle Main Navigation

Dec 5, 2011

Using jQuery Deferreds with Animations

Posted in "development"


I try and hang out in the #jQuery IRC Channel whenever I've got some time and I see a lot of the same questions. One of those, which I see fairly often, is: "How do I run some code once my animations ar finished?". The simple answer would be to add a callback function to .animate(), but for many, they only want to execute that function once, after all their elements have finished animating. We can solve this easily with deferreds.

$.when($('div').animate({"opacity": "0"}, 1000)).done(function(){
    // animations are finished, run code 
});

The above example shows how we can easily wrap our animate in a deferred and it gets nicely resolved with our callback only executing a single time.