I cant get my modals to work. The first one works but the rest do not. I dont know what i’m doing wrong. I’ve tried different variations of a for loop and forEach method but nothing works.
<div class="modal hidden" id='modal1'>
<button class="close-modal">×</button>
<img
src="./Images/alstroemeria.jpg"
alt="Three pink and
white flowers with a yellow and white center with green stems.
Lavender flower is faded in the background."
/>
<h2>Alstroemeria</h2>
<p>
It's symbolic of wealth, prosperity and fortune. It is also the flower
of friendship.
</p>
</div>
<div class="overlay hidden"></div>
<button class="btn">Siberian Iris</button>
<div class="modal hidden" id='modal2'>
<button class="close-modal">×</button>
<img
src="./Images/siberian-iris.jpeg"
width="200"
height="200"
alt="A close up photo of a flower with various hues of blue, purple, and yellow. The flower has vein like designs on most of the petals."
/>
<h2>Siberian Iris</h2>
<p>
<h2>Siberian Iris</h2>
It symbolizes eloquence. Purple iris is symbolic of wisdom and
compliments. Blue iris symbolizes faith and hope. Yellow iris symbolizes
passion while white iris symbolizes purity.
</p>
</div>
<div class="overlay hidden"></div>
this JS code only works for the first button but not the second button.
const modal = document.querySelectorAll(".modal");
const openModal = document.querySelectorAll(".btn");
const closeBtn = document.querySelectorAll(".close-modal");
const overlay = document.querySelectorAll(".overlay");
const showModal = () => {
modal.classList.remove("hidden");
overlay.classList.remove("hidden");
};
const closeModal = () => {
modal.classList.add("hidden");
overlay.classList.add("hidden");
};
openModal.addEventListener("click", showModal);
closeBtn.addEventListener("click", closeModal);
overlay.addEventListener("click", closeModal);
i tried these loops separately but they dont work. what am I doing wrong?
for (let i = 1; i < modal.length; i++) {
openModal[i].addEventListener("click", showModal);
closeBtn.addEventListener("click", closeModal);
overlay.addEventListener("click", closeModal);
}
modal.forEach(function (modals) {
modals.addEventListener("click", function () {
showModal();
});
});