JavaScript Element keydown Event

Beginner
⏱️ 11 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
DOM event
Instance event

What You’ll Learn

The keydown event fires when a key is pressed. Learn addEventListener vs onkeydown, key vs code, modifiers, how it differs from keyup / keypress, IME tips, and five try-it labs.

01

Kind

Instance event

02

Type

KeyboardEvent

03

When

Key pressed down

04

Handler

onkeydown

05

Fields

key / code

06

Status

Baseline widely available

Introduction

Keyboard shortcuts, games, accessible menus, and Escape-to-close dialogs all start with knowing when a key goes down. The keydown event is that signal.

The event target is usually the focused element (an <input>, contenteditable host, button, and so on). If nothing suitable is focused, it may be Document or the root. The event bubbles.

💡
Beginner tip

Prefer event.key (and sometimes event.code) over legacy keyCode. Prefer keydown over the deprecated keypress event for modern apps.

Understanding keydown

An instance event that answers: “Did a key just go down (possibly repeating while held)?”

  • Fires when any key is pressed (including modifiers and arrows).
  • KeyboardEventkey, code, modifier flags, repeat, isComposing.
  • Handleronkeydown or addEventListener("keydown", ...).
  • Bubbles — can reach Document / Window.
  • May repeat while the key is held (event.repeat).
  • Baseline Widely available on MDN (since July 2015).

📝 Syntax

Use the event name with addEventListener, or set the handler property:

JavaScript
addEventListener("keydown", (event) => { });

onkeydown = (event) => { };

Event type

A KeyboardEvent (inherits from UIEvent and Event).

Handy properties

PropertyMeaning
keyKey value (e.g. "a", "Enter", "Escape")
codePhysical key id (e.g. "KeyA", "ArrowUp")
ctrlKey / shiftKey / altKey / metaKeyModifier flags active during the event
repeattrue when auto-repeat fires while the key is held
isComposingtrue during IME composition (between compositionstart/end)

⚠️ IME Composition & isComposing

During Input Method Editor (IME) composition (common for CJKT text), browsers may fire keydown events that you should ignore for shortcuts. MDN recommends skipping when event.isComposing is true, and also checking the legacy keyCode === 229 marker.

JavaScript
eventTarget.addEventListener("keydown", (event) => {
  if (event.isComposing || event.keyCode === 229) {
    return;
  }
  // handle shortcuts safely
});

⚡ Quick Reference

GoalCode / note
Listenel.addEventListener("keydown", fn)
Handler propertyel.onkeydown = fn
Detect Escapeif (event.key === "Escape")
Physical keyevent.code (e.g. "KeyS")
Ctrl/Cmd shortcutevent.ctrlKey || event.metaKey
MDN statusBaseline Widely available

🔍 At a Glance

Four facts to remember about keydown.

Event type
KeyboardEvent

UIEvent + Event

Means
key pressed

May auto-repeat

Prefer
key · code

Not legacy keyCode alone

Baseline
yes

Widely available

Examples Gallery

Examples follow MDN Element: keydown event. Focus a field, then press keys to see events.

📚 Getting Started

MDN listener patterns and the onkeydown property.

Example 1 — Log KeyboardEvent.code (MDN)

Append each physical key code while typing in an input.

JavaScript
const input = document.querySelector("input");
const log = document.getElementById("log");

input.addEventListener("keydown", logKey);

function logKey(e) {
  log.textContent += ` ${e.code}`;
}
Try It Yourself

How It Works

e.code identifies the physical key. Use e.key when you care about the produced character or named key (like "Enter").

Example 2 — onkeydown Property

Show both key and code for each press.

JavaScript
const field = document.getElementById("field");
const out = document.getElementById("out");

field.onkeydown = (event) => {
  out.textContent = "key=" + event.key + " code=" + event.code;
};
Try It Yourself

How It Works

Prefer addEventListener when you need multiple listeners or easy removal.

📈 Shortcuts, Arrows & IME

Build Escape handling, arrow navigation, and composition-safe shortcuts.

Example 3 — Escape Shortcut

Close a fake dialog when the user presses Escape.

JavaScript
const dialog = document.getElementById("dialog");
const out = document.getElementById("out");

document.addEventListener("keydown", (event) => {
  if (event.key !== "Escape") return;
  dialog.hidden = true;
  out.textContent = "Closed with Escape";
});
Try It Yourself

How It Works

Listening on document keeps the shortcut available even when focus is inside the dialog.

Example 4 — Arrow Key Movement

Move a box with arrow keys using event.key.

JavaScript
const box = document.getElementById("box");
const stage = document.getElementById("stage");
let x = 20;
let y = 20;

stage.tabIndex = 0; // make stage focusable
stage.focus();

