Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why can't I delay addClass and removeClass using jquery?

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.

like image 918
niko craft Avatar asked Feb 04 '23 18:02

niko craft


1 Answers

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 */

like image 96
Roko C. Buljan Avatar answered Feb 07 '23 07:02

Roko C. Buljan