Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When animating, how fire the callback only when all elements are done?

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
}
like image 561
Maria Söderberg Avatar asked May 24 '10 13:05

Maria Söderberg


2 Answers

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
};
like image 121
microspino Avatar answered Nov 11 '22 11:11

microspino


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...

like image 37
Justin Ethier Avatar answered Nov 11 '22 12:11

Justin Ethier