Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

162
Views
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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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);
  })
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!