Emmanuel Akinfulubi

JavaScriptDOM

Display a random image on click in JavaScript

Intermediate · 3 min read

A random tip of the day, a random product on a home page, a random avatar for a new user: picking something at random from a list is a small job that comes up all the time. Getting it slightly wrong is also common, and the bug only shows up now and then, which makes it hard to catch.

In this tutorial you will show a random image from a list when a button is pressed, with the right width, height and description. Then you will make the random part testable. You should know what an array is and what a function is.

Picking a random index

Math.random() gives a decimal number from 0 up to, but never including, 1. To turn that into a position in a list of 3 items:

  1. Multiply by the length: you get a number from 0 up to, but not including, 3.
  2. Round it down with Math.floor: you get 0, 1 or 2.

JavaScript

const length = 3;
console.log(Math.floor(0 * length));    // 0
console.log(Math.floor(0.5 * length));  // 1
console.log(Math.floor(0.99 * length)); // 2

Those are exactly the three positions in the list.

The images

Each image is an object with its address (src), size and a description (alt) for people who can't see it. The addresses here are SVG data URLs: the picture is written into the address itself, so nothing has to be downloaded.

JavaScript

const images = [
  { src: 'data:image/svg+xml;utf8,...', width: 240, height: 160, alt: 'A blue placeholder, 240 by 160' },
  { src: 'data:image/svg+xml;utf8,...', width: 320, height: 195, alt: 'A green placeholder, 320 by 195' },
  { src: 'data:image/svg+xml;utf8,...', width: 500, height: 343, alt: 'A red placeholder, 500 by 343' },
];

The ... stands for the drawing; the full solution builds each one with a small swatch function.

Here is the exercise. Have a go first if you like, then read on.

11 Show a random image

fair

Pick a random image from a list and display it, with its width and height, when a button is pressed.

Stuck? Three hints, smallest first
  1. 1. Math.floor(Math.random() * list.length) gives a valid index. Note floor, not round.
  2. 2. Randomness cannot be asserted directly. Inject the random function so a test can supply a known one.
  3. 3. Always set alt, and set width and height so the page does not jump as the image loads.

Step 1: pick one

Step 1

const images = [
  { width: 240, height: 160, alt: 'A blue placeholder, 240 by 160' },
  { width: 320, height: 195, alt: 'A green placeholder, 320 by 195' },
  { width: 500, height: 343, alt: 'A red placeholder, 500 by 343' },
];
const pick = images[Math.floor(Math.random() * images.length)];
console.log(images.includes(pick)); // true

You can't predict which image comes out, so the check asks a question that is true every time: is it one of the three?

Step 2: the wrong turn with Math.round

Math.round looks like it would do the same job. Watch what it does near the top:

Step 2

const images = ['blue', 'green', 'red'];
console.log(Math.round(0.99 * images.length)); // 3
console.log(images[3]);                         // undefined
console.log(Math.floor(0.99 * images.length)); // 2

Math.round(2.97) is 3, and there is no position 3 in a list of three. Your page would try to show undefined now and then, roughly one click in six. Math.floor never goes past the last position.

Step 3: show the image

Create an img element, set its four properties and put it on the page:

Step 3

function showRandomImage(host, list, random = Math.random) {
  const pick = list[Math.floor(random() * list.length)];
  host.textContent = '';              // remove the previous image
  const img = document.createElement('img');
  img.src = pick.src;
  img.width = pick.width;
  img.height = pick.height;
  img.alt = pick.alt;
  host.appendChild(img);
  return img;
}

Setting width and height lets the browser save the right amount of space before the image loads, so the page doesn't jump. alt is the only thing a screen reader user gets, so never leave it out. Clearing host first means only one image shows at a time.

To run it on a click:

JavaScript

document.getElementById('go').addEventListener('click', () => {
  showRandomImage(document.getElementById('host'), images);
});

Step 4: make the random part testable

Look at the third parameter: random = Math.random. On the page, nobody passes it, so the real Math.random is used. In a test you can pass a function that returns a number you choose:

Step 4

function showRandomImage(host, list, random = Math.random) {
  const pick = list[Math.floor(random() * list.length)];
  host.textContent = '';
  const img = document.createElement('img');
  img.src = pick.src;
  img.width = pick.width;
  img.height = pick.height;
  img.alt = pick.alt;
  host.appendChild(img);
  return img;
}
const images = [
  { src: 'data:,blue', width: 240, height: 160, alt: 'A blue placeholder, 240 by 160' },
  { src: 'data:,green', width: 320, height: 195, alt: 'A green placeholder, 320 by 195' },
  { src: 'data:,red', width: 500, height: 343, alt: 'A red placeholder, 500 by 343' },
];
const host = document.getElementById('host');
console.log(showRandomImage(host, images, () => 0).alt);    // A blue placeholder, 240 by 160
console.log(showRandomImage(host, images, () => 0.99).alt); // A red placeholder, 500 by 343
console.log(host.children.length);                          // 1

