Change the image when the page is reloaded

Hi there!
Clarify please, how can I implement the change of the image after the page is reloaded? I have 5 images, and they are changing when the page reloads.

I assume that I need an array with image URLs and a ‘random’ function which will grab a random URL from the array and set it as an image’s src attribute accordingly. But I can’t understand how I can do it via handlebars.js.

Help, please.

Hey @everydaytem :wave:
Best method of doing this is to use HTML JavaScript like so:

<img src="" data-random-image="image-1.jpg image-2.jpg image-3.jpg" alt="">
const image = document.querySelector('img[data-random-image]');
const sources = image.dataset.randomImage.split(" ");
const randomSource = sources[Math.floor(Math.random() * sources.length)]

image.setAttribute('src', randomSource);

I’ve put together a very brief demo on CodePen, which also includes a fallback:

Hope this helps :blush:

It works perfectly. Huge thanks, David! :muscle:

1 Like