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
}
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
};
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:
.someElements
, and set up a separate callback for each one. count
variable that keeps track of how many total callbacks there are. 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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With