I am writing a script that will animate a set of jQuery Elements, but I'm running into some issues. Here are my requirements:
- Sequential animations
- Callback functionality after all animations are complete. Callback can be defined globally
- Animation works on floated elements with
- Entire solution can be js/jquery/css or a combination
Here's what I've gotten so far: http://jsfiddle.net/fmpeyton/cqAws/
HTML
<div class="block">Im a box</div>
<div class="block">me too</div>
<div class="block">and me!</div>
<div class="block">am I?</div>
<div class="block">yes.</div>
<div class="block">Im a box</div>
<div class="block">me too</div>
<div class="block">and me!</div>
<div class="block">am I?</div>
<div class="block">yes.</div>
<div class="block">Im a box</div>
<div class="block">me too</div>
<div class="block">and me!</div>
<div class="block">am I?</div>
<div class="block">yes.</div>
CSS
.block{
float:left;
width:100px;
background: red;
margin: 0 10px;
padding: 10px;
}
.hiddenForAnimation{ opacity:0; margin-top:-20px; }
JS
$(function(){
$('.block').addClass('hiddenForAnimation').each(function(i){
var delay = i * 200,
animationSpeed = 800;
$(this).delay(delay).animate({opacity: '1', marginTop: '0px'
}, animationSpeed, function(){ if(typeof afterPageAnimation === 'function' && i === $(this).length){ setTimeout(afterPageAnimation, delay + animationSpeed);} $(this).removeClass('hiddenForAnimation').attr('style',''); });
});
});
function afterPageAnimation(){ alert('animation is done!'); }
My issues:
- Is there a better way to refactor this JS script to be sequential? Using
delay()is effective, but not elegant. - The callback is not being executed directly after the animations
- When the last element in a row finishes animating, the first element in the next row starts at the far right, then jumps to the left (I suspect
margin-tophas something to do with this.)
Thanks!