Skip to content
Advertisement

Display multiple random images rather than just the one

The code below displays one image from an array at random. I’ve been trying to change it without success to show all the images from the array at random. I’ve used a while loop to generate the random function. The random function works and randomises the whole array but only on image is returned. There are 8 images in the array.

function DisplayImage(i) {
    let CardImage = document.createElement('img');
    CardImage.src = `Images/${images[i].img}`;
    CardImage.alt = CardImage.src;
    document.querySelector("#box").appendChild(CardImage);
}

Thank you

Advertisement

Answer

Are you searching for something like these two approaches?

To chose randomly just one image:

function DisplayImage(totalImages) {
  const i = Math.floor(Math.random() * totalImages)
  let CardImage = document.createElement('img');
  CardImage.src = `Images/${images[i].img}`;
  CardImage.alt = CardImage.src;
  document.querySelector("#box").appendChild(CardImage);
}

Or to randomize all images:

function shuffle(array) {
  let currentIndex = array.length,  randomIndex;
  while (currentIndex != 0) {
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex--;
    [array[currentIndex], array[randomIndex]] = [array[randomIndex], array[currentIndex]];
  }

  return array;
}

function DisplayImage(totalImages) {
  const items = [...Array(totalImages).keys()]
  const randomItems = shuffle(items) 

  randomItems.forEach(item => {
    let CardImage = document.createElement('img');
    CardImage.src = `Images/${images[item].img}`;
    CardImage.alt = CardImage.src;
    document.querySelector("#box").appendChild(CardImage);
  })
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement