Add a class using jQuery after a delay
delay, jquery
Solution
Clear the queue:
DEMO
$('.element1').click(function() {
$('body').delay(500).queue(function(){
$(this).addClass('left-bg').clearQueue();
});
});
$('.another-element').click(function() {
$('body').removeClass('left-bg');
});
Problem
When an element is clicked, I want to add a class to the body element, but with a slight delay. So, element1 is clicked, then after .5 seconds, the body is a given a new class. I was using this which works to an extent... ``` $('.element1').click(function() { $('body').delay(500).queue(function(){ $(this).addClass('left-bg') }); }); ``` However, I have another click event which removes this left-bg class from body. ``` $('.another-element').click(function() { $('body').removeClass('left-bg'); }); ``` But then the next time .element1 is clicked, it doesn't apply the left-bg class to the body at all. Hope that makes sense. Can anybody help me with this or suggest another way of going about it?