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

126
Views
Stop JS selecting same image twice from defined variables

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)] + ')'});
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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