Show and Hide Divs at a Specific Time Interval Using jQuery
By leveraging the jQuery setInterval function, it's possible to display divs at predefined intervals and control their visibility in a sequence. Here's a detailed overview of the steps involved:
Code Implementation:
Begin by defining your HTML structure, creating three divs (div1, div2, div3) and hiding them initially.
<div>
In your JavaScript code, create a function called showDiv() to control the display of divs. Within this function, use the counter variable to iterate through the divs and show them one at a time.
function showDiv() {...}
Initialize a counter to track the current div and use the jQuery stop() function to cancel any ongoing animations.
var counter = 0; $('div', '#container').stop().hide();
To display the current div, use jQuery's filter() function to select the appropriate div based on the counter, and then show it using show('fast').
.filter(function() {...}).show('fast');
Increment or reset the counter to ensure the sequence repeats after reaching the last div.
counter == 3 ? counter = 0 : counter++;
Finally, start the timer using setInterval and set the desired time interval (5000 milliseconds in this case).
var timer = setInterval(showDiv, 5000);
This solution offers a flexible and customizable way to show and hide divs at specific time intervals, making it suitable for scenarios where sequential or timed display is required.
The above is the detailed content of How Can I Use jQuery to Show and Hide Divs at Set Intervals?. For more information, please follow other related articles on the PHP Chinese website!