Let's say I have three divs, and I'd like each to animate once the previous one is done. Currently, I write this:
$('div1').fadeOut('slow', function() {
$('div2').fadeOut('slow', function() {
$('div3').fadeOut('slow');
});
});
Which is ugly, but manageable.
Now imagine I have 10 different animations that need to happen one after the other on different elements. Suddenly the code gets so clunky that it's extremely hard to manage...
Here's pseudocode for what I'm looking to do:
$('div1').fadeOut('slow' { delay_next_function_until_done: true } );
$('div2').fadeOut('slow' { delay_next_function_until_done: true } );
$('div3').animate({ top: 500 }, 1000 );
How do I achieve this?
If you're using a recent version of jQuery, use the animation promises:
You can make it generic:
Still a lot of function closures but that's the very nature of Javascript. However, it's much more natural and a lot more flexible using Deferreds/Promises since you avoid callbacks "inception".
Use this:
If you can give the
<div>
s a class:Live DEMO
Callback is a friend, dont push it away. There are ways to simplify them. Here is one of them
One way to do this would be to write your own helper function, like so:
And use it like so:
try something like:
Adjust the timing as necessary
When ever completion functions or callbacks get nested too deep or code is getting repeated over and over again, I tend to think about a data table solution with a common function:
And, if you wanted a different type of animation for some of the items, you could create a array of objects that describe what each successive animation is supposed to be. You could put as much detail in the array of objects as was needed. You can even intermix animations with other synchronous jQuery method calls like this:
And, here's a working demo of this second option: http://jsfiddle.net/jfriend00/PEVEh/