'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);
});


Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jacob Riches