I have a JS script that opens a modal dialog window when you click on a certain HTML element.
My problem is that the script only works for one element. When I call the same class name .trigger
on another element, the entire script fails to work.
HTML
<div class="trigger">
<h2>Contact Me Form</h2>
<div class="modal">
<div class="modal-content">
<span class="close-button">x</span>
<p>Contact form details goes here</p>
</div>
</div>
</div>
<div class="trigger">
<h2>About Me</h2>
<div class="modal">
<div class="modal-content">
<span class="close-button">x</span>
<p>About Me details goes here</p>
</div>
</div>
</div>
JS
var modal = document.querySelector(".modal");
var trigger = document.querySelector(".trigger");
var closeButton = document.querySelector(".close-button");
function toggleModal() {
modal.classList.toggle("show-modal");
}
function windowOnClick(event) {
if (event.target === modal) {
toggleModal();
}
else if (event.target === closeButton) {
toggleModal();
}
}
trigger.addEventListener("click", toggleModal);
closeButton.addEventListener("click", toggleModal);
window.addEventListener("click", windowOnClick);
edit: I tried to change my JS code and it still doesn't work:
var modals = document.querySelectorAll(".modal");
const triggers = document.querySelectorAll('.trigger');
var closeButtons = document.querySelectorAll(".close-button");
for (const trigger of triggers) {
trigger.addEventListener('click', toggleModal);
}
function toggleModal(event)
event.target.querySelector('.modal').classList.toggle("show-modal");
}
function windowOnClick(event) {
if (event.target === modal) {
toggleModal();
}
else if (event.target === closeButton) {
toggleModal();
}
}
closeButton.addEventListener("click", toggleModal);
window.addEventListener("click", windowOnClick);
```