Using esc to close an image

How can I implement the use of "esc" key, or other accessibility features to close a pop-up image with this script?
document.querySelectorAll('.card img').forEach(image => {
image.onclick = () => {
document.querySelector('.popup-image').style.display = 'block';
document.querySelector('.popup-image img').src = image.getAttribute('src');
}
})

document.querySelector('.popup-image span').onclick = () => {
document.querySelector('.popup-image').style.display = 'none';
}
document.querySelectorAll('.card img').forEach(image => {
image.onclick = () => {
document.querySelector('.popup-image').style.display = 'block';
document.querySelector('.popup-image img').src = image.getAttribute('src');
}
})

document.querySelector('.popup-image span').onclick = () => {
document.querySelector('.popup-image').style.display = 'none';
}
It just display an image fixed.
11 Replies
Jochem
Jochem2y ago
Very basically this: https://codepen.io/jochemm/pen/ExRRWMO?editors=1011 replace the dialog.close() with whatever you need to do to hide your image but you've gotta listen for the keypress and then react to it
~MARSMAN~
~MARSMAN~2y ago
Document.addeventlistener("keydown"), function (e) {
If (e.keyCode == 27){
/// Your action here
}
}
Document.addeventlistener("keydown"), function (e) {
If (e.keyCode == 27){
/// Your action here
}
}
I'm such a slow typer lol
Jochem
Jochem2y ago
event.keyCode is deprecated, you shouldn't use it anymore 🙂 you should use event.code, and then compare against "Escape"
~MARSMAN~
~MARSMAN~2y ago
Oh good to know 👍 Don't know why my VS code isn't showing that it's deprecated
Jochem
Jochem2y ago
I had to look it up on MDN to be sure
~MARSMAN~
~MARSMAN~2y ago
Thanks for the heads-up!
Electronic
Electronic2y ago
Doesn't e.key just say the name of the key e.g. ESC
Jochem
Jochem2y ago
"Escape", but yes
Myndi
Myndi2y ago
I was pretty close to this, but I guess I failed. Thanks to you, and everyone 😊
Electronic
Electronic2y ago
I usually use e.key.tolowercase then check what I want
Myndi
Myndi2y ago
I was working with dialogs. Made this function to close it when clicking, thinking it works outside of the content, but it closes anywhere.
modal.forEach((modal) => {
modal.addEventListener("click", (e) => {
if (e.target.class !== "modal-content") {
modal.close();
}
});
});
modal.forEach((modal) => {
modal.addEventListener("click", (e) => {
if (e.target.class !== "modal-content") {
modal.close();
}
});
});
Any clue what might be wrong? The CSS is simply:
dialog>.modal
div>.modal-content
p>"some content"
dialog>.modal
div>.modal-content
p>"some content"
Want results from more Discord servers?
Add your server