0

I need some help with a small exercise I am doing using Javascript. I must create a small page with a menu generated from Javascript, and an image source that, when the image is clicked, the image is changed to a random image. If the next random image is same as the one before, I must generate another random image. How can this be done please?

HTML:

<!DOCTYPE html>
<html>
    <head>
        <title>Revision</title>
    </head>

    <body>
        <nav id="menu"></nav>
        <img id="image" width="300px" height="200px"/>
        <script src="js/mainScript.js"></script> 
        <script src="js/script.js"></script> 
    </body>
</html>

Javascript:

var imgArray = ["js/images/bmw1.JPG", "js/images/bmw2.jpg", 
"js/images/bmw3.jpg"];
var image = document.getElementById("image");
image.src = imgArray[0];

function changeImage()
{
    var i = imgArray.indexOf(this.getAttribute("src"));

    if(i < (imgArray.length-1))
        {
            i++;
            this.src = imgArray[i];
        }
    else
        {
            this.src = imgArray[0];
        }
}

image.addEventListener('click', changeImage);

As is, the code will show the first image, which is BMW1.jpg, and after I click on the image, it goes to the next image, BMW2.jpg, then on BMW3.jpg, and then it starts over.

Thanks!

EDIT: This is not a duplicated question as this needs image sources to be random, not numbers.

johnny
  • 135
  • 1
  • 12
  • Programming is applying, you can apply the ranged unique random number to the indices when picking up an image from the array containing the paths to the images. – Teemu Jun 28 '18 at 12:12
  • Duplicate does not mean word by word duplicate, it means the answers available on that question sufficiently answers this question. Now if someone ask how to play random music, that will also be a duplicate to that question. Hope you understand. – Munim Munna Jun 28 '18 at 13:06

0 Answers0