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()
.
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.
You should use callbacks .
$('#sampleID').delay(2000).fadeOut(500,function(){
$(this).delay(2000).addClass('aNewClass');
});
http://api.jquery.com/fadeOut/
You can also use setTimeout, with CSS transition :
setTimeout(function() {
$('#sampleID').addClass('aNewClass');
}, 2000);
And the CSS
#sampleID {
transition: opacity 1s ease;
opacity: 0;
}
#sampleID.aNewClass {
opacity: 1;
}