I'm trying to animate a set of elements simultaneously (almost, there's a small delay between each animation):
$('.block').each(function(i){
$(this).stop().delay(60 * i).animate({
'opacity': 1
}, {
duration: 250,
complete: mycallbackfunction // <- this fires the callback on each animation :(
});
});
How can I run a callback function after all animations have completed?
Since jQuery 1.5, you can use
$.when
[docs], which is a bit easier to write and understand:DEMO
Use a closure around a counter variable.
Note the saving of the list of items into the $block variable to save a lookup.
Felix Kling's answer will fire the callback when there's no animation left to do. This makes the callback firing even if the animation is stopped via
$el.stop()
and thus not completed to the end.I found an method by Elf Sternberg using deferred objects which I implemented in this jsfiddle:
http://jsfiddle.net/8v6nZ/