简体   繁体   中英

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!

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");
});

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

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");
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM