views:

47

answers:

2

When animating in jQuery, what's best practice for firing a callback only when ALL elements are done animating and not for each element?

For example:

$('.someElements').fadeOut('fast', function() {
  // dont do this until ALL elements are done fading
}
+2  A: 

This is a great question, as per the jQuery docs:

If multiple elements are animated, it is important to note that the callback is executed once per matched element, not once for the animation as a whole.

To work around this limitation you could:

  • Enumerate all of the elements matching .someElements, and set up a separate callback for each one.
  • Have a count variable that keeps track of how many total callbacks there are.
  • In your callback, decrement count until it reaches 0.

When count reaches 0, all callbacks are complete, and you will be guaranteed that all elements are done animating. From here, you can then have special code in your callback that does whatever you need to do...

Justin Ethier
Thanks Justin! This seems a bit elaborate if you just want the callback to fire once, but is great for when you need something to happen for each animation as well. For this simpler case I'd go with microspino's answer, though.
Maria Söderberg
+2  A: 

This could be a snippet to try:

var numberOfElements = $('.someElements').length;

$('.someElements').fadeOut(fast, function() {
  if( numberOfElements-- > 0 ) return;
  alert('call the Fireman!'); 
});

The alert Is just a placeholder to the end-callback you need to fire.

EDIT (another way):

You can also catch all the elements but not the last one.

$('.someElements').not(.someElements:last).fadeOut();

and then add a fadeOut with callback only to It

$('.someElements:last').fadeOut(fast, function (){ 
   // do something, it's the end of the world
};
microspino
Great! But, to make the comparison become true, the condition should be (--numberOfElements > 0) right? To decrease the variable before the comparison.
Maria Söderberg
-- is a LeftHandSideExp operator. The expression decrease first then evaluate the comparison. Say you are on the last loop: you have 1 element, the expression goes this way: 1-- > 0 ? False, don't return, go to next line and fire the alert call.
microspino