My buttons are working fine, but I'm having trouble getting the escape key to work with the correct modal. It keeps closing the last modal no matter how many I have.
Even though thisModal
seems to point to the right one for the buttons, it doesn't work properly with the document.onkeydown
function, and I can't figure out why since everything is within the same for loop.
And please, let's keep any comments about using jQuery to a minimum :).
const modalToggle = document.querySelectorAll(".button"),
modal = document.querySelectorAll(".modal"),
closeButton = document.querySelectorAll(".close");
if (modalToggle) {
for (i = 0; i < modalToggle.length; i++) {
let thisToggle = modalToggle[i];
let thisModal = modal[i];
let thisClose = closeButton[i];
thisToggle.addEventListener("click", () => openModal(thisModal));
thisClose.addEventListener("click", () => closeModal(thisModal));
document.onkeydown = (e) => {
if (e.keyCode == 27) {
console.log(thisModal); // Always displays the LAST modal... why?
closeModal(thisModal);
}
}
};
}
function openModal(el) {
el.style.display = "block";
}
function closeModal(el) {
el.style.display = "none";
}
.modal {
display: none;
background: lightgray;
border: 1px solid black;
width: 50%;
height: 100px;
}
<button class="button">One</button>
<button class="button">Two</button>
<button class="button">Three</button>
<div class="modal">ONE
<button class="close">Close</button>
</div>
<div class="modal">TWO
<button class="close">Close</button>
</div>
<div class="modal">Three
<button class="close">Close</button>
</div>