Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

163
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda