3

How do I delay the removal of a css class in jQuery?

Here is my code

$(this).addClass("uk-form-danger").delay(5000).removeClass("uk-form-danger");

The above code does nothing. I can add the class with the following code

$(this).addClass("uk-form-danger");

and I can remove it with

$(this).removeClass("uk-form-danger");

but I can't delay the removal of the class.

0

5 Answers 5

4

You can easily accomplish that with a setTimeout:

var myItem = $(this);

myItem.addClass("uk-form-danger");
setTimeout( function(){ myItem.removeClass("uk-form-danger"); }, 5000 );
Sign up to request clarification or add additional context in comments.

Comments

3

jquery delay is only intended to use with animations, you will not be able to delay the removeClass this way, use setTimeout instead:

var $el = $('#myId');
$el .addClass("uk-form-danger")
setTimeout(function(){
    $el .removeClass("uk-form-danger");
}, 5000);

Comments

1

Try something like this using setTimeout

var self = $(this);
self.addClass('uk-form-danger');
setTimeout(function () {
    self.removeClass('uk-form-danger');
}, 5000);

1 Comment

This wont work. What do you thing 'this' is inside the timeout function's scope?
1

Have you tried using setTimeout instead of delay?

var myObject = $(this);

myObject.addClass("uk-form-danger");

setTimeout(function()
{
    myObject.removeClass("uk-form-danger");
}, 5000);

3 Comments

This wont work. What do you thing 'this' is inside the timeout function's scope?
Then you just create a variable and store it there, then refer to it likeso: var myObject = $(this); myObject.removeClass("uk-form-danger");
Well... that would be correct. But your answer is not doing that.
0

The easiest way is to use jQueryUI.

.delay() only works for methods in the effects queue. You need to place your .addClass() and .removeClass() into the default effects queue by including a duration.

$(this).addClass("uk-form-danger", 250).delay(5000).removeClass("uk-form-danger", 250);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.