Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a class using jQuery after a delay

Tags:

jquery

delay

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?

like image 249
user2586455 Avatar asked Jul 26 '13 10:07

user2586455


People also ask

What is the use of delay () method in jQuery?

jQuery delay() Method The delay() method sets a timer to delay the execution of the next item in the queue.

How do I add a class to a delay?

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.

How do you remove a class after some time?

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.

Is delay event method in jQuery?

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 .


2 Answers

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');
});
like image 176
A. Wolff Avatar answered Oct 06 '22 06:10

A. Wolff


you need to dequeue

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

as mentioned here

like image 37
Parv Sharma Avatar answered Oct 06 '22 05:10

Parv Sharma