jQuery: Can I call delay() between addClass() and such?
Something as simple as:
$("#div").addClass("error").delay(1000).removeClass("error");
doesn't seem to work. What would be the easiest alternative?
Solution 1:
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.
Solution 2:
AFAIK the delay method only works for numeric CSS modifications.
For other purposes JavaScript comes with a setTimeout method:
window.setTimeout(function(){$("#div").removeClass("error");}, 1000);