Home > Web Front-end > CSS Tutorial > How Can I Use jQuery to Show and Hide Divs at Set Intervals?

How Can I Use jQuery to Show and Hide Divs at Set Intervals?

Mary-Kate Olsen
Release: 2024-12-08 12:46:11
Original
196 people have browsed it

How Can I Use jQuery to Show and Hide Divs at Set Intervals?

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>
Copy after login

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() {...}
Copy after login

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();
Copy after login

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');
Copy after login

Increment or reset the counter to ensure the sequence repeats after reaching the last div.

counter == 3 ? counter = 0 : counter++;
Copy after login

Finally, start the timer using setInterval and set the desired time interval (5000 milliseconds in this case).

var timer = setInterval(showDiv, 5000);
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template