jQuery Snippets: 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 completely 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.

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 .setTimeout() method.

var header = $('#header');
header.addClass('blue');
setTimeout(function() {
    header.removeClass('blue');
}, 4000);

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 that 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!



Responsive Menu
Add more content here...