How to Create and Iterate Array of Images in JavaScript

  1. Use Array Objects to Show an Array of Images in JavaScript
  2. Use Arrays to Show an Array of Images in JavaScript
  3. Use HTML Templates to Show an Array of Images in JavaScript
  4. Use Modern JavaScript (ES6) Features to Show an Array of Images in JavaScript
  5. Conclusion
How to Create and Iterate Array of Images in JavaScript

In this tutorial, we’ll cover various approaches on how to create an array of images using JavaScript, from basic methods to modern ES6 features. Let’s delve into these methods and understand how they enable effective image handling and display.

ADVERTISEMENT

Use Array Objects to Show an Array of Images in JavaScript

First, let’s examine a coding example demonstrating the use of JavaScript’s array objects to effectively create an array of images.

HTML Code:

HTML
 htmlCopy<!DOCTYPE html>
<html>
<head>
    <!-- Link to the JavaScript file -->
    <script src="./javascript/imageArray.js"></script>

    <!-- Link to the CSS file -->
    <link rel="stylesheet" href="./css/styles.css">

    <!-- Title of the webpage -->
    <title>Image Iteration</title>
</head>
<body>
    <!-- Heading for user instruction -->
    <h1>Click to see the next image</h1>

    <!-- Container for the main image -->
    <div id="splash">
        <img src="./images/splash class room image.jpg" alt="classroom image" id="mainImage">
    </div>

    <!-- Controls for navigating between images -->
    <div id="controls">
        <button id="previousbtn" onclick="previousImage()">Previous Image</button>
        <button id="nextbtn" onclick="nextImage()"> Next Image</button>
    </div>
</body>
</html>

CSS Code:

CSS
 cssCopy/* CSS for styling images */
img {
    width: 350px;
    height: 350px;
}
#previousbtn {
    margin-right: 75px; /* Add right margin to the previous button */
}
#nextbtn {
    margin-left: 75px; /* Add left margin to the next button */
}

JavaScript Code:

JavaScript
 javascriptCopyvar imgArray = new Array();

imgArray[0] = new Image();
imgArray[0].src = './images/splash class room image.jpg';

imgArray[1] = new Image();
imgArray[1].src = './images/splash animal image.jpg';

imgArray[2] = new Image();
imgArray[2].src = './images/splash nature image.jpg';

imgArray[3] = new Image();
imgArray[3].src = './images/splash food image.jpg';

imgArray[4] = new Image();
imgArray[4].src = './images/splash travel image.jpg';

function nextImage() {
  var img = document.getElementById('mainImage');
  for (var i = 0; i < imgArray.length; i++) {
    if (imgArray[i].src == img.src) {
      if (i === imgArray.length) {
        document.getElementById('mainImage').src = imgArray[0].src;
        break;
      }
      document.getElementById('mainImage').src = imgArray[i + 1].src;
      break;
    }
  }
}

function previousImage() {
  var img = document.getElementById('mainImage');
  for (var i = imgArray.length - 1; i >= 0; i--) {
    if (imgArray[i].src == img.src) {
      if (i === imgArray.length) {
        document.getElementById('mainImage').src = imgArray[4].src;
        break;
      }
      document.getElementById('mainImage').src = imgArray[i - 1].src;
      break;
    }
  }
}

Output:

javascript array of images - image iteration using object

In the JavaScript code, we have an array named imgArray created to store Image objects. Image objects are created, and their sources are assigned to elements in the imgArray.

We also have the nextImage() function designed to display the next image in the slideshow. It retrieves the current image element, loops through the image array to find the index of the current image, and then displays the next image in the array.

If the current image is the last one, it wraps around the first image.

The previousImage() function is similar to the nextImage(), but it displays the previous image in the slideshow. It retrieves the current image element, loops through the image array in reverse order to find the index of the current image, and then displays the previous image in the array.

If the current image is the first one, it wraps around the last image.

Both functions (nextImage() and previousImage()) essentially handle the logic for navigating through the images in a slideshow, either moving forward to the next image or backward to the previous one. The wrapping behavior ensures a seamless transition from the last image to the first (and vice versa).

The functions utilize the HTML DOM to update the src attribute of an image element to change the displayed image.

Use Arrays to Show an Array of Images in JavaScript

We can also use JavaScript arrays to present a sequence of images seamlessly to users. See the coding example below:

HTML Code:

HTML
 htmlCopy<!DOCTYPE html>
<html>
<head>
    <!-- Link to the JavaScript file -->
    <script src="./javascript/imageArray.js"></script>

    <!-- Link to the CSS file -->
    <link rel="stylesheet" href="./css/styles.css">

    <!-- Title of the webpage -->
    <title>Image Iteration</title>
