Why can't I defer addClass and removeClass with jquery?
This is my code:
$("#form_editor").addClass('abcd')
$("#form_editor").delay(32000).removeClass('abcd')
The class never gets applied if I have a second line uncommented . If I comment this out, the class is applied as expected. The second line seems to be executed without any delay, i.e. ignores .delay(32000)
.
Delay works with addClass
and removeClass
? I assumed this would delay any function call that came after it, but apparently not in the way it seems to be executed immediately.
source to share
You can, but you need queue()
$("#form_editor").addClass('abcd').delay(3200).queue(function() {
$(this).removeClass('abcd');
});
.abcd:before{
content:"abcd";
background:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="form_editor">efgh....</div>
or use the method setTimeout
:
var $formEditor = $("#form_editor"); // we plan to reuse it so let cache it!
$formEditor.addClass('abcd'); // add
setTimeout(function(){
$formEditor.removeClass('abcd'); // remove
}, 3200);
.abcd:before{
content:"abcd";
background:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="form_editor">efgh....</div>
jQuery animations (.animate, .fadeTo, fadeIn, etc.) add to the animation queue stack, an internal jQuery function than handle "what's next?" (latim), while other "no animation" methods (such as .text (), addClass (),. on (),. click (), etc.) do not.
To make it easy to remember .queue()
, think of it as a (really) missing callback function for.delay(2000, function(){ /*BAM!*/ }) /* well sadly, this does not works */
source to share