References

Beginner-friendly references for web development, with live, editable examples.

The HTML onkeydown event

Event All modern browsers Updated
Quick answer

The HTML onkeydown attribute runs JavaScript when a key is pressed down. It is an inline handler for the keydown event; in modern code prefer addEventListener('keydown', …).

Overview

The onkeydown event attribute runs JavaScript when a key is pressed down. In JavaScript the event itself is named keydown — drop the on prefix when you call addEventListener.

It is a keyboard event. The handler receives a KeyboardEvent exposing key (the character or named key like "Enter" or "ArrowLeft") and modifier flags such as ctrlKey and shiftKey. Prefer the key property over the long-deprecated keyCode.

You can wire this up with the inline onkeydown HTML attribute, but the modern, recommended approach is element.addEventListener('keydown', handler) in JavaScript. That keeps behavior out of your markup, lets you attach several handlers to the same event, and makes them easy to remove. The inline attribute is fine for quick demos.

Syntax

<element onkeydown="handler()">…</element>

element.addEventListener('keydown', handler);

Example

Live example
<input onkeydown="this.nextElementSibling.textContent = 'Key: ' + event.key" placeholder="Press a key" style="padding:8px;"><span></span>

Best practices

  • Prefer element.addEventListener('keydown', handler) over the inline onkeydown attribute — it separates behavior from markup and allows multiple handlers.
  • Read event.key to identify the key — do not use the deprecated keyCode.
  • Make sure mouse interactions have keyboard equivalents so the page is operable without a mouse.
  • Call event.preventDefault() only when you intend to override the browser's default key behavior.

Frequently asked questions

What is the onkeydown event?
It runs JavaScript when a key is pressed down. In JavaScript the event is named keydown.
How do I detect which key was pressed?
Read event.key, which gives the character or a named value like "Enter", "Escape" or "ArrowUp".
Should I use keyCode or key?
Use event.key. The keyCode property is deprecated.
Should I use the onkeydown attribute or addEventListener?
Prefer addEventListener('keydown', …) in JavaScript. The inline onkeydown attribute works but mixes behavior into the markup and allows only one handler per element.