Events

onkeydown

A keyboard key is pressed, including repeated events while held. HTML event-handler content attribute or corresponding event-handler property; the event fires only on relevant targets. The example uses document.getElementById("demo"). Event interface: KeyboardEvent. For the described native event: bubbles: yes; cancelable: yes. Use key for meaning, code for physical location, repeat for repetition; account for IME composition. Example: Focus the field and press/release a key. The event listener is registered with addEventListener(), which avoids inline script handlers and supports multiple listeners. Inline handlers require a CSP that permits them; do not insert untrusted code into handler attributes.

Formal Syntax & Structure

html syntaxhtml
<input onkeydown="handleEvent(event)">target.addEventListener("keydown", event => { /* handle event */ });

Parameters & Attributes

NameTypeDescription
onkeydownJavaScript handler bodyOptional HTML event-handler code; the example uses a registered listener instead. Not a Boolean attribute.
eventKeyboardEventEvent object delivered to the addEventListener callback; event.type is "keydown". Inspect target, currentTarget, bubbles and cancelable as appropriate.

Working Example

Example Snippethtml
<label for="demo">Sample text</label><input id="demo" value="Example text"><p role="status" id="log">Waiting for keydown</p><script>  const target = document.getElementById("demo");  const log = document.getElementById("log");  target.addEventListener("keydown", event => {    log.textContent = String(event.type + ": " + event.key);  });</script>
HTML Reference