I have been searching through the web, but could not find the answer to the question, which seems to have a trivial solution.
I have three popups on my page, which user can open and the functionality to open and close them looks usual:
const popupPicture = document.querySelector(".popup_pic");
const popupProfile = document.querySelector(".popup_profile");
const popupImage = document.querySelector(".popup_image");
function openPopup(popup) {
popup.classList.add("popup_opened");
}
function closePopup(popup) {
popup.classList.remove("popup_opened");
}
and I pass one of the popup variables to closePopup or to openPopup as a variable. For instance
closePopupButton.addEventListener("click", () => closePopup(popupProfile));
closePopupImageButton.addEventListener("click", () => closePopup(popupImage));
closePopupPictureButton.addEventListener("click", () => closePopup(popupPicture));
The same with opening popups. I need now closing functionality by Escape button. I understand that it is easy to achieve if there is just one popup by the following code:
document.addEventListener("keydown", function (evt) {
if (evt.key === "Escape") {
// and close popup here
}
});
But there are three popups in my case and I do not know, which I should close. Of course I can do it by this ugly way:
document.addEventListener("keydown", function (evt) {
if (evt.key === "Escape") {
closePopup(popupProfile);
closePopup(popupImage);
closePopup(popupPicture);
}
});
And it solves my case, but I wonder if there is more elegant solution, which does not require calling two functions that should not be called.
Hopefully I stated my issue clear.
Thank you very much in advance!
Simply use document.getElementsByClassName().
This returns an HTMLCollection of elements that include the given class string, then you just need to iterate through it.
Here's an example: https://jsfiddle.net/whp8xzb2/1/
The elements used in the example have multiple classes assigned to them, similar to your code. It retrieves these elements using document.getElementsByClassName("foo"), then it iterates through the results using a for loop:
for (let item of results) {
console.log(item)
}