Pinkie
Pinkie

Reputation: 10256

jQuery using delay() with $.each() not working

I have different classes each with a different background. I'm trying to switch background on div #elm every 2 seconds. Why is the following not delaying 2 seconds between each index. They all come in at once.

var classes = ['class1', 'class2', 'class3'];
$.each(classes, function(index, val) {
    $('#elm').removeAttr('class').addClass(val).delay(2000*index);
});

http://jsfiddle.net/bLHqP/

Upvotes: 0

Views: 1030

Answers (3)

Hussein
Hussein

Reputation: 42818

delay() only works on effects.

From jQuery delay() documantation

The .delay() method is best for delaying between queued jQuery effects. Because it is limited—it doesn't, for example, offer a way to cancel the delay—.delay() is not a replacement for JavaScript's native setTimeout function, which may be more appropriate for certain use cases.

Since addClass() is not an effect, you can include a fadeIn() effect and use addclass as a callback function.

var classes = ['class1', 'class2', 'class3'];
$.each(classes, function(index, ui) {
    $('body').removeAttr('class').delay(1000).fadeIn(function() {
        $(this).addClass(ui);
    });
});

Check working example at http://jsfiddle.net/8e3Rm/

Upvotes: 2

manji
manji

Reputation: 47978

EDIT:

this works:

for (var i = 0; i < classes.length; i++) {
    setTimeout (    
        (function(index){
        return function(){
            $('#elm').removeAttr('class').addClass(classes[index]);
        };
        })(i), 2000*i);
}

Upvotes: 1

Marc
Marc

Reputation: 310

Isn't the delay method only for events that use the effects queue, like fading in and out, etc.?

Upvotes: 1

Related Questions