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.

3 Comments

Karl Swedberg Posted: Dec 05, 2011 @ 10:26pm

Nice one, Darcy! Great to see you spreading the knowledge around!

A slightly different syntax that can be used for this sort of thing is to use the $.fn.promise() method

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

I figure you already know about it, but thought I’d post it in this here comment to help with the education effort. :)

cheers!

Yotam Posted: Nov 01, 2012 @ 10:37am

That’s absolutely what I was looking for.
Can the promise be achieved using other jquery methods?

Šime Vidas Posted: Dec 04, 2012 @ 4:43pm

I applied that info in one of my answers on Stack Overflow (http://stackoverflow.com/a/13712302/425275). Thanks. Btw, the design of this web-site is amazing. :-)

Leave a Reply: