0

I'm trying to add a class to an li element once after button is clicked. The goal is to add the class one at a time with a delay time in between. It seems to work fine with the fadeOut function but not with the addClass or related function.

Here is a Jsfiddle.net demo http://jsfiddle.net/4ANCj/3/

and part of the code

$("button").click(function() {
    $('li').each(function(index) {
        $(this).delay(900*index).addClass("hi");
    });
});

I know there is a similar question here on SO but it does not cut it.

Community
  • 1
  • 1
andrewk
  • 3,721
  • 4
  • 30
  • 37

1 Answers1

2

addClass is not an animation function, so it is not added to the effect queue. You can use .queue [docs] instead (adds to the effect queue by default):

$(this).delay(900*index).queue(function(next) {
    $(this).addClass("hi");
    next();
});

Or use setTimeout [MDN] for a non-jQuery solution:

$("button").click(function() {
    var lis = $('li').get();

    function run() {
        var li;
        if(li = lis.shift()) {
            $(li).addClass('hi');
            setTimeout(run, 900);
        }
    }

    setTimeout(run, 900);
});
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143