Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery - increase timeout interval with each iteration of .each()

Tags:

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?

like image 692
stinkysGTI Avatar asked Mar 25 '16 21:03

stinkysGTI


1 Answers

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>
like image 114
adeneo Avatar answered Oct 11 '22 13:10

adeneo