Search code examples
javascriptaddclasssequential

Add class to a collection of elements sequentially starting with last element


I wanted to add a class to a collection of elements sequentially. I found an answer here.

For reference here is the code from that article:

var i = 0;
var callback;

callback = function () {
    if (i < article.length) {
       $(article[i]).addClass('something');

       ++i;
       setTimeout(callback, 10000);
    }
};

setTimeout(callback, 10000);

I would now like to remove the class starting with the last element, so in effect reverse the order of what will be an animation.

Can anyone help? Many thanks in advance.


Solution

  • Just start i as article.length loop in the other direction

    var i = article.length;
    var callback;
    
    callback = function () {
        if (i--) {
           $(article[i]).removeClass('something');
           setTimeout(callback, 10000);
        }
    };
    
    setTimeout(callback, 10000);