7 November 2023

Capturing the "Escape" key press with an event listener is a common practice in web development, especially for modals or dialogs. Example useful cases of using the event: It provides a better user experience. Users expect to be able to close a modal by pressing the "Escape" key. This is a standard behavior in many applications, making it more intuitive for users. It enhances accessibility for users who rely on keyboard navigation or screen readers. Accessibility guidelines recommend that modal dialogs should be closable via the keyboard, and the "Escape" key is a common way to achieve this. It ensures consistency in user interfaces. Users are accustomed to dismissing dialogs or pop-ups with the "Escape" key in various applications and websites. It offers a convenient way to close a modal without relying solely on a close button or other UI elements. Users can quickly close the modal using the keyboard, which can be particularly useful when navigating a website or web application with a keyboard.

Source code viewer
  1. // Add the event listener when needed.
  2. document.addEventListener('keydown', OnEscapePressed);
  5. const EscapePressed = () => {
  7. // What else should happen ...
  9. // Destroy the event after it's no longer needed.
  10. document.removeEventListener('keydown', OnEscapePressed);
  11. };
  12. // Event listener function for the Escape key.
  13. const OnEscapePressed = (event) => event.key === 'Escape' && EscapePressed();
Programming Language: ECMAScript