Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I delay jQuery addClass?

Is there a way to delay the addClass() of jQuery? For example this code

$('#sampleID').delay(2000).fadeOut(500).delay(2000).addClass('aNewClass');

When I load the page, it has the class 'aNewClass' already on id 'sampleID'. How to solve this problem? What I want is the addClass will happen after it ended the fadeOut().

like image 324
Ryan Avatar asked Jan 29 '11 09:01

Ryan


People also ask

How to set delay in jQuery?

The delay() method is an inbuilt method in jQuery that is used to set a timer to delay the execution of the next item in the queue. Syntax: $(selector). delay(para1, para2);

How to delay jQuery animation?

To delay execution of animation, use . delay() method which allows to delay the execution of functions that follow it in the queue. It accepts duration as parameter. Durations are given in milliseconds; higher values indicate slower animations, not faster ones.

How to call function with delay in jQuery?

To call a jQuery function after a certain delay, use the siteTimeout() method. Here, jQuery fadeOut() function is called after some seconds.

How to add and remove class in jQuery with 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.


3 Answers

What I want is the addClass will happen after it ended the fadeOut().

You can use callback function to fadeOut like this:

$('#sampleID').fadeOut(500, function(){
  $(this).addClass('aNewClass');
});
like image 104
Sarfraz Avatar answered Nov 16 '22 03:11

Sarfraz


You can't directly delay an addClass call, however you can if you wrap it in a queue call which takes a function as a parameter like this

$(this).delay(2000).queue(function(){$(this).addClass('aNewClass')});

See this post: jQuery: Can I call delay() between addClass() and such?

like image 45
Dave Avatar answered Nov 16 '22 04:11

Dave


You can't do this with delay because it only affects the effects queue. It doesn't "pause" execution of later code if it is not implemented using the queue.

You need to do this with setTimeout:

$('#sampleID').delay(2000).fadeOut(500, function() {
    setTimeout(function() {
        $(this).addClass('aNewClass');
    }, 2000);
});

This uses the complete callback of fadeOut and then sets a function to execute 2 seconds in the future.

like image 20
lonesomeday Avatar answered Nov 16 '22 03:11

lonesomeday