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?
jQuery delay() Method The delay() method sets a timer to delay the execution of the next item in the queue.
var header = $('#header'); header. addClass('blue'); setTimeout(function() { header. removeClass('blue'); }, 4000); The first line of the snippet establishes the variable header (var header will select the #header element), and the next line adds the blue class to the header element.
Free jQuery snippet to remove class from an element after delay of a few seconds. This snippet uses setTimeout function to delay the execution of the script. To remove class we simply use removeClass jQuery function.
Added to jQuery in version 1.4, the . delay() method allows us to delay the execution of functions that follow it in the queue. It can be used with the standard effects queue or with a custom queue. Only subsequent events in a queue are delayed; for example this will not delay the no-arguments forms of .
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');
});
you need to dequeue
$('.element1').click(function() {
$('body').delay(500).queue(function(){
$(this).addClass('left-bg');
$(this).dequeue()
});
});
as mentioned here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With