() => 0 always picks the first image and () => 0.99 always picks the last, so the results are exact. This trick, passing in the thing that changes, works for anything random and for anything that depends on the clock.

The full solution

The panel builds the three images and shows one for each of a fixed set of "random" numbers. Its checks confirm each pick, that floor stays in range and round doesn't, that width, height and alt are set, and that a few hundred real random picks always land in range and reach all three images. Press Run, then click the button in the live demo a few times.

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

The answer

// Inline SVG data URLs, so nothing is fetched. Remote image URLs
// go dead, and loading them would break the offline promise.
const swatch = (fill, w, h) =>
  'data:image/svg+xml;utf8,' + encodeURIComponent(
    `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}">` +
    `<rect width="100%" height="100%" fill="${fill}"/></svg>`);

const images = [
  { src: swatch('#3055d8', 240, 160), width: 240, height: 160, alt: 'A blue placeholder, 240 by 160' },
  { src: swatch('#17734b', 320, 195), width: 320, height: 195, alt: 'A green placeholder, 320 by 195' },
  { src: swatch('#a3341f', 500, 343), width: 500, height: 343, alt: 'A red placeholder, 500 by 343' },
];

// random is a PARAMETER. That is what makes a random choice testable: the page
// passes Math.random, a test passes something it controls.
function showRandomImage(host, list, random = Math.random) {
  const pick = list[Math.floor(random() * list.length)];   // floor, never round
  host.textContent = '';
  const img = document.createElement('img');
  img.src = pick.src;
  img.width = pick.width;          // stated so the layout does not jump
  img.height = pick.height;
  img.alt = pick.alt;              // never omit this
  host.appendChild(img);
  return img;
}

const host = el('p', { id: 'host' });
document.body.appendChild(host);

// A fixed sequence stands in for randomness.
let i = 0;
const sequence = [0, 0.5, 0.99];
const nextFixed = () => sequence[i++ % sequence.length];

for (const _ of sequence) {
  const img = showRandomImage(host, images, nextFixed);
  console.log('picked', img.getAttribute('width') + '\u00d7' + img.getAttribute('height'), '| alt:', img.alt);
}

// Why floor and not round: round would reach an index that does not exist.
console.log('Math.round(0.99 * 3) =', Math.round(0.99 * 3), '<- index 3 of 3 is undefined');
console.log('Math.floor(0.99 * 3) =', Math.floor(0.99 * 3), '<- always in range');

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('0 picks the first', showRandomImage(host, images, () => 0).alt, images[0].alt);
test('0.5 picks the middle', showRandomImage(host, images, () => 0.5).alt, images[1].alt);
test('0.99 picks the last', showRandomImage(host, images, () => 0.99).alt, images[2].alt);
test('floor keeps the index in range', Math.floor(0.999999 * images.length), 2);
test('round would go out of range', Math.round(0.99 * images.length), 3);
test('and that index does not exist', images[3], undefined);
test('the image has a width', showRandomImage(host, images, () => 0).getAttribute('width'), '240');
test('and a height', showRandomImage(host, images, () => 0).getAttribute('height'), '160');
test('and a non-empty alt', showRandomImage(host, images, () => 0).alt.length > 0, true);
test('the source is a data URL, so nothing is fetched', showRandomImage(host, images, () => 0).src.startsWith('data:'), true);
test('only one image is shown at a time', host.children.length, 1);
test('a real Math.random always lands in range', Array.from({ length: 200 }, () => Math.floor(Math.random() * images.length)).every((n) => n >= 0 && n < images.length), true);
test('and every image is reachable', new Set(Array.from({ length: 400 }, () => Math.floor(Math.random() * images.length))).size, 3);

Adapted, twice over. Remote image URLs go dead, and fetching anything would break this course's promise that it works from a file:// URL with no network — so the images are inline SVG data URLs. And Math.random is a parameter with a default, which is the general technique for testing anything random: the page gets real randomness, the test supplies () => 0.5 and asserts an exact result.

Math.floor, never Math.round. With three images, round(0.99 * 3) is 3, and index 3 does not exist — the assertions pin down both the failure and the fix. This is the standard off-by-one in random selection.

width, height and alt are all load-bearing. The dimensions reserve space so the page does not jump as the image arrives, and alt is the only thing a screen-reader user gets.

Common mistakes

  • Using Math.round instead of Math.floor. It can produce an index one past the end of the list.
  • Leaving out alt. Screen reader users get nothing. Describe the image in a few words.
  • Not clearing the old image. Each click adds another one. Empty the container first with host.textContent = ''.

Try it yourself

  1. Never show the same image twice in a row: if the new pick matches the last one, pick again.
  2. Show the size under the image as text, for example 320×195.
  3. Add two more images to the list and check that every one of them still gets picked.

Keep practising

Newsletter

New writing, when it lands.

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