Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

167
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda