Web Front-end
HTML Tutorial
JavaScript regularly switches CSS classes to achieve dynamic interface effects
JavaScript regularly switches CSS classes to achieve dynamic interface effects

This article will guide you on how to use JavaScript's `setTimeout` function, combined with CSS class operations, to automatically switch styles or states of page elements after a specific time, such as hiding or displaying a pop-up window at a scheduled time. This method can create dynamic and user-friendly interactive effects without refreshing the page, improving the responsiveness and user experience of the web page.
In modern web development, dynamic user interface (UI) is the key to improving user experience. Sometimes we need to allow an element to briefly change state (such as hiding) after user interaction, and then automatically restore it to its original state after a specified time without reloading the page. This article will introduce in detail how to use JavaScript's setTimeout function and CSS class operations to achieve this function.
Core concepts: CSS class operations and JavaScript timers
To achieve dynamic state switching of elements, we need to master two core technologies:
-
CSS class operation (Element.classList) : JavaScript provides the Element.classList interface to manage the CSS classes of elements. Commonly used methods include:
- classList.add(className): Add one or more CSS classes.
- classList.remove(className): Remove one or more CSS classes.
- classList.toggle(className): Remove the class if it exists, add it if it does not exist. By adding or removing specific CSS classes, we can easily switch the style and visibility of elements.
JavaScript timer (setTimeout) : setTimeout(function, delay) is a global function that executes a function after a specified number of milliseconds (delay). It returns a timer ID, which can be used to cancel the execution of the timer through the clearTimeout() function.
Combining these two concepts, we can implement the logic of changing the state immediately after clicking and automatically restoring after a certain period of time.
Implementation steps and code examples
Suppose we have a popup element that is visible by default. When the user clicks the "Close" button, we want the popup to hide immediately and automatically redisplay after 2 seconds.
1. HTML structure
First, define the HTML structure of the pop-up window. To achieve separation of behavior from structure, we will no longer use inline onclick events, but add event listeners via JavaScript.
<div class="pupuppro"> <h1 class="text">Hello world! </h1> <i id="proo">Close</i> </div>
2. CSS style
Next, define the default style of the pop-up window and the style when hidden. We use the .pupuppro class as the default style and the .pupuppro.active class to represent the hidden state. To make the transition smoother, we combine the opacity and visibility properties and add a CSS transition.
.pupuppro {
background: #0000007a;
position: absolute;
top: 0;
bottom: 0;
left: 0;
width: 50%;
height: 50%;
border: 0;
z-index: 9999;
color: #fff;
display: flex;
justify-content: center;
align-items: center;
visibility: visible; /* Visible by default */
opacity: 1; /* Fully opaque by default*/
/* Add transition effect: opacity transition 0.3s, visibility becomes visible immediately after the opacity transition ends */
transition: opacity 0.3s ease-in-out, visibility 0s linear 0.3s;
}
.pupuppro.active {
visibility: hidden; /* hide*/
opacity: 0; /* completely transparent */
/* When hiding: opacity transitions for 0.3s, visibility immediately changes to hidden */
transition: opacity 0.3s ease-in-out, visibility 0s linear;
}
#proo {
position: absolute;
cursor: pointer;
top: 10px;
right: 25px;
color: red;
width: 50px;
height: 50px;
font-size: xx-large;
}
3. JavaScript logic: use setTimeout to implement scheduled recovery
Now, we write JavaScript code to handle click events and scheduled recovery logic.
document.addEventListener('DOMContentLoaded', () => {
const popupElement = document.querySelector(".pupuppro");
const closeButton = document.getElementById("proo");
let timerId = null; // Used to store the timer ID so that it can be cleared when needed/**
*Function that handles pop-up window closing and scheduled recovery* @param {number} delayMilliseconds After the pop-up window is hidden, how many milliseconds will it take for it to become visible again*/
function handleCloseAndTimedReopen(delayMilliseconds) {
// Before setting a new timer, clear any old timers that may exist // This can prevent multiple timers from running at the same time and causing logical confusion when there are multiple clicks in a short period of time if (timerId !== null) {
clearTimeout(timerId);
timerId = null;
}
// 1. Immediately add the 'active' class and hide the pop-up window according to CSS popElement.classList.add("active");
// 2. Set the timer, remove the 'active' class after the specified delay, and make the pop-up window visible again timerId = setTimeout(() => {
popupElement.classList.remove("active");
timerId = null; // After the timer is executed, reset the ID to null
}, delayMilliseconds);
}
//Add a click event listener for the close button closeButton.addEventListener('click', () => {
handleCloseAndTimedReopen(2000); // Set 2 seconds (2000 milliseconds) before the pop-up window becomes visible});
});
Complete sample code
Combining the above HTML, CSS, and JavaScript code together results in a complete, runnable example:
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript regularly switches CSS classes</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
background-color: #f0f0f0;
}
.pupuppro {
background: #0000007a;
position: absolute;
top: 0;
bottom: 0;
left: 0;
width: 100%; /* Set to full screen in the example*/
height: 100%; /* Set to full screen in the example*/
border: 0;
z-index: 9999;
color: #fff;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
visibility: visible;
opacity: 1;
transition: opacity 0.3s ease-in-out, visibility 0s linear 0.3s;
}
.pupuppro.active {
visibility: hidden;
opacity: 0;
transition: opacity 0.3s ease-in-out, visibility 0s linear;
}
.pupuppro h1 {
margin-bottom: 20px;
}
#proo {
position: absolute;
cursor: pointer;
top: 20px;
right: 30px;
color: red;
width: 50px;
height: 50px;
font-size: xx-large;
display: flex;
justify-content: center;
align-items: center;
background-color: rgba(255, 255, 255, 0.2);
border-radius: 50%;
}
</style>
<div class="pupuppro">
<h1 class="text">Hello world! </h1>
<i id="proo">X</i> <!-- It is more concise to use X instead of close-->
</div>
<script>
document.addEventListener('DOMContentLoaded', () => {
const popupElement = document.querySelector(".pupuppro");
const closeButton = document.getElementById("proo");
let timerId = null; // Used to store the timer ID so that it can be cleared when needed/**
*Function that handles pop-up window closing and scheduled recovery* @param {number} delayMilliseconds After the pop-up window is hidden, how many milliseconds will it take for it to become visible again*/
function handleCloseAndTimedReopen(delayMilliseconds) {
// Make sure to clear any old timers that may exist before setting a new timer if (timerId !== null) {
clearTimeout(timerId);
timerId = null;
}
// 1. Immediately add the 'active' class and hide the pop-up window according to CSS popElement.classList.add("active");
// 2. Set the timer, remove the 'active' class after the specified delay, and make the pop-up window visible again timerId = setTimeout(() => {
popupElement.classList.remove("active");
timerId = null; // After the timer is executed, reset the ID to null
}, delayMilliseconds);
}
//Add a click event listener for the close button closeButton.addEventListener('click', () => {
handleCloseAndTimedReopen(2000); // Set 2 seconds (2000 milliseconds) before the pop-up window becomes visible});
});
</script>
Things to note and best practices
- Event listener : It is recommended to use addEventListener instead of inline onclick. addEventListener allows multiple event handlers to be registered for the same element and the same event type, and helps separate JavaScript behavior from HTML structure, making code easier to maintain and debug.
- setTimeout and setInterval :
- setTimeout executes the specified function only once.
- setInterval(function, delay) will execute the function repeatedly every delay milliseconds until canceled by clearInterval(). Choose the appropriate timer based on your needs. In this case, we only need a one-time delay, so setTimeout is the right choice.
- Importance of clearTimeout : Although clearTimeout may not seem necessary in some simple scenarios, it is a very important best practice.
- Prevent duplicate execution : If the user triggers the event again before the timer completes, not clearing the old timer will cause multiple timers to run at the same time, which may produce unexpected behavior.
- Resource management : Timely clearing timers that are no longer needed can avoid unnecessary memory usage and CPU cycle consumption.
- User experience :
- Delay time : Choosing the right delay time is crucial. A delay that is too short may make it difficult for users to detect status changes, and a delay that is too long may make users wait. Adjust according to specific scenarios and user expectations.
- CSS transition : Combined with the transition attribute, the display/hiding process of elements can be made smoother and more professional, avoiding abrupt instantaneous switching.
- Variable scope : In JavaScript, use const and let to declare variables to better manage scope and avoid global pollution.
Summarize
By cleverly combining JavaScript's setTimeout function and CSS class operations, we can easily implement scheduled state switching of page elements, providing users with a more dynamic and friendly interactive experience. Mastering these techniques can not only solve specific problems, but also lay a solid foundation for building more complex dynamic UI effects. In actual projects, be sure to pay attention to code maintainability, performance, and user experience.
The above is the detailed content of JavaScript regularly switches CSS classes to achieve dynamic interface effects. For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undress AI Tool
Undress images for free
AI Clothes Remover
Online AI tool for removing clothes from photos.
Undresser.AI Undress
AI-powered app for creating realistic nude photos
ArtGPT
AI image generator for creative art from text prompts.
Stock Market GPT
AI powered investment research for smarter decisions
Hot Article
Popular tool
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
20522
7
13634
4
Solve the problem of unexpected offset of Flex container due to the font size change of the first child element
Mar 09, 2026 pm 08:15 PM
When the first child element of a Flex container dynamically adjusts the font-size, the container will be vertically offset along the inline baseline; while a normal block-level container will change in height due to the linkage between line height and font measurement. The root cause lies in the baseline alignment mechanism of the Flex container. By default, the baseline of the first child is the container baseline. This can be completely solved through vertical-align: top or explicit baseline control.
A complete guide to using the keyboard to control the smooth movement of HTML elements
Mar 13, 2026 pm 10:18 PM
This article explains in detail why transform: translate() combined with the keydown event cannot move elements, and provides a reliable solution based on CSS positioning and JavaScript, covering absolute positioning settings, coordinate update logic, code robustness optimization, and common pitfalls.
Chart.js complete implementation solution for dynamically switching chart types (line chart, bar chart, pie chart)
Mar 12, 2026 pm 08:51 PM
This article explains in detail how to safely and reliably dynamically switch chart types (line/bar/pie) in Chart.js, and solve the problem of Cannot read properties of undefined errors caused by mismatched data structures and rendering exceptions after type switching. The core lies in destroying old instances, deep copying configurations, and accurately rebuilding data structures by type.
How to optimize Lighthouse image scoring while maintaining high image quality
Mar 11, 2026 pm 09:39 PM
This article explores why providing 2x images to high DPR devices may lower Lighthouse performance scores, and provides practical solutions to balance visual quality and real performance: including proper srcset configuration, image compression strategies, modern format selection, and load priority control.
How to dynamically pass HTML form data to analytics.track() method
Mar 13, 2026 pm 10:57 PM
This article explains in detail how to safely and efficiently extract user input from HTML forms and structure it into JavaScript objects as attribute parameters of analytics.track() to avoid hard coding and syntax errors and support flexible expansion.
How to properly override default styles and implement custom CSS layouts in Divi theme builder
Mar 14, 2026 am 12:00 AM
This article explains in detail the root cause of style failure when applying custom CSS in the WordPress Divi theme builder. It provides practical solutions for improving selector specificity, accurately positioning elements, and rational use of !important, as well as debugging tips and code optimization examples.
How to add prompt copy for disabled button click
Mar 30, 2026 pm 04:30 PM
This article introduces a complete solution for disabling the "Next" button when the form does not meet the conditions, and using native HTML5 form validation or JavaScript dynamic control to display a friendly prompt message when the disabled button is clicked.
How to switch images by clicking a button (elegant implementation based on jQuery)
Apr 04, 2026 pm 08:06 PM
This article introduces how to use jQuery to dynamically switch background images after button clicks, and corrects problems such as CSS selector misuse, inline event coupling, and logical redundancy in the original code, providing a concise and maintainable interaction solution.





