How to Add/Remove Classes After Delay
This Article Is About How to Add/Remove Classes After Delay In your projects, there can often be instances of wanting to change something (color, size, font family, etc) about an element, but only after a certain amount of time has passed (the time passed can be anywhere from a millisecond to ten minutes to ten hours if you like — its entirely up to you and the needs of your project). In jQuery, it’s easy to change elements style or content based on a trigger event (click, for example, is a very common trigger even), but it’s also possible to use time passed as a trigger event of sorts.
Remove Classes After Delay
As an example, let’s say you have a class called “blue” applied to an element. The class changes the color of the text within any element to blue. If you have it applied to an element but want to remove it from an element after a designated amount of time has passed, you can do so by using jQuery’s
var header = $(‘#header’);
The first line of the snippet establishes the variable header (var header will select the #header element), and the next line adds the blue class to the header element. Then, the .setTimeout() method creates a function that will remove the blue class from the header element after 4000 milliseconds.
If you choose to use this snippet, keep in mind that you can set the time it takes until the class is removed to be anything you’d like — but remember that the increments are in milliseconds, not seconds. In the example above, 4000 milliseconds only equals 4 seconds, so make sure you know the conversion between milliseconds and seconds before setting your time. Also, don’t forget to change the variables, the element selectors, and the classes to reflect the actual names of the variables, elements, and classes within your project.
Conversely, you can also change this code around to ADD a class after a certain amount of milliseconds by swapping out the .removeClass() method for the .addClass() one. Play around with the code for yourself to see how it works!
Also Check Free JQuery Plugins