Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - add a class and remove it after 500ms [duplicate]

Tags:

html

jquery

css

I want to add a class and remove it after 500 miliseconds. It does not work with delay(). To give an simple example I do it here with a background-color:

code pen

jQuery

$('.box').click(function(){

 $('.box').addClass("bg1").delay(500).removeClass("bg1");
});
like image 626
user2952265 Avatar asked Dec 19 '22 20:12

user2952265


2 Answers

You can use a timeout for this.

In your case: jsfiddle

$('.box').on('click', function(){

    var self = $(this);

    self.addClass("bg1");

    setTimeout(function(){
        self.removeClass("bg1");
    }, 500);

});
like image 127
damian Avatar answered Jan 05 '23 03:01

damian


Use a timeout or if using delay, you need to put it in queue:

DEMO

$('.box').click(function () {
    $('.box').addClass("bg1").dequeue().delay(500).queue(function () {
        $(this).removeClass("bg1");
    });
});
like image 40
A. Wolff Avatar answered Jan 05 '23 04:01

A. Wolff