Home > Software engineering >  Display multiple images randomly and hide the rest
Display multiple images randomly and hide the rest

Time:04-28

Hi, I have 5 images that I would like to display randomly each time I click on them.

My code:

<img src="/image1.jpg">
<img src="/image2.jpg">
<img src="/image3.jpg">
<img src="/image4.jpg">
<img src="/image5.jpg">

<button  onClick="randomizer()">
   <i ></i>
</button>

many thanks in advance.

CodePudding user response:

Refer following code

<img id="showImage">
<button id="changeImage">click</button>
//this will grab the image element
const imgElement = document.querySelector("#showImage");

// this is where we'll add the 'click' event lsitener & it's corresponding function
const btn = document.querySelector("#changeImage");

// In this array, you can store links to images (& you are **not** limited to 5 images only)
const imgSrc = [ 'link1', 'link2', 'link3' ];


btn.addEventListener('click', () => {
// here we generate random number, which will always be less than the imgSrc array, (so you are not limited to 5 images only)
    const randomNumber = Math.floor(Math.random()*imgSrc.length);
//here we use setAttribute() function to add the link to img element
  imgElement.setAttribute('src', imgSrc[randomNumber]);

})

CodePudding user response:

This should work for your use case. You can change the img src. I simply used some placeholder images.

As you mentioned in the question, Hide all other images and only pick one randomly..

const images = document.querySelectorAll("img");

const btn = document.querySelector(".prev-btn");

btn.addEventListener("click", () => {
  const randomNumber = Math.round(Math.random() * (images.length - 1));

  for (let index = 0; index < images.length; index  ) {
    const element = images[index];
    element.style.display = "none";
  }

  images[randomNumber].style.display = "flex";
});
<!DOCTYPE html>
<html>
  <head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />

    <style>
      .hideImg {
        display: none;
      }
    </style>
  </head>

  <body>
    <div id="app">
      <img src="https://via.placeholder.com/600/771796"  />
      <img src="https://via.placeholder.com/600/24f355"  />
      <img src="https://via.placeholder.com/600/d32776"  />
      <img src="https://via.placeholder.com/600/d32776"  />

      <button >
        <i ></i>
        Click me
      </button>
    </div>

    <script src="src/index.js"></script>
  </body>
</html>

  • Related