jeudi 28 juin 2018

Javascript - onClick random image [duplicate]

This question already has an answer here:

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.




Aucun commentaire:

Enregistrer un commentaire