How to effect cascade with Javascript / jQuery?

7

Imagine that I have a list of 20 <li> blocks, and that when the page loads, each of them should be shown with a millisecond difference from one to another (this would be done with CSS3 , so code just have to add a class in the elements), like that a "cascade" effect.

How could I pass this logic to JavaScript / jQuery?

Here's a FIDDLE with all the example, just missing the logic of the effect "cascade ".

    
asked by anonymous 06.04.2014 / 00:38

2 answers

8

You can use this:

$('ul li').each(function (i, el) { // percorrer cada elemento
    setTimeout(function () {   
        $(el).addClass('on');  // adicionar a classe
    }, i * 200);               // usar o indice do .each() do jQuery para multiplicar por 200 milisegundos
});

Example

    
06.04.2014 / 00:44
5
  

For a better and more concise solution, see @Sergio's answer .

I would use a simple setInterval :

var indice = 0;
var interval = setInterval(function() {
    var proximo = $("li").eq(indice++);
    if ( proximo.length == 0 )
        clearInterval(interval);
    else
        proximo.addClass("on");
}, 500);

Example .

    
06.04.2014 / 00:42