Random Image Swapping using Javascript not working

15 views Asked by At

The images in the /images folder are not swapping randomly with the ones located in the /swap-images folder. Both sets of images have the same name.

I am expecting the images to swap randomly in a loop on page load. This is the code.

 <script>
    window.addEventListener('load', function() {
        // Get all img elements
        var images = document.querySelectorAll('.image-grid img');

        // Loop through each img element
        images.forEach(function(image) {
            // Generate a random number between 1 and the total number of images in the 'swap-images' folder
            var randomImageNumber = Math.floor(Math.random() * 15) + 1;

            // Construct the new image source
            var newImageSource = 'swap-images/image' + randomImageNumber + '.jpg';

            // Set the new image source
            image.src = newImageSource;
        });
    });
</script>

0

There are 0 answers