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.

Sparky
  • 823
  • 1
  • 11
  • 17

5 Answers5

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 );
Scott 'scm6079'
  • 1,517
  • 13
  • 25
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);
taxicala
  • 21,408
  • 7
  • 37
  • 66
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);
CristianHG
  • 442
  • 5
  • 16
1

Try something like this using setTimeout

var self = $(this);
self.addClass('uk-form-danger');
setTimeout(function () {
    self.removeClass('uk-form-danger');
}, 5000);
Lumi Lu
  • 3,289
  • 1
  • 11
  • 21
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);

rocky
  • 116
  • 4