Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delayed addclass/remove class function not working

what am I doing wroing here?

$(function() {
$('ul li:nth-child(1)').addClass("go").delay(4500).removeClass("go");
$('ul li:nth-child(2)').addClass("go").delay(1500).removeClass("go");
$('ul li:nth-child(3)').addClass("go").delay(500).removeClass("go");
$('ul li:nth-child(4)').addClass("go").delay(4500).removeClass("go");
$('ul li:nth-child(5)').addClass("go").delay(1000).removeClass("go");
});
like image 684
Bizarro Zeldman Avatar asked Feb 10 '11 08:02

Bizarro Zeldman


2 Answers

Just to add, you can use a .queue:

$('ul li:nth-child(1)').addClass("go")
                       .delay(4500)
                       .queue(function() {
                           $(this).removeClass("go");
                           $(this).dequeue();
                       });
like image 141
karim79 Avatar answered Nov 14 '22 06:11

karim79


.delay() is only designed to work with animations. You'll have to resort to using regular setTimeouts for what you're doing:

var li = $('ul li:nth-child(1)').addClass('go');
setTimeout(function () {
    li.removeClass('go');
}, 4500);

To make doing this to every <li> a little more pleasant, you can refactor your code like so:

$(function () {
    var delays = [4500, 1500, 500, 4500, 1000];
    $('ul li').addClass('go').each(function (i) {
        setTimeout(function (li) {
            li.removeClass('go');
        }, delays[i], $(this));
    });
});
like image 17
David Tang Avatar answered Nov 14 '22 04:11

David Tang