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.

tags: / / / /

1 comments

  • Karl Swedberg

    Posted: Dec 5, 2011

    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!

"w3fools.com - because friends don't let friends use w3schools" ~ dan heberden
themify
Learning JavaScript