user2961861
user2961861

Reputation:

How to use delay to add/remove classes

Inside the .click(function () {}); I am trying t oget it to remove a class, add another, delay a second, then reverse everything again. It seems so simple to me yet I am stumped on this broken function:

$(document).ready(function() {
    var items = $(".tabs-group .sidebar ul li:not(:last-child) a");
    var prompt = $(".prompt-button");
    prompt.click(function () {
        $(items).removeClass("pulse").addClass("solid").delay(1000).removeClass("solid").addClass("pulse");
    });
});

Help appreciated, thanks!

Upvotes: 0

Views: 166

Answers (3)

Karl-André Gagnon
Karl-André Gagnon

Reputation: 33870

Even though PSL answer is probably the best solution, here an alternative. You could create you own delay function since .delay() work only on queued elements.

Here an example :

(function($){
    if($ && !$.fn.wait){
        $.fn.wait = function(time, fn){
            setTimeout(fn.bind(this), time);
            return this;
        }
    }
})(jQuery)

After inserting this in your files, you could call it like that :

$(items).removeClass("pulse").addClass("solid").wait(1000, function(){
     this.removeClass('solid');
})

See the code in action

Upvotes: 1

Sadako
Sadako

Reputation: 352

You have an extra $ in items

$(document).ready(function() {
    var items = $(".tabs-group .sidebar ul li:not(:last-child) a");
    var prompt = $(".prompt-button");
    prompt.click(function () {
        items.removeClass("pulse").addClass("solid").delay(1000).removeClass("solid").addClass("pulse");
    });
});

Upvotes: 0

PSL
PSL

Reputation: 123739

Try placing the subsequent operation in the queue. Otherwise removeClass, addClass is not added to FX queues to have it delayed by applying delay directly.

$(items).removeClass("pulse").addClass("solid").delay(1000).queue(function(){
                               $(this).removeClass("solid").addClass("pulse");
});

You could do:

$(items).toggleClass("pulse solid").delay(1000).queue(function(){
                               $(this).toggleClass("pulse solid");
});

Upvotes: 2

Related Questions