windowaddEventListenerkeydown
window.addEventListener('keydown', ...), commonly described in documentation as a way to listen for keyboard input at the window level, is a standard Web API used to respond to keys pressed by the user. The keydown event fires when any key is pressed down, and it propagates through the DOM to the window, allowing a single handler to capture most keyboard activity regardless of which element has focus.
The event object provided to the listener contains several useful properties:
- key: the character value of the key pressed (for example, 'a', 'Escape', 'Enter').
- code: the physical key on the keyboard (for example, 'KeyA', 'Escape', 'ArrowLeft').
- keyCode: a legacy numeric code (deprecated in favor of key and code).
- altKey, ctrlKey, shiftKey, metaKey: booleans indicating modifier keys.
- repeat: true if the key is being held down and the event is repeated.
- isComposing: true when an IME composition is in progress.
Usage typically looks like: window.addEventListener('keydown', (event) => { if (event.key === 'Escape') { /* close modal */ } });
When deciding which properties to check, key is useful for character-oriented checks, while code is better for
Common considerations include avoiding interference with native shortcuts, using preventDefault sparingly, and ensuring accessibility by not