Reputation: 107
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)";
})
}
Upvotes: 0
Views: 44
Reputation: 311
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+")";
})
}
Upvotes: 1