Invoking a jQuery function after .each() has completed

Luther Baker picture Luther Baker · Mar 1, 2010 · Viewed 234.3k times · Source

In jQuery, is it possible to invoke a callback or trigger an event after an invocation of .each() (or any other type of iterative callback) has completed.

For example, I would like this "fade and remove" to complete

$(parentSelect).nextAll().fadeOut(200, function() {
    $(this).remove();
});

before doing some calculations and inserting new elements after the $(parentSelect). My calculations are incorrect if the existing elements are still visible to jQuery and sleeping/delaying some arbitrary amount of time (200 for each element) seems like a brittle solution at best.

I can easily .bind() the necessary logic to an event callback but I'm not sure how to cleanly invoke the .trigger() after the above iteration has completed. Obviously, I can't invoke the trigger inside the iteration as it would fire multiple times.

In the case of $.each(), I've considered adding something to the end of the data argument (that I'd manually look for in the iteration body) but I'd hate to be forced to that so I was hoping there was some other elegant way to control the flow with respect to iterative callbacks.

Answer

Sébastien GRAVIER picture Sébastien GRAVIER · Jan 20, 2012

It's probably to late but i think this code work...

$blocks.each(function(i, elm) {
 $(elm).fadeOut(200, function() {
  $(elm).remove();
 });
}).promise().done( function(){ alert("All was done"); } );