In this article:
CSS
#imageContainer {width: 300px;height: 300px;}
img {width: 100%;height: 100%;}
HTML
<div id="imageContainer">
<img id="loopingImage" src="" alt="Image Loop">
</div>
Javascript
// Array of image URLs
const images = [
'https://www.ivoicesoft.com/wp-content/uploads/img/loop1.jpg',
'https://www.ivoicesoft.com/wp-content/uploads/img/loop2.jpg',
'https://www.ivoicesoft.com/wp-content/uploads/img/loop3.jpg'
];
let currentIndex = 0;
// Function to change the image
function changeImage() {
const imgElement = document.getElementById('loopingImage');
imgElement.src = images[currentIndex];
currentIndex = (currentIndex + 1) % images.length;
}
// Change the image every 1 second
setInterval(changeImage, 1000);
// Initialize with the first image
changeImage();
This example includes:
- An array of image URLs (images).
- A function (changeImage) that updates the src attribute of the img element to display the current image and then increments the index.The setInterval function that calls changeImage every 1000 milliseconds (1 second).
- Initialization of the first image when the page loads.
- Replace ‘loop1.jpg’, ‘loop2.jpg, etc., with the actual paths or URLs to your images. This script will cycle through the images in the array every second.
Github & Pencode
https://codepen.io/audio4funTP/pen/YzbmZjX
https://github.com/audio4funTP/imageloops/blob/main/imageloops.htm