Element: keydown event

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨July 2015⁩.

The keydown event is fired when a key is pressed.

Unlike the deprecated keypress event, the keydown event is fired for all keys, regardless of whether they produce a character value.

The keydown and keyup events provide a code indicating which key is pressed, while keypress indicates which character was entered. For example, a lowercase "a" will be reported as 65 by keydown and keyup, but as 97 by keypress. An uppercase "A" is reported as 65 by all events.

The event target of a key event is the currently focused element which is processing the keyboard activity. This includes: <input>, <textarea>, anything that is contentEditable, and anything else that can be interacted with the keyboard, such as <a>, <button>, and <summary>. If no suitable element is in focus, the event target will be the <body> or the root. The event bubbles. It can reach Document and Window.

The event target might change between different key events. For example, the keydown target for pressing the Tab key would be different from the keyup target, because the focus has changed.

Syntax

Use the event name in methods like addEventListener(), or set an event handler property.

js
addEventListener("keydown", (event) => { })

onkeydown = (event) => { }

Event type

A KeyboardEvent. Inherits from UIEvent and