Running jQuery animations in serial

I have a fade animation group, after which I want to start the animation call group.

How can I make sure one by one?

If I do this:

 $(div1).fadeOut(600); $(div2).fadeOut(600); $(div3).fadeOut(600); $(div4).animation({opacity:1},600); $(div5).animation({opacity:1},600); $(div6).animation({opacity:1},600); 

Animation runs in parallel.

The above code is just a simplification / abstraction of the problem. I cannot group all the calls into one function, and in real life there is a variable number of elements, each of which is controlled by its own class.

+6
source share
2 answers

You can use jQuery pending objects :

 var deferred = [ new $.Deferred(), new $.Deferred(), new $.Deferred() ]; $(div1, div2, div3).each(function(i, elem) { $(elem).fadeOut(600, function() { deferred[i].resolve(); }); }); $.when(deferred[0], deferred[1], deferred[2]).done(function() { $(div4, div5, div6).each(function(i, elem) { $(elem).animation({ opacity : 1 }, 600); }); }); 

As @Felix noted in the comments, a cleaner syntax for $.when would look like this:

 $.when.apply(null, deferred).done(function() { $(div4, div5, div6).each(function(i, elem) { $(elem).animation({ opacity : 1 }, 600); }); }); 
+6
source

If you are using jQuery 1.6+, the deferred.pipe () function can simplify the code:

 $.Deferred(function (dfr) { dfr .pipe(function () { return $(div1).fadeOut(600); }) .pipe(function () { return $(div2).fadeOut(600); }) .pipe(function () { return $(div3).fadeOut(600); }) }).resolve(); 

Link: http://blog.darkthread.net/post-2011-08-03-deferred-pipe-animation.aspx

+3
source

Source: https://habr.com/ru/post/892901/


All Articles