Emmanuel Akinfulubi

JavaScriptEvents

Image slideshow with next and previous buttons in JavaScript

Intermediate · 4 min read

Photo galleries, product pages and hotel listings often show one picture at a time with "Previous" and "Next" buttons. That is a slideshow, sometimes called a carousel. Under the buttons there is one small idea: a number that says which slide you are on.

In this tutorial you will build a slideshow of three images that moves forward and back, wraps around at both ends, and keeps its description right for screen readers. You should know what an array is and have used addEventListener.

The idea: keep an index

Keep the slides in an array and keep one number, index, that says which one is showing. Clicking "Next" changes the number. Then a function draws whatever slide the number points at. You never keep track of "the image on screen" separately; it is always worked out from index.

The remainder operator %

To wrap from the last slide back to the first, you need %, the remainder operator. It gives what is left over after dividing.

JavaScript

console.log(1 % 3); // 1
console.log(2 % 3); // 2
console.log(3 % 3); // 0: back to the start
console.log(-1 % 3); // -1: not 2!

With three slides, counting up and taking % 3 cycles 0, 1, 2, 0, 1, 2. The last line is a trap we will meet in Step 4.

Here is the page:

index.html

<button id="prev" type="button">Previous</button>
<button id="next" type="button">Next</button>
<div id="stage" aria-live="polite"></div>

Here is the exercise. Try it yourself first, or read on and we will build it together.

5 A slideshow with next and previous

fair

Show one image at a time, with buttons to move forward and back. Decide what happens at the ends.

Stuck? Three hints, smallest first
  1. 1. Keep an index and derive what is shown from it. Do not track the visible image separately.
  2. 2. To wrap around, (i + 1) % n forward and (i - 1 + n) % n backward.
  3. 3. The + n matters: -1 % 3 is -1 in JavaScript, not 2.

Step 1: the slides

Step 1

const slides = [
  { src: 'lagos.svg', alt: 'Slide 1, Lagos' },
  { src: 'abuja.svg', alt: 'Slide 2, Abuja' },
  { src: 'kano.svg', alt: 'Slide 3, Kano' },
];
let index = 0;
console.log(slides[index].alt); // Slide 1, Lagos

Each slide is an object with an image address (src) and a description (alt). The full solution draws each slide as a colored rectangle so it needs no image files, but the shape of the data is the same.

Each slide has its own alt text. A screen reader reads alt aloud instead of showing the picture, so one fixed description would be wrong for two of the three slides.

Step 2: draw the current slide

Step 2

const stage = document.getElementById('stage');
function render() {
  stage.textContent = '';
  const img = document.createElement('img');
  img.src = slides[index].src;
  img.alt = slides[index].alt;
  stage.appendChild(img);
}
render();
console.log(stage.querySelector('img').alt); // Slide 1, Lagos

stage.textContent = '' empties the stage, so there is only ever one image in it. Then a fresh img is made for the current slide and added.

aria-live="polite" on the stage asks screen readers to mention when its content changes, without interrupting whatever they are reading.

Step 3: the Next button

Step 3

const next = document.getElementById('next');
next.addEventListener('click', () => {
  index = (index + 1) % slides.length;
  render();
});
for (let i = 0; i < 3; i++) {
  next.dispatchEvent(new Event('click'));
  console.log(stage.querySelector('img').alt);
}
// Slide 2, Abuja
// Slide 3, Kano
// Slide 1, Lagos

From the last slide, index + 1 is 3, and 3 % 3 is 0, so the show wraps back to the start. Using slides.length instead of writing 3 means you can add slides without touching this line.

Step 4: the Previous button, and the trap

Going back looks like the same thing with a minus sign: (index - 1) % slides.length. Try it from the first slide:

JavaScript

const slides = ['Lagos', 'Abuja', 'Kano'];
let index = 0;
index = (index - 1) % slides.length;
console.log(index, slides[index]); // -1 undefined
index = 0;
index = (index - 1 + slides.length) % slides.length;
console.log(index, slides[index]); // 2 Kano

In JavaScript, % keeps the sign of the number on its left, so -1 % 3 is -1. There is no slide at position -1, and render() would crash trying to read .src from undefined.

Adding slides.length first keeps the number positive: 0 - 1 + 3 is 2, and 2 % 3 is 2, the last slide. For any other slide the extra + 3 makes no difference, because the % 3 takes it away again.

Step 5: wire up Previous

Step 5

const prev = document.getElementById('prev');
prev.addEventListener('click', () => {
  index = (index - 1 + slides.length) % slides.length;
  render();
});
prev.dispatchEvent(new Event('click'));
console.log(stage.querySelector('img').alt); // Slide 3, Kano

From slide 1, Previous now wraps round to slide 3.

The full solution

