How to detect Escape key in JavaScript

Detecting the Escape key is essential for implementing intuitive UI interactions like closing modals, canceling operations, and providing exit paths in web applications. As the creator of CoreUI with over 25 years of web development experience, I’ve implemented Escape key detection in countless modal dialogs and overlay components. The most reliable approach is using the keydown event listener and checking for event.key === 'Escape'. This method provides consistent behavior across all modern browsers and follows accessibility best practices.

Check for event.key === 'Escape' within a keydown event listener to detect Escape key presses.

document.addEventListener('keydown', function(event) {
    if (event.key === 'Escape') {
        console.log('Escape key was pressed!')
        // Close modal, cancel action, etc.
    }
})

This code listens for all keydown events on the document and specifically checks if the pressed key is ‘Escape’. When detected, you can trigger your desired action such as closing a modal dialog or canceling a form operation. The event.key property returns the string ‘Escape’ for the Escape key, making the condition clear and readable.

Best Practice Note:

This is the exact pattern we use in CoreUI modal components for accessibility compliance. Consider adding event.preventDefault() to prevent any default Escape key behavior when handling the key press yourself.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author