4

This is my code:

   $("#form_editor").addClass('abcd')
   $("#form_editor").delay(32000).removeClass('abcd')

The class never gets applied if I have the second line uncommented. If I comment it out, then the class gets applied as expected. It seems that the second line executes without any delay at all i.e. ignores .delay(32000).

Does delay work with addClass and removeClass? I assumed it would delay the call to any function that came after it, but apparently not as it seems to execute right away.

Zze
  • 18,229
  • 13
  • 85
  • 118
niko craft
  • 2,893
  • 5
  • 38
  • 67
  • 1
    You have to queue it. Why not just use a good ol' fashioned setTimeout()? – Drew Kennedy Apr 03 '17 at 22:46
  • 1
    Possible duplicate of [jQuery: Can I call delay() between addClass() and such?](http://stackoverflow.com/questions/2510115/jquery-can-i-call-delay-between-addclass-and-such) – Drew Kennedy Apr 03 '17 at 22:49

1 Answers1

8

You can, but you need to 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 setTimeout method:

var $formEditor = $("#form_editor"); // we plan to reuse it so let's 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 jQuery internal function than handles "what's next?" (laically speaking), while other "animation-less" methods (like .text(), addClass(), .on(), .click() etc...) do not.

To easily remember .queue() think of it as the missing (really is) callback functionality for .delay(2000, function(){ /*BAM!*/ }) /* well sadly, this does not works */

Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313