I want to trigger an animation on a list of elements and have each iteration increase in delay a bit. I have what I've done so far here:
JS Fiddle
var timer = 1000;
$('div').each(function(){
setTimeout(function(){
$('div').animate({
width:200,
height:200,
opacity:1
}, 1000);
}, timer);
timer += 1000;
});
There aren't any errors and it technically works, but they all animate at the same time. I know it's very similar (practically identical) to this, similar code, but for some reason it's not working. What am I missing?
You can use the index parameter to increase the animation as you go.
Also, you're targeting all the elements inside the loop, use the second parameter instead, which is the element currently iterated over
$('div').each(function(i, elem){
setTimeout(function(){
$(elem).animate({
width:200,
height:200,
opacity:1
}, 1000);
}, 1000 * i);
});
FIDDLE
jQuery also has a delay()
method that can be used for animations
$('div').each(function(i, elem){
$(elem).delay(i * 1000).animate({
width : 200,
height : 200,
opacity : 1
}, 1000);
});
div {
width:0;
height:0;
opacity:0;
display:block;
margin:0 auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="background:#f00;"></div>
<div style="background:#000;"></div>
<div style="background:#ccc;"></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With