The panel builds the slideshow and clicks through it, then resets to the first slide and checks: Next advances and wraps to the start, Previous wraps to the end, -1 % 3 really is -1, only one image is ever on stage, and every slide has its own alt. Press Run to see it, and click through the live demo.

Live, in a real browser. Click it. Sandboxed to allow-scripts only, so it cannot reach this page.

The answer

const swatch = (fill) =>
  'data:image/svg+xml;utf8,' + encodeURIComponent(
    `<svg xmlns="http://www.w3.org/2000/svg" width="260" height="120"><rect width="100%" height="100%" fill="${fill}"/></svg>`);

const slides = [
  { src: swatch('#3055d8'), alt: 'Slide 1, Lagos' },
  { src: swatch('#17734b'), alt: 'Slide 2, Abuja' },
  { src: swatch('#a3341f'), alt: 'Slide 3, Kano' },
];

const stage = el('div', { id: 'stage', 'aria-live': 'polite' });
const prev = el('button', { id: 'prev', type: 'button' }, 'Previous');
const next = el('button', { id: 'next', type: 'button' }, 'Next');
document.body.appendChild(el('div', {}, [prev, next, stage]));

let index = 0;                                  // the single source of truth

function render() {
  stage.textContent = '';                       // clear
  const img = document.createElement('img');
  img.src = slides[index].src;
  img.alt = slides[index].alt;                  // the alt changes with the slide
  stage.appendChild(img);
}

// + slides.length before the % , because JavaScript's % keeps the LEFT operand's
// sign: (0 - 1) % 3 is -1, not 2.
next.addEventListener('click', () => { index = (index + 1) % slides.length; render(); });
prev.addEventListener('click', () => { index = (index - 1 + slides.length) % slides.length; render(); });

render();

const shown = () => stage.querySelector('img').alt;

console.log('start:', shown());
fire(next, 'click'); console.log('next :', shown());
fire(next, 'click'); console.log('next :', shown());
fire(next, 'click'); console.log('next :', shown(), '<- wrapped to the start');
fire(prev, 'click'); console.log('prev :', shown(), '<- wrapped to the end');
console.log('why the + n:', (0 - 1) % 3, 'vs', (0 - 1 + 3) % 3);

// The walk-through above moved the index. Put it back before asserting, rather
// than writing assertions that depend on how many times it was clicked.
index = 0;
render();

Output


      
13 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 13 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

13 checks

test('it starts on the first slide', shown(), 'Slide 1, Lagos');
test('next advances', (() => { fire(next, 'click'); return shown(); })(), 'Slide 2, Abuja');
test('and again', (() => { fire(next, 'click'); return shown(); })(), 'Slide 3, Kano');
test('next at the end wraps to the start', (() => { fire(next, 'click'); return shown(); })(), 'Slide 1, Lagos');
test('previous at the start wraps to the end', (() => { fire(prev, 'click'); return shown(); })(), 'Slide 3, Kano');
test('a naive -1 % n would be negative', (0 - 1) % slides.length, -1);
test('which is not a valid index', slides[-1], undefined);
test('adding n first fixes it', (0 - 1 + slides.length) % slides.length, 2);
test('only one image is on stage at a time', stage.querySelectorAll('img').length, 1);
test('the alt text changes with the slide', (() => { fire(next, 'click'); return shown(); })(), 'Slide 1, Lagos');
test('a full cycle returns to the start', (() => { const first = shown(); for (let i = 0; i < slides.length; i++) fire(next, 'click'); return shown() === first; })(), true);
test('the stage announces changes politely', stage.getAttribute('aria-live'), 'polite');
test('every slide has its own alt', new Set(slides.map((s) => s.alt)).size, slides.length);

(index - 1 + n) % n rather than (index - 1) % n. JavaScript's % is a remainder, not a mathematical modulo, and it keeps the sign of the left operand — so -1 % 3 is -1, and slides[-1] is undefined. The assertions pin down both the broken version and the fix. This is the same correction as the array-rotation exercise in the Basic section, and it comes up whenever an index cycles.

Two details make it usable rather than just working. The alt changes with the slide, since a fixed alt describes one image and lies about the other two. And aria-live="polite" on the stage means a screen reader mentions the change without interrupting; using assertive here would cut across whatever the user was reading.

Common mistakes

  • Writing (index - 1) % n for Previous. It gives -1 on the first slide. Add n before taking the remainder.
  • Using one alt for every slide. Screen reader users hear the wrong description. Change alt along with src.
  • Tracking the visible image separately. A second variable for "what's on screen" can fall out of step with index. Draw everything from index.

Try it yourself

  1. Show "Slide 2 of 3" under the image, worked out from index and slides.length.
  2. Let the left and right arrow keys move the slideshow, using a keydown listener and event.key values 'ArrowLeft' and 'ArrowRight'.
  3. Instead of wrapping, stop at the ends: disable Previous on the first slide and Next on the last with button.disabled = true.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.