JQuery - add a class and delete it after 500 ms

I want to add a class and delete it after 500 milliseconds. It does not work with a delay (). To give a simple example, I am doing this here with a background color:

code pen

JQuery

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

 $('.box').addClass("bg1").delay(500).removeClass("bg1");
});
+4
source share
6 answers

You can use timeoutfor this.

In your case: jsfiddle

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

    var self = $(this);

    self.addClass("bg1");

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

});
+8
source

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

Demo

$('.box').click(function () {
    $('.box').addClass("bg1").dequeue().delay(500).queue(function () {
        $(this).removeClass("bg1");
    });
});
+2
source

- jquery .

i.e

$('.box').click(function(){
        $('.box').addClass("bg1");
        setTimeout(function(){
            $('.box').removeClass("bg1");
        },500);
    });
+1

:

setTimeout(function() {
    // Do stuff
}, 500);
0
$('.box').click(function(){
 $('.box').addClass("bg1");
 setTimeout(function() {
    $('.box').removeClass("bg1")
 }, 500);
});

:

0

:

$('.box').click(function(){
    $('.box').addClass("bg1");
    setTimeout("$('.box').removeClass('bg1')", 500);
});
-1

All Articles