samedi 22 août 2020

Show random images without repeat in Javascript

I'm a complete beginner in JavaScript with some experience in html and css. Anyway I'm trying to get a two random images everytime a user clicks on one of the two images. I've successfully implemented the code. However the images keep on repeating. I spent a whole hour searching for a way to do that and I've found but it didn't work for me. This is my code and thanks in advance:

<!DOCTYPE html>
<html>
<head>
    <title>My awesome website</title>
    <link rel="stylesheet" href="styles.css">

    <script>
        function getRandomImage() {
            var images = new Array("1.jpg", "2.jpg", "3.jpg", "4.jpg", "5.jpg", "6.jpg", "7.jpg", "8.jpg", "9.jpg", "10.jpg", "11.jpg", "12.jpg");
            var randomNum1 = Math.floor(Math.random() * images.length);
            var randomNum2 = Math.floor(Math.random() * images.length);
            if (randomNum1 == randomNum2) {
                var randomNum2 = Math.floor(Math.random() * images.length);
            }
            document.getElementById("firstPic").src = images[randomNum1]
            document.getElementById("secondPic").src = images[randomNum2]
        }
    </script>

</head>
<body>
    <div class="title">
        My awesome website
    </div>
    <pre><h1><center><img src="1.jpg" width="300px" height="300px" id="firstPic" onclick="getRandomImage()" />   or  <img src="2.jpg" width="300px" height="300px" id="secondPic" onclick="getRandomImage()" /></center></h1></pre>
</body>



Aucun commentaire:

Enregistrer un commentaire