jQuery: Can I call delay() between addClass() and such?
You can create a new queue item to do your removing of the class:
$("#div").addClass("error").delay(1000).queue(function(next){ $(this).removeClass("error"); next();});
Or using the dequeue method:
$("#div").addClass("error").delay(1000).queue(function(){ $(this).removeClass("error").dequeue();});
The reason you need to call next
or dequeue
is to let jQuery know that you are done with this queued item and that it should move on to the next one.
I know this this is a very old post but I've combined a few of the answers into a jQuery wrapper function that supports chaining. Hope it benefits someone:
$.fn.queueAddClass = function(className) { this.queue('fx', function(next) { $(this).addClass(className); next(); }); return this;};
And here's a removeClass wrapper:
$.fn.queueRemoveClass = function(className) { this.queue('fx', function(next) { $(this).removeClass(className); next(); }); return this;};
Now you can do stuff like this - wait 1sec, add .error
, wait 3secs, remove .error
:
$('#div').delay(1000).queueAddClass('error').delay(2000).queueRemoveClass('error');