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

231
Views
Can I combine these functions into one streamlined function?

I am swapping out background images on click for several different instances, and also only targeting screens at 991px and above. Can I create one, streamlined function or make this more concise/better?

const mediaQuery = window.matchMedia('(min-width: 991px)')
const infraTab1 = document.querySelector(".content1")
const infraTab2 = document.querySelector(".content2")
const infraTab3 = document.querySelector(".content3")
const infraTab4 = document.querySelector(".content4")
const infrastructure = document.querySelector(".infrastructure")

if (mediaQuery.matches) {

  infraTab1.addEventListener("click", function () {
    infrastructure.style.backgroundImage = "url(img1.jpg)";
  })
}
if (mediaQuery.matches) {
  infraTab2.addEventListener("click", function () {
    infrastructure.style.backgroundImage = "url(img2.jpg)";
  })
}
if (mediaQuery.matches) {
  infraTab3.addEventListener("click", function () {
    infrastructure.style.backgroundImage = "url(img3.jpg)";
  })
}
if (mediaQuery.matches) {
  infraTab4.addEventListener("click", function () {
    infrastructure.style.backgroundImage = "url(img4.jpg)";
  })
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Maybe, This is the solution which you want

const mediaQuery = window.matchMedia('(min-width: 991px)')
const infraTab1 = document.querySelector(".content1")
const infraTab2 = document.querySelector(".content2")
const infraTab3 = document.querySelector(".content3")
const infraTab4 = document.querySelector(".content4")
const infrastructure = document.querySelector(".infrastructure")

if (mediaQuery.matches) {
    setEventOn(infraTab1, infrastructure,  "img1.jpg");
    setEventOn(infraTab2, infrastructure,  "img2.jpg");
    setEventOn(infraTab3, infrastructure,  "img3.jpg");
    setEventOn(infraTab4, infrastructure,  "img4.jpg");
}

function setEventOn(element, infra,  img){
    infraTab4.addEventListener("click", function () {
        infra.style.backgroundImage = "url("+img+")";
    })
}
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!