JavaScript — Displaying Images

intermediate25 min

Learning objectives

  • Use JavaScript to build an image slider
  • Use JavaScript to build an image gallery

Learn

C1 — An image slider with JavaScript

<div id="slider">
  <img id="slide-image" src="img_slide1.jpg" alt="Product photo 1">
  <button id="prev-btn">Previous</button>
  <button id="next-btn">Next</button>
</div>
const images = ["img_slide1.jpg", "img_slide2.jpg", "img_slide3.jpg"];
let index = 0;
const slideImage = document.querySelector("#slide-image");

function showSlide(newIndex) {
  index = (newIndex + images.length) % images.length; // wraps around at both ends
  slideImage.src = images[index];
}

document.querySelector("#next-btn").addEventListener("click", () => showSlide(index + 1));
document.querySelector("#prev-btn").addEventListener("click", () => showSlide(index - 1));

How the wraparound works

(newIndex + images.length) % images.length keeps index valid even when it goes below 0 or above the last image — clicking "previous" on the first image correctly jumps to the last one, and vice versa.

An image gallery

A gallery is a different pattern from a slider: instead of one image with next/previous buttons, every image is visible at once as a grid of thumbnails, and clicking one shows it larger.

<div id="gallery">
  <img class="thumb" src="img_veg_box.jpg" alt="Weekly vegetable box">
  <img class="thumb" src="img_farm_shop.jpg" alt="Our farm shop front">
  <img class="thumb" src="img_harvest.jpg" alt="Fresh harvest crates">
</div>
<img id="gallery-main" src="img_veg_box.jpg" alt="Selected gallery image">
const thumbs = document.querySelectorAll(".thumb");
const mainImage = document.querySelector("#gallery-main");

thumbs.forEach((thumb) => {
  thumb.addEventListener("click", () => {
    mainImage.src = thumb.src;
    mainImage.alt = thumb.alt;
  });
});

querySelectorAll selects every thumbnail at once, and forEach attaches the same click behaviour to each one individually — clicking any thumbnail copies its src/alt onto the larger #gallery-main image. Unlike the slider, there's no "current index" to track — the gallery just responds to whichever thumbnail was actually clicked.

Task

Add both an image slider and an image gallery to your own site, using assets you sourced and prepared in Aim B — the slider for one part of the page and the gallery for another, so you can show you understand when each pattern is the more appropriate choice.

Practise

Apply what you've just learned in the Coding Lab.

Open Coding Lab
Log in to track this lesson on your progress dashboard.
Log in