Random Image with JavaScript

OpenJavaScript 0

Last updated: December 11, 2022.

You can use JavaScript to display a random image, both on page load and when a user clicks to get another image.

Start by creating an <img> element without an src value:

<img id="random-image" src="" alt="Random image">

You can then make a random image appear in the element by storing the path to all images in an array and generating a random number to select one of the images randomly by their index value.

In the code below, this process is repeated every time a user clicks on the image by again running the randomImage function:

const imgEl = document.getElementById('random-image');

const srcArray = ['img1.jpg', 'img2.jpg', 'img3.jpg', 'img4.jpg'];
// Stores path to images in an array

imgEl.addEventListener('click', () => {
    randomImage();
    // Runs randomImage function when user clicks on image
});

let index;
// Current image index

randomImage();
function randomImage() {

    const randomIndex = Math.floor(Math.random()*srcArray.length);
    // Generates random number between 0 and array length-1 (because Math.floor rounds)

    if (randomIndex !== index) {
    // If number NOT same as current image index...

        imgEl.src = srcArray[randomIndex];
        //...set as image src

        index = randomIndex;
        //...and as new current index value

    } else {
    // If number same as current index value (repeat)...

        randomImage();
        //...start function from beginning again

    }

}

To prevent repeats, the newly generated random index value is checked against the current one. If there is a match, a new random value is generated. This repeats indefinitely until the new value is no longer a match.

Random image on page load / refresh

Alternatively, to get a random image on page load, store the current index value in browser local storage and check the new random value against this each time.

And, instead of running the randomImage function each time the image if clicked, refresh the page instead:

const imgEl = document.getElementById('random-image');

const srcArray = ['img1.jpg', 'img2.jpg', 'img3.jpg', 'img4.jpg'];

imgEl.addEventListener('click', () => {
    window.location.reload();
    // Refreshes page when image clicked
});

randomImage();

function randomImage() {

    const randomIndex = Math.floor(Math.random()*srcArray.length);

    if (localStorage.getItem('currentIndex') !== String(randomIndex)) {
    // Checks if current index in local storage is NOT equal to new randm value (as string)...
        
        imgEl.src = srcArray[randomIndex];
        //...if so, set random value as new image src...

        localStorage.setItem('currentIndex', randomIndex);
        //...and save as current index value in local storage

    } else {
      // random value and current index value match...

        randomImage();
        // ... so call random image function again

    }
}

Related posts