admin管理员组

文章数量:1200789

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=".10.2/jquery.min.js"></script>


$(document).ready(function(){
$('#one').delay(10000).addClass("grow")
});

Any idea where the above code is going wrong?

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?

Share Improve this question asked Nov 19, 2013 at 19:07 Sam Friday WelchSam Friday Welch 2552 gold badges4 silver badges14 bronze badges 4
  • .delay() is not a replacement for JavaScript's native setTimeout function – Teemu Commented Nov 19, 2013 at 19:10
  • .delay() only works in the context of jQuery animations. Just use setTimeout(). – adamb Commented Nov 19, 2013 at 19:11
  • $('#one').delay(10000).queue(function(){$(this).addClass("grow");}) jsfiddle.net/9k4vw or use a timeout – A. Wolff Commented Nov 19, 2013 at 19:12
  • possible duplicate of jQuery: Can I call delay() between addClass() and such? – epascarello Commented Nov 19, 2013 at 19:14
Add a comment  | 

3 Answers 3

Reset to default 14

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);

DEMO

$(document).ready(function(){
    window.setTimeout(function(){
        $("#one").addClass("one");
    },10000);
});

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);
});

jsfiddle

本文标签: javascriptChanging the class of a div after a time delayStack Overflow