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

195
Vistas
how to load background images into different blocks from an array

I have 9 blocks, where it is necessary that when reloading the background image, pictures from the folder are loaded without repeating. How can I implement this?

When I click on the button, I reload the page, then I interfere with the array. How then to get these pictures?

<div class="game">
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
      </div>
const imgCollection = [
  "assets/img/1.png",
  "assets/img/2.png",
  "assets/img/3.png",
  "assets/img/4.png",
  "assets/img/5.png",
  "assets/img/6.png",
  "assets/img/7.png",
  "assets/img/8.png",
  "assets/img/9.png",
];
reset.addEventListener("click", () => {
  location.reload();
      x=imgCollection.sort(()=>Math.random()-0.5);
});
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The styling is up to you, but this setup allows you to refresh the board without completely reloading the page.

HTML:

<div class="game">
</div>
<button id="reload-btn">reload</button>

Javascript:

let gameEl = document.querySelector('.game');
let reloadBtn = document.querySelector('#reload-btn');

const imgCollection = [
  "assets/img/1.png",
  "assets/img/2.png",
  "assets/img/3.png",
  "assets/img/4.png",
  "assets/img/5.png",
  "assets/img/6.png",
  "assets/img/7.png",
  "assets/img/8.png",
  "assets/img/9.png",
];

const shuffle = (array) => {
  for (let i = array.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [array[i], array[j]] = [array[j], array[i]];
  }
  return array;
}

const drawBlocks = (imageArray) => {
  gameEl.innerHTML = "";
  
  shuffle(imageArray).forEach((image) => {
    let newBlock = document.createElement('div');
    newBlock.innerHTML = image;
    newBlock.style.backgroundImage = `url('${image}')`; 
    gameEl.appendChild(newBlock);
  })
}

reloadBtn.addEventListener("click", () => {
  drawBlocks(imgCollection);
});

live example: https://codepen.io/jriches/pen/OJOepNP

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