Home » Code editor » How to display loop-images by JavaScript

How to display loop-images by JavaScript

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

Get Giveaway every day!

Check Also

Understanding User Interactions: A Customer Journey Map Example

In the realm of strategic business tools, the customer journey map stands tall as a …

IOS update

Fix iPhone Activation Issue after iOS 17 Update

The experience of owning Apple’s flagship device, which is known for its strong security measures …