When animating, how fire the callback only when al

2019-04-07 20:38发布

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
}

3条回答
一纸荒年 Trace。
2楼-- · 2019-04-07 21:22

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
};
查看更多
SAY GOODBYE
3楼-- · 2019-04-07 21:22

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

查看更多
4楼-- · 2019-04-07 21:26

More recent releases of jQuery (version 1.6 and later) include the idea of a promise. Using this function eliminates the need for a workaround. For example:

// define the animation on many elements
$('.someElements').fadeOut('fast');

// define the promise that is called once all element animations are done
$('.someElements').promise().done( function() {
    // put callback actions here
});
查看更多
登录 后发表回答