Skip to content

Instantly share code, notes, and snippets.

@legoktm
Created March 2, 2025 07:35
Show Gist options
  • Select an option

  • Save legoktm/735c56a36d167b692a18df59a365a035 to your computer and use it in GitHub Desktop.

Select an option

Save legoktm/735c56a36d167b692a18df59a365a035 to your computer and use it in GitHub Desktop.
Closing Modals with JavaScript and the ESC Key

Closing Modals with JavaScript and the ESC Key

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:

  1. Keeps your existing click handlers
  2. Adds a global keydown event listener
  3. Checks if the pressed key is 'Escape'
  4. 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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment