Search code examples
javascriptarraysimagerandominvisible

How to make multiple random images appear upon clicking another using Javascript?


I'm currently trying to make an image that upon clicking, disappears and shows three random images. So far I thought maybe duplicating the clickable image twice and just making those invisible would work, so they would change to one of the random images and become visible after clicking the image. If you have any other idea of how this may work, I'd really like to know!

Also does anyone know how I could make it so that an image could only be used for one of the three spots, so that you always have three different random images next to each other.

Here is my JS and HTML:

var playerImg;
var playerImg2;
var playerImg3;
var playerArray = ["A1.png", "A2.png", "A3.png", "A4.png", "A5.png", "M1.png", "M2.png", "M3.png", "M4.png", "M5.png", "V1.png", "V2.png", "V3.png", "V4.png", "V5.png", "D1.png", "D2.png", "D3.png"];

function openPack() {
    var randomPlayer = (Math.floor(Math.random() * 18) + 1);
    playerImg = playerArray[randomPlayer - 1];
    document.getElementById("pack").src = "image/" + playerImg;

    var randomPlayer2 = (Math.floor(Math.random() * 18) + 1);
    playerImg2 = playerArray[randomPlayer2 - 1];
    document.getElementById("player2").src = "image/" + playerImg2;

    var randomPlayer3 = (Math.floor(Math.random() * 18) + 1);
    playerImg3 = playerArray[randomPlayer3 - 1];
    document.getElementById("player3").src = "image/" + playerImg3;
}

document.querySelectorAll("img#player2")[0].addEventListener("click", openPack);
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <link rel="stylesheet" href="css/style.css">
</head>

<body>
    <img id="pack" src="image/pack.png" alt="Unopened pack">
    <img id="player2" src="image/pack.png" alt="Place for a second player after the pack is opened">
    <img id="player3" src="image/pack.png" alt="Place for a third player after the pack is opened">
    <img id="veld" src="image/veld.png" alt="Football field with positions">



</body>
<script src="scripts/packs.js"></script>

</html>

Let me know if I forgot to tell something, and thank you!


Solution

  • Here new openPack function that will exclude duplicates

    function openPack() {
        var playerArraycopy = playerArray.slice();//getting new copy of initial input
        function getRandomImg(){
            return playerArraycopy.splice([Math.floor(Math.random() * playerArraycopy.length)],1)[0];//calculating a new random image and removing it from copy to exclude duplicates
        }
    
       document.getElementById("player2").src = "image/" + getRandomImg();
       document.getElementById("pack").src = "image/" + getRandomImg();
       document.getElementById("player3").src = "image/" + getRandomImg();
    }
    

    check Array.splice for more information