Can I delay jQuery addClass?

Ryan picture Ryan · Jan 29, 2011 · Viewed 23.8k times · Source

Is there a way to delay the addClass() of jQuery? For example this code

$('#sampleID').delay(2000).fadeOut(500).delay(2000).addClass('aNewClass');

When I load the page, it has the class 'aNewClass' already on id 'sampleID'. How to solve this problem? What I want is the addClass will happen after it ended the fadeOut().

Answer

Dave picture Dave · Feb 26, 2013

You can't directly delay an addClass call, however you can if you wrap it in a queue call which takes a function as a parameter like this

$(this).delay(2000).queue(function(){$(this).addClass('aNewClass')});

See this post: jQuery: Can I call delay() between addClass() and such?