</head>
<body onload="makeImage();">
    <!-- Container to display the image -->
    <div class="contents" id="content"></div>

    <!-- Button to go to the next image -->
    <button onclick="nextImage()">Next Image</button>
</body>
</html>

CSS Code:

CSS
 cssCopy/* CSS for styling images */
img {
    width: 350px;
    height: 350px;
}

JavaScript Code:

JavaScript
 javascriptCopyvar images = [
  './images/splash class room image.jpg', './images/splash animal image.jpg',
  './images/splash nature image.jpg', './images/splash food image.jpg',
  './images/splash travel image.jpg'
];
var index = 0;

function makeImage() {
  var img = document.createElement('img');
  img.src = images[index];
  document.getElementById('content').appendChild(img);
}

function nextImage() {
  var img = document.getElementById('content').getElementsByTagName('img')[0];
  index++;
  index = index % images.length;
  img.src = images[index];
}

Output:

javascript array of images - image iteration using array

Here’s a detailed explanation of the provided JavaScript code:

This code allows navigation through a set of images by displaying one image at a time in a designated HTML container. Calling the nextImage() function moves to the next image in the sequence, and the images cycle back to the beginning once the end of the array is reached.

Use HTML Templates to Show an Array of Images in JavaScript

Moreover, HTML templates can be a structured and clean way to define your images and iterate over them.

HTML Code:

HTML
 htmlCopy<!DOCTYPE html>
<html>
<head>
    <!-- Link to the JavaScript file -->
    <script src="./javascript/imageArray.js"></script>

    <!-- Link to the CSS file -->
    <link rel="stylesheet" href="./css/styles.css">

    <!-- Title of the webpage -->
    <title>Image Iteration</title>
</head>
<body>
    <!-- Container to display the image -->
    <div id="imageContainer"></div>

    <!-- Button to go to the next image -->
    <button onclick="nextImage()">Next Image</button>
</body>
</html>

JavaScript Code:

JavaScript
 javascriptCopyconst images = [
  './images/splash class room image.jpg', './images/splash animal image.jpg',
  './images/splash nature image.jpg', './images/splash food image.jpg',
  './images/splash travel image.jpg'
];
let currentIndex = 0;

function renderImage(index) {
  const imageContainer = document.getElementById('imageContainer');
  const img = document.createElement('img');
  img.src = images[index];
  imageContainer.innerHTML = '';
  imageContainer.appendChild(img);
}

function nextImage() {
  currentIndex = (currentIndex + 1) % images.length;
  renderImage(currentIndex);
}

document.addEventListener('DOMContentLoaded', () => {
  renderImage(currentIndex);
});

Below is a detailed explanation of the provided code above:

This code displays a series of images and allows navigation through them. The nextImage() function is used to cycle through the images, and the renderImage(index) function is responsible for displaying an image based on the given index.

The initial image is rendered when the DOM content is fully loaded.

Use Modern JavaScript (ES6) Features to Show an Array of Images in JavaScript

Modern JavaScript features like arrow functions and the forEach method can make image iteration more concise and readable.

JavaScript Code:

JavaScript
 javascriptCopyconst images = [
  './images/splash class room image.jpg', './images/splash animal image.jpg',
  './images/splash nature image.jpg', './images/splash food image.jpg',
  './images/splash travel image.jpg'
];

let currentIndex = 0;

const renderImage = index => {
  const img = document.getElementById('mainImage');
  img.src = images[index];
};

const nextImage = () => {
  currentIndex = (currentIndex + 1) % images.length;
  renderImage(currentIndex);
};

const previousImage = () => {
  currentIndex = (currentIndex - 1 + images.length) % images.length;
  renderImage(currentIndex);
};

document.addEventListener('DOMContentLoaded', () => {
  renderImage(currentIndex);
});

Here’s a detailed explanation of the provided code:

Overall, this code sets up a simple image viewer that allows you to navigate through a sequence of images by clicking the Next or Previous buttons. The renderImage() function updates the displayed image, and the nextImage() and previousImage() functions manage the navigation through the images.

Conclusion

We have discussed the different ways to handle image arrays in JavaScript, each with its own advantages and use cases. Depending on your project requirements and coding preferences, you can choose the method that best fits your needs.

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
Mehvish Ashiq avatar Mehvish Ashiq avatar

Mehvish Ashiq is a former Java Programmer and a Data Science enthusiast who leverages her expertise to help others to learn and grow by creating interesting, useful, and reader-friendly content in Computer Programming, Data Science, and Technology.

LinkedIn GitHub Facebook

Related Article - JavaScript Array

Related Article - JavaScript Image