Adding a class using jQuery after a delay

When the element is clicked, I want to add a class to the body element, but with a slight delay. Thus, element1 is clicked, and then after 0.5 seconds the body is the specified new class.

I used this, which works to the extent ...

$('.element1').click(function() { $('body').delay(500).queue(function(){ $(this).addClass('left-bg') }); }); 

However, I have another click event that removes this left-bg class from the body.

 $('.another-element').click(function() { $('body').removeClass('left-bg'); }); 

But then the next time you click the .element1 element, it will not apply the left-bg class to the body at all.

Hope this makes sense. Can someone help me with this or suggest another way to do this?

+7
jquery delay
source share
6 answers

Clear queue:

Demo

 $('.element1').click(function() { $('body').delay(500).queue(function(){ $(this).addClass('left-bg').clearQueue(); }); }); $('.another-element').click(function() { $('body').removeClass('left-bg'); }); 
+9
source share

you need to remove dequeue

 $('.element1').click(function() { $('body').delay(500).queue(function(){ $(this).addClass('left-bg'); $(this).dequeue() }); }); 

as mentioned here

+3
source share

You need to use .stop ()

 $('.element1').click(function() { $('body').stop().delay(500).queue(function(){ $(this).addClass('left-bg') }); }); 

Demo

0
source share

use this -

 var bgch; $('.element1').click(function() { bgch = setTimeout((function(){$('body').addClass('left-bg');}),500); }); $('.another-element').click(function() { $('body').removeClass('left-bg'); clearTimeout(bgch); }); 
0
source share

Please keep in mind that your delay may cause a problem : - clicking on an element1 - clicking on another element - deleting a class - adding a class after a delay

In order for everything to work fine, you need to monitor what is happening, and you should also check if the class is already in the body element, so the class is not used twice

 var bodyClassTracker = 0; var handledClass = 'left-bg'; $('.element1').click(function() { bodyClassTracker = 1; $('body').delay(500).queue(function(){ var eleBody = $('body'); if (!eleBody.hasClass(handledClass)) eleBody.addClass(handledClass); bodyClassTracker = 0; eleBody.clearQueue(); }); }); $('.another-element').click(function() { var removerFun = function(){ var eleBody = $('body'); if (eleBody.hasClass(handledClass)) eleBody.removeClass(handledClass); eleBody.clearQueue(); }; if (bodyClassTracker == 1) $('body').delay(500).queue(removerFun); else removerFun(); }); 

Here you can test and demonstrate the code. http://jsfiddle.net/uTShk/3/

0
source share

You need to stop () the body after installing it.

 $('#add').click(function() { $('body').delay(500).queue(function(){ $(this).addClass('left-bg') }).stop(); }); $('#rem').click(function() { $('body').removeClass('left-bg'); }); 

Fiddle demo

0
source share

All Articles