How to effect "cascade" with Javascript / jQuery?

Asked

Viewed 664 times

7

Imagine I have a list of 20 blocks <li>, and that when the page loads, each of them should be shown within milliseconds of each other (this would be done with CSS3, so the code would only have to add a class to the elements), like a "cascade effect".

How could I pass this logic to Javascript / jQuery?

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

2 answers

8


You can use it like 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

  • 1

    +1 Contrary to my answer, this does not depend on creating extra variables unnecessarily

  • @mgibsonbr, this time I agree with you, you usually have the best and fastest response :)

5

For a better and more concise solution, see the response of @Sergio.

I’d 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.

  • Both questions (yours and @Sergio’s) worked correctly and were easy to understand, which left me wondering which one to choose. I thought a fair criterion for the "tie-breaker" would be the performance of the proof code, and that’s what I did. Your code has shown to perform better and so I will mark yours as correct, but Sergio’s code is also efficient and even smaller. Test link: http://jsperf.com/efeito-em-cascade

  • @Kazzkiq Thanks, but there’s a fundamental problem in your test: in my solution, the code for each element only runs when processing that element; in Sergio’s, the loop to process the entire list runs at once. In other words, you are comparing apples to oranges. I tried to adapt the test to be fairer, but it is difficult, since these are asynchronous events. But I have strong suspicions that his is more efficient too - since mine uses eq.

  • P.S. I give up! It is impossible to correctly evaluate the performance of these solutions using jsperf... Please do not execute Revision 3 of the link above (created by me) as it will crash your browser! :(

Browser other questions tagged

You are not signed in. Login or sign up in order to post.