My JS is applying a random background image from a defined set of variables (var images =) to div elements with classes image01, image02, image03, and image04. How do I stop my JS selecting the same image twice between classes?
HTML
<section id="grid" class="desktop-image">
<div class="image-grid">
<div id="image" class="image01"></div>
<div id="image" class="image02"></div>
<div id="image" class="image03"></div>
<div id="image" class="image04"></div>
</div>
</section>
JS
var images = ['PK1.jpg','PK2.jpg','PK3.jpg','PK4.jpg','PK5.jpg','PK6.jpg','PK7.jpg','PK8.jpg','PK9.jpg','PK10.jpg','PK11.jpg','PK12.jpg','PK13.jpg','PK14.jpg',
'PK15.jpg','PK16.jpg','PK17.jpg','PK18.jpg','PK19.jpg','PK20.jpg','PK21.jpg','PK22.jpg','PK23.jpg','PK24.jpg','PK25.jpg','PK26.jpg','PK27.jpg',];
$(".image01").css({'background-image': 'url(assets/' + images[Math.floor(Math.random() * images.length)] + ')'});
$(".image02").css({'background-image': 'url(assets/' + images[Math.floor(Math.random() * images.length)] + ')'});
$(".image03").css({'background-image': 'url(assets/' + images[Math.floor(Math.random() * images.length)] + ')'});
$(".image04").css({'background-image': 'url(assets/' + images[Math.floor(Math.random() * images.length)] + ')'});
Create an array of images that have been already chosen randomly.
var images = ['PK1.jpg','PK2.jpg','PK3.jpg','PK4.jpg','PK5.jpg','PK6.jpg','PK7.jpg','PK8.jpg','PK9.jpg','PK10.jpg','PK11.jpg','PK12.jpg','PK13.jpg','PK14.jpg',
'PK15.jpg','PK16.jpg','PK17.jpg','PK18.jpg','PK19.jpg','PK20.jpg','PK21.jpg','PK22.jpg','PK23.jpg','PK24.jpg','PK25.jpg','PK26.jpg','PK27.jpg',];
let usedImgs = [];
let imgNames = [".image01", ".image02", ".image03", ".image04"];
imgNames.forEach((img) => {
let randImg = Math.floor(Math.random() * images.length);
while (usedImgs.includes(randImg)) {
randImg = Math.floor(Math.random() * images.length);
}
$(img).css({'background-image': 'url(assets/' + images[randImg] + ')'});
usedImgs.append(randImg);
})