Home >Web Front-end >CSS Tutorial >How Can I Use jQuery to Show Divs Sequentially at Set Time Intervals?
Automated Display of Divs at Specific Time Intervals using jQuery
jQuery offers a convenient way to manipulate HTML elements dynamically. In this specific case, we aim to show a sequence of divs ("div1", "div2", "div3") at predetermined intervals of 10 seconds each. After the initial delay, each div should be displayed in turn while the others remain hidden.
To achieve this:
Sample Code:
$('html').addClass('js'); // Add a class indicating JavaScript support $(function() { var timer = setInterval(showDiv, 5000); // Set up a timer to trigger every 5 seconds var counter = 0; // Initialize the counter function showDiv() { if (counter == 0) { // Skip the first iteration to introduce a 5-second delay counter++; return; } $('div', '#container') // Select all divs within the container .stop() // Stop any ongoing animations .hide() // Hide all divs .filter(function() { // Filter the divs by ID return this.id.match('div' + counter); // Check if the ID matches the current counter }) .show('fast'); // Show the matching div counter == 3 ? counter = 0 : counter++; // Increment the counter, or reset it to 0 if it reaches 3 } });
Conclusion:
By harnessing jQuery's setInterval and DOM manipulation capabilities, you can easily automate the display of elements on a website at specified time intervals, allowing for dynamic and engaging content.
The above is the detailed content of How Can I Use jQuery to Show Divs Sequentially at Set Time Intervals?. For more information, please follow other related articles on the PHP Chinese website!