7

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?

Sam Friday Welch
  • 265
  • 2
  • 4
  • 14
  • [`.delay()` is not a replacement for JavaScript's native `setTimeout` function](http://api.jquery.com/delay/) – Teemu Nov 19 '13 at 19:10
  • `.delay()` only works in the context of jQuery animations. Just use `setTimeout()`. – adamb Nov 19 '13 at 19:11
  • `$('#one').delay(10000).queue(function(){$(this).addClass("grow");})` http://jsfiddle.net/9k4vw/ or use a timeout – A. Wolff Nov 19 '13 at 19:12
  • possible duplicate of [jQuery: Can I call delay() between addClass() and such?](http://stackoverflow.com/questions/2510115/jquery-can-i-call-delay-between-addclass-and-such) – epascarello Nov 19 '13 at 19:14

3 Answers3

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);
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
4

DEMO

$(document).ready(function(){
    window.setTimeout(function(){
        $("#one").addClass("one");
    },10000);
});
kei
  • 20,157
  • 2
  • 35
  • 62
2

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

joews
  • 29,767
  • 10
  • 79
  • 91