delayed addclass/remove class function not working
Asked Answered
P

2

14

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");
});
Paresh answered 10/2, 2011 at 8:24 Comment(2)
Little explanation would be handy. I'm guessing you're trying to change the class of a list in a specific order by setting it after a different delay for each item. What bit doesn't work?Erectile
.delay() only delays animations, not functionsVintage
G
42

Just to add, you can use a .queue:

$('ul li:nth-child(1)').addClass("go")
                       .delay(4500)
                       .queue(function() {
                           $(this).removeClass("go");
                           $(this).dequeue();
                       });
Gorgerin answered 10/2, 2011 at 8:32 Comment(3)
Ah I forgot about this +1. Don't forget to .dequeue() or next() though!Tonsure
Its still the same issue - the classes get added to the list items at the same time...then they are removed at different times check: jsfiddle.net/bM6uY/8Paresh
@BizarroZeldman That fiddle seems to demonstrate exactly the behavior that I would expect, given that the delay set for each li has a different value.Krysta
T
17

.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));
    });
});
Tonsure answered 10/2, 2011 at 8:28 Comment(2)
I'm creating an animation where I will have a bunch of list items 'display : none; I then need to add a class to each list item, one at a time, for a pre-determined amount of time, only after the time has passed is the class removed and added to the next list item. At which point the same class will be added to the next list item for a completely different amount of predetermined time. for a sParesh
thx, it kinda works... if you look you see that all the classes are applied at the same instant (they all turn blue at exactly the same time) then they all fade away at different intervals. I need the class to be applied to only one list item, once the time has passed, THEN its applied to the next list itemParesh

© 2022 - 2024 — McMap. All rights reserved.