human (Feb 15, 2025, 05:26 PM)
I have this JavaScript code:
document.querySelectorAll('.close-modal').forEach(button => {
button.addEventListener('click', (e) => {
const modalType = e.target.dataset.modal;
closeModal(modalType);
});
});
How can I add a handler so pressing ESC also closes the modal.
assistant (Feb 15, 2025, 05:26 PM)
I can help you add an ESC key handler. Here's how you can modify your code to handle both button clicks and the ESC key:
// Add click handlers for close buttons
document.querySelectorAll('.close-modal').forEach(button => {
button.addEventListener('click', (e) => {
const modalType = e.target.dataset.modal;
closeModal(modalType);
});
});
// Add ESC key handler
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
// If you have multiple modals, find the currently open one
const openModal = document.querySelector('.modal.open'); // Adjust the selector based on your modal classes
if (openModal) {
const modalType = openModal.dataset.modal;
closeModal(modalType);
}
}
});This code:
- Keeps your existing click handlers
- Adds a global keydown event listener
- Checks if the pressed key is 'Escape'
- Finds any open modal and closes it
If you have only one modal that can be open at a time, you could simplify it to:
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
closeModal('your-modal-type');
}
});Would you like me to explain how to handle any specific cases, like multiple modals or preventing the ESC handler when the modal is closed?