To create a timed slideshow, you can utilize the setInterval
method along with setting the src
attribute of an img
element:
window.onload = function() {
var slides = [ "path_to_image_one",
"path_to_image_two",
"path_to_image_three" // ...
],
index = 0,
timer = 0;
// Display the initial slide
showNextSlide();
// Switch to the next slide every five seconds
timer = setInterval(showNextSlide, 5000);
// Function to display the next slide
function showNextSlide() {
if (index >= slides.length) {
index = 0;
}
document.getElementById('theImage').src = slides[index++];
}
};
Ensure your image markup is as follows:
<img id="theImage" src="path_to_initial_placeholder">
Keep in mind that the timer handle is stored in timer
, which can be used to cancel the timer if necessary to halt the slideshow.
Update: If you need to fetch images from a specific div instead of hardcoded paths, here's an updated version that dynamically populates the slides
array by extracting direct child IMG
elements from a div with the ID "theDiv":
window.onload = function() {
var slides = [],
index = 0,
timer = 0,
node;
// Retrieve the slides
for (node = document.getElementById('theDiv').childNodes;
node;
node = node.nextSibling) {
if (node.nodeType == 1 && node.tagName == "IMG") {
slides.push(node.src);
}
}
// Display the initial slide
showNextSlide();
// Switch to the next slide every five seconds
timer = setInterval(showNextSlide, 5000);
// Function to display the next slide
function showNextSlide() {
if (index >= slides.length) {
index = 0;
}
document.getElementById('theImage').src = slides[index++];
}
};