stage.addEventListener("keydown", (event) => {
  const step = 10;
  if (event.key === "ArrowRight") x += step;
  else if (event.key === "ArrowLeft") x -= step;
  else if (event.key === "ArrowDown") y += step;
  else if (event.key === "ArrowUp") y -= step;
  else return;
  event.preventDefault();
  box.style.transform = "translate(" + x + "px," + y + "px)";
});
Try It Yourself

How It Works

preventDefault() stops the page from scrolling when arrows are used for custom movement.

Example 5 — IME-Safe Shortcut (MDN pattern)

Ignore composition keydowns before handling Ctrl/Cmd+S style actions.

JavaScript
const out = document.getElementById("out");

document.addEventListener("keydown", (event) => {
  if (event.isComposing || event.keyCode === 229) {
    return;
  }
  if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "s") {
    event.preventDefault();
    out.textContent = "Save shortcut handled";
  }
});
Try It Yourself

How It Works

The IME guard avoids treating composition keys as shortcuts. metaKey covers the Mac Command key.

🚀 Common Use Cases

  • Keyboard shortcuts (Save, Search, Escape to close).
  • Games and canvas controls (WASD / arrows).
  • Accessible menus and listbox arrow navigation.
  • Preventing default browser actions for custom key UX.
  • Detecting held keys with event.repeat.

🔧 How It Works

1

Focus matters

The focused element (or document) receives the event.

Target
2

Key goes down

keydown fires with key, code, modifiers.

Press
3

Optional repeat

Holding the key may fire more events with repeat: true.

Hold
4

keyup

When the key is released, keyup fires (target may differ after Tab).

📝 Notes

  • MDN: Baseline Widely available — no Deprecated / Experimental / Non-standard banner.
  • Prefer keydown / keyup over deprecated keypress.
  • Use key for meaning; use code for physical layout-independent keys.
  • Skip IME composition events for shortcuts (isComposing / keyCode === 229).
  • Related learning: input, keypress (deprecated), addEventListener(), JavaScript hub.

Browser Support

keydown is marked Baseline Widely available on MDN. Logos use the shared browser-image-sprite.png sprite from this project. KeyboardEvent key/code are the modern path across engines.

Baseline · Widely available

Element keydown

Fires when a key is pressed; works for all keys including modifiers and navigation.

Full Widely available
Google Chrome Full support
Yes
Mozilla Firefox Full support
Yes
Apple Safari Full support
Yes
Microsoft Edge Full support
Yes
Opera Full support
Yes
Internet Explorer Supported (prefer feature-detect modern key/code)
Partial
keydown Baseline

Bottom line: Safe default for shortcuts. Guard IME composition and prefer key/code over legacy keyCode alone.

Conclusion

keydown is the modern foundation for keyboard interaction: detect the press, read key / code, respect modifiers, and ignore IME noise when building shortcuts.

Continue with keypress (deprecated), addEventListener(), or the JavaScript hub.

💡 Best Practices

✅ Do

  • Use event.key / event.code for modern detection
  • Guard shortcuts with isComposing (and keyCode === 229)
  • Call preventDefault() only when you intentionally override browser behavior
  • Listen on document for global shortcuts when appropriate
  • Prefer addEventListener in production code

❌ Don’t

  • Rely on deprecated keypress for new features
  • Ignore IME composition in international text apps
  • Assume Tab’s keydown and keyup share the same target
  • Treat code as the displayed character without considering layout
  • Overwrite onkeydown if you need multiple listeners

Key Takeaways

Knowledge Unlocked

Five things to remember about keydown

Key pressed—read key/code, build shortcuts safely.

5
Core concepts
📄 02

KeyboardEvent

key · code · mods

API
03

vs keypress

prefer keydown

Modern
🔄 04

IME guard

isComposing

Safe
🎯 05

Baseline

widely available

Status

❓ Frequently Asked Questions

It fires when a key is pressed down. Unlike the deprecated keypress event, keydown fires for all keys — including modifier and navigation keys — whether or not they produce a character.
No. MDN marks Element keydown as Baseline Widely available. It is not Deprecated, Experimental, or Non-standard. (keypress is the deprecated relative.)
A KeyboardEvent (inherits from UIEvent and Event). Useful properties include key, code, altKey, ctrlKey, shiftKey, metaKey, repeat, and isComposing.
key is the value produced (for example 'a' or 'Enter'), considering layout and Shift. code is the physical key position (for example 'KeyA'), which stays the same across layouts.
keydown fires when the key goes down (and may repeat while held). keyup fires when the key is released. Shortcuts often listen on keydown; cleanup can use keyup.
Skip events when event.isComposing is true, and also when event.keyCode === 229 (legacy IME marker). MDN documents this for better CJKT compatibility.
Did you know?

After pressing Tab, the keydown target can differ from the keyup target because focus already moved. Always check event.target if your logic depends on which element is focused.

Next: keypress

See why the legacy character-key event is deprecated.

keypress →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

5 people found this page helpful