Changing the class of a div after a time delay
Solution 1
The delay
method adds an item to the animation queue, but as addClass
is not an animation effect, it's not put on the queue, it takes effect right away.
You can use the queue
method to put code in the animation queue, so that it runs after the delay:
$('#one').delay(10000).queue(function(){
$(this).addClass("one");
});
Demo: http://jsfiddle.net/6V9rX/
An alternative to use animation for the delay is to use the setTimeout
method:
window.setTimeout(function(){
$('#one').addClass("one");
}, 10000);
Solution 2
$(document).ready(function(){
window.setTimeout(function(){
$("#one").addClass("one");
},10000);
});
Solution 3
delay
only works on elements on jQuery's queue. Since addClass isn't an animation added to the queue by default, it runs immediately regardless of delay
. You should use Javascript's native setTimeout
for general delays:
$(function(){
setTimeout(function() {
$('#one').addClass("grow")
}, 10000);
});
Sam Friday Welch
Updated on July 09, 2022Comments
-
Sam Friday Welch almost 2 years
I am wanting add a class to a div element (id="one") 10 seconds after a page loads, without anything having to be hovered on or clicked on etc. I tried the following code but it does not work:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> $(document).ready(function(){ $('#one').delay(10000).addClass("grow") });
Any idea where the above code is going wrong?