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

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

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