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

193
Views
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 answers
Answer question

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