I am trying to build a pop-up function written in JavaScript but I feel the code could be better.
So I have two thumbnails and when click it shows the corresponding image but bigger.
I want to build a page with about 20 of these but I feel there will be a lot of code repetition and I am stuck.
My code is here:
https://codesandbox.io/s/i8b1s
Here is my JS:
/*
The goal of this is to simplify the JS code as when I add more images
I do want to keep duplicating code.
*/
// Tesing
const targetNum = document.querySelectorAll("target");
console.log(targetNum);
// Original code below
// Target 1
const target1 = document.querySelector(".counterNo1");
const target2 = document.querySelector(".counterNo2");
// Target 1 Pop Up
const target1MainImage = document.querySelector(".mainImage1");
const target2MainImage = document.querySelector(".mainImage2");
// Close buttons
const close1 = document.querySelector(".closeBTN1");
const close2 = document.querySelector(".closeBTN2");
//Target 1 Clicked Event
target1.addEventListener("click", function () {
console.log("Target 1");
target1MainImage.classList.remove("hide");
target1MainImage.classList.add("show");
});
//Target 2 Clicked Event
target2.addEventListener("click", function () {
console.log("Target 2");
target2MainImage.classList.remove("hide");
target2MainImage.classList.add("show");
});
// Close
//Close Event 1
close1.addEventListener("click", function () {
console.log("Close Target 1");
target1MainImage.classList.add("hide");
target1MainImage.classList.remove("show");
});
//Close Event 2
close2.addEventListener("click", function () {
console.log("Close Target 2");
target2MainImage.classList.add("hide");
target2MainImage.classList.remove("show");
});
As you can see if I have more that one pop up, I am duplicating event listeners etc and I do not want a lot of dup code for elements. This is where I am stuck.
Can anyone point me in the right direction on what to do please?
Thanks,
Ben.
so what you can do is create a common popup and let there be 20 targets on the page. so all you have to do then is
// here create a variable to map the location or src value of bigger image
const ImageMapper = {
one: '/images/one.jpg'
.....
}
// then create the function which calls the popup and set the src of the image element in it
const openPopup = (opener) => {
popupImage.src = ImageMapper[opener]
popup.classList.add('show')
}
// and in the poup add a button which closes the popup so that you dont have to write multiple functions just to close a single popup
const closePopup = () => {
popup.classList.add('hide')
}
// and last in each of the possible element that will open the popup just add the onclick handler like
target1.onclick = () => {
openPopup('one')
}
// this will require a lot less code then what you will have to write