- Instant help with your JavaScript coding problems

Detect escape key press in JavaScript

How to detect escape key press in JavaScript?
document.addEventListener('keydown', evt => {
    if (evt.key === 'Escape') {
        alert('Escape pressed');

The KeyboardEvent interface's key read-only property returns the value of the key pressed by the user, taking into consideration the state of modifier keys such as Shift as well as the keyboard locale and layout. The Unicode value of the key pressed can be derived from it using charCodeAt() .

Its value is determined as follows:

  • If the pressed key has a printed representation, the returned value is a non-empty Unicode character string containing the printable representation of the key.
  • If the pressed key is a control or special character, the returned value is one of the pre-defined key values.
  • If the KeyboardEvent represents the press of a dead key, the key value must be "Dead".
  • Some specialty keyboard keys (such as the extended keys for controlling media on multimedia keyboards) don't generate key codes on Windows; instead, they trigger WM_APPCOMMAND events. These events get mapped to DOM keyboard events, and are listed among the "Virtual key codes" for Windows, even though they aren't actually key codes.
  • If the key cannot be identified, the returned value is Unidentified.
Share "How to detect escape key press in JavaScript?"
detect escape press, escape keypress, keyboard event, keypress, escape, esc
Technical term:
Detect escape key press in JavaScript