Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Rather than using the callback of <code>animate</code> to call a secondary animation, if you chain <code>animate().delay().animate()</code> you can return the promise for the secondary animation.</p> <p>My solution uses nested arrays of objects so you can easily add as many animations in one sequence as you wish. The trick is to create an array of all of the promises within the group and use that array to determine when the full group of animations is complete.</p> <p>Sample data:</p> <pre><code>var animations = [ /* first group array */ [ { "sel": ".box1","main": {"css": {"top": "100px"},"dur": 1000}, "secondary": {"delay": 100,"css": {"top": "50px"},"dur": 1000 } }, {"sel": ".box2","main": {"css": {"top": "100px"},"dur": 1000}}, {"sel": ".box4","main": {"css": {"top": "100px"},"dur": 1000}}, { "sel": ".box5","main": {"css": {"top": "100px"},"dur": 1000}, "secondary": {"delay": 100,"css": {"top": "50px"},"dur": 1000 } } ], /* second group array */ [ { "sel": ".box3","main": {"css": {"top": "100px"},"dur": 1000}, "secondary": {"delay": 100,"css": {"top": "50px"},"dur": 1000 } }, {"sel": ".box4","main": {"css": {"top": "100px"},"dur": 1000}} ] ]; </code></pre> <p>JS:</p> <pre><code>var curr = -1; var paused = false; function animateBoxes() { if (paused) { return; } //curr = (curr + 1 &lt; animations.length) ? curr + 1 : 0; curr=curr+1; if( !animations[curr]){ alert('DONE!!'); return; } /* array of animation deffereds*/ var anims = []; $.each(animations[curr], function(i, currAnim) { var anim = boxAnimate(currAnim); anims.push(anim) }); $.when.apply(null, anims).done(function() { animateBoxes(); }); } $('#start').click(function() { paused = false; animateBoxes(); }); $('#reset').click(function() { curr = -1; stopanimation(); $('.box').css({ top: '0px' }); }); $('#pause').click(function() { stopanimation(); }); function stopanimation() { paused = true; $('div:animated').stop(true, true); } function boxAnimate(obj) { var $el = $(obj.sel), anim; if (obj.secondary) { /* chain animate &amp; delay to get promise for last effect */ anim = $el.animate(obj.main.css, obj.main.dur) .delay(obj.secondary.delay) .animate(obj.secondary.css, obj.secondary.dur) } else { anim = $el.animate(obj.main.css, obj.main.dur) } return anim; } </code></pre> <p>DEMO: <a href="http://jsfiddle.net/SWHTx/5/" rel="nofollow">http://jsfiddle.net/SWHTx/5/</a></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload