Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

233
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda