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()
.
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);
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.
To call a jQuery function after a certain delay, use the siteTimeout() method. Here, jQuery fadeOut() function is called after some seconds.
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.
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');
});
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?
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.
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