vendredi 23 octobre 2020

Get Random Image with Button Click with Javascript

I know this has been answered before, but I can't for the life of me figure out why this wouldn't work. I've checked, and re-checked, and everything looks like it should work outright, but I'm not sure what I would be missing with this. Here's what I have:

JS:

const images = [

      "https://assets.codepen.io/8689/lake-thumb.jpg",
      "https://assets.codepen.io/8689/photo-thumb.jpg",
      "https://assets.codepen.io/8689/gopro-thumb.jpg"
    ];
    
    function getRandomImage() {
      const rnd = Math.floor(Math.random() * images.length);
      return images[rnd];
    }
    
    function changeImage() {
      const img = document.querySelector("#images");
      img.src = getRandomImage();
    }
    
    function init() {
      const btn = document.querySelector(".btn-image");
      btn.onclick = changeImage;
    }
    
    window.onload = init;

HTML:

<div id="images"></div>

<a href="#" class="btn-img">Get Image</a>

Codepen link: https://codepen.io/ultraloveninja/pen/ZEOLKeV

It should work and show a random image on load and then when you click the link/button load up a new on. So, not sure why they wouldn't be showing overall and I'm not getting any errors in the console.




Aucun commentaire:

Enregistrer un commentaire