Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the class of a div after a time delay

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?

like image 782
Sam Friday Welch Avatar asked Nov 19 '13 19:11

Sam Friday Welch


People also ask

How to remove class in JavaScript after Some time?

removeClass() Method. This method removes one or more class names from the selected elements. If no parameter is specified in the removeClass() method, it will remove all class names from the selected elements.

How do you make a div appear after time?

To show an element after delay: Use the setTimeout() method to invoke a function after a delay. In the function, set the element's visibility property to visible . Pass the delay in milliseconds as the second parameter to the setTimeout method.

How do you add a delay to time in HTML?

The setTimeout() Methodwindow.setTimeout(function, milliseconds); The window.setTimeout() method can be written without the window prefix. The first parameter is a function to be executed. The second parameter indicates the number of milliseconds before execution.

Can you add a delay in JavaScript?

The standard way of creating a delay in JavaScript is to use its setTimeout method. For example: console. log("Hello"); setTimeout(() => { console.


1 Answers

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);
like image 86
Guffa Avatar answered Sep 30 '22 00:09

Guffa