Search code examples
javascripthtmlarraysweb

How do I choose a random image from an array and use it as a source for other images in javascript and html


I am trying to make a website and I need random images to be generated and then used as an input button thingy.

When I try to use the results of the thing the image does not show up.

The thing i need help with is displaying the image bc the code that picks the random image like has it under a name but idk how to use to name as a source for a button thing

I want the generated image to replace the button if that makes any sense


Solution

  • I believe you're trying to do this:

    HTML:

    <html>
      <body>
        <a href="#" onclick="alert('You clicked!')">
          <img src="" id="button_img" style="height: 100px;width: 100px;">
        </a>
      </body>
    </html>
    

    JS:

    <script>
    
      //array of links for images
      var array_of_images = [
        "https://www.pngitem.com/pimgs/m/97-974332_yellow-duck-png-download-image-transparent-background-rubber.png",
        "https://www.shareicon.net/data/256x256/2015/07/31/78089_make_512x512.png",
        "https://www.pngitem.com/pimgs/m/97-974413_rubber-duck-png-transparent-background-duck-clipart-png.png"
        ];
    
      //generate random number form 0-3
      var randomNum = Math.floor(Math.random()*3);
    
      //using the random number to choose a link from the array
      document.getElementById('button_img').src = array_of_images[randomNum];
    
    </script>