HTML onkeydown Attribute

Beginner
⏱️ 6 min read
📚 Updated: Jun 2026
🎯 3 Examples
Events & Handlers

Introduction

The onkeydown attribute is an inline event handler that runs JavaScript when the keydown event fires — the moment a key is pressed down on the keyboard. Attach it to focusable elements like <input> and <textarea>, or listen on document / window with addEventListener for page-wide shortcuts. Use event.key to read which key was pressed (e.g. "Enter", "Escape", "a"). Common uses include keyboard shortcuts, game controls, and live key feedback. Prefer addEventListener("keydown", …) in production; avoid blocking alert() on every keystroke.

What You’ll Learn

01

Event handler

Inline JS.

02

keydown event

Key pressed.

03

event.key

Which key.

04

vs onkeyup

Down vs up.

05

addEventListener

Preferred way.

06

Shortcuts

Ctrl, Escape.

Purpose of onkeydown Attribute

The primary purpose of onkeydown is to respond to keyboard input as soon as a key goes down — before it is released. That makes it useful for games, editor shortcuts, “press Enter to search” patterns, and showing which key the user hit. Because keydown fires on every physical press (and repeats while a key is held), you can build responsive keyboard-driven UIs.

For detecting text changes in a field, use oninput instead. For detecting a key release, use onkeyup. Keyboard handlers should respect accessibility — do not trap Tab or Escape without a clear reason.

💡
Pass the event object

Use onkeydown="myFunction(event)" so your handler can read event.key, event.code, and modifier flags like event.ctrlKey.

📝 Syntax

Set onkeydown on a focusable element, or assign element.onkeydown:

onkeydown.html
<input type="text" onkeydown="myFunction(event)">

<script>
  function myFunction(e) {
    console.log("Key down:", e.key);
  }
</script>

Syntax Rules

  • Value is JavaScript executed when the keydown event fires.
  • Works on focusable elements and via document.addEventListener("keydown", …).
  • Pass event to access key, code, repeat, and modifiers.
  • Fires before the character appears in text inputs; use preventDefault() to block default action.
  • Repeats while a key is held down (event.repeat === true on repeat fires).
  • Modern alternative: element.addEventListener("keydown", handler).
  • The keydown event bubbles — delegation on a parent works.

💎 Values

The onkeydown attribute accepts a string of JavaScript code:

  • onkeydown="myFunction(event)" — Call a named function with the event.
  • onkeydown="logKey(event)" — Inline handler reference.
  • JavaScript: field.onkeydown = (e) => { … } assigns the handler.
onkeydown-js.html
document.addEventListener("keydown", (e) => {
  if (e.key === "Escape") {
    closeDialog();
  }
  if (e.ctrlKey && e.key === "s") {
    e.preventDefault();
    saveDocument();
  }
});

⚡ Quick Reference

Actionkeydown fires?Notes
Press a letter key in focused inputYesBefore character appears
Hold key downYes (repeats)event.repeat is true
Press Tab / Shift+TabYesDo not block without reason
Release key onlyNoUse onkeyup
Paste text (no key down in field)NoUse oninput
Handler attributeonkeydownInline on element

Applicable Elements

TargetSupported?Notes
<input>, <textarea>YesWhen focused
<button>, <select>YesSpace / Enter on button
tabindex="0" on divYesCustom keyboard targets
document / windowYesVia addEventListener
<div> without tabindexNoNot focusable — no key events

onkeydown vs onkeyup vs oninput

HandlerWhen it firesTypical use
onkeydownKey pressed downShortcuts, games, immediate response
onkeyupKey releasedActions after key lift
oninputValue changedLive search, character count

Examples Gallery

Show the pressed key, register with addEventListener, and clear a field with Escape.

👀 Live Preview

Focus the field and press keys — the last key appears below:

Last key: (none)

Example — Inline onkeydown on input

Log the key when the user presses down in a text field:

inline-onkeydown.html
<input type="text" onkeydown="logKey(event)">
<p id="keyOut"></p>

<script>
  function logKey(e) {
    document.getElementById("keyOut").textContent =
      "Key pressed: " + e.key;
  }
</script>
Try It Yourself

How It Works

The browser fires keydown when a key goes down while the input is focused. Passing event gives access to key details.

Dynamic Values with JavaScript

Attach the handler with addEventListener or the property form:

dynamic-onkeydown.html
<input type="text" id="dynamicField">

<script>
  document.getElementById("dynamicField").addEventListener("keydown", function (e) {
    document.getElementById("log").textContent = "Key pressed: " + e.key;
  });
</script>
Try It Yourself

How It Works

Register once at page load. The handler runs for every keydown while the field has focus.

Example — Escape to clear

Clear the input when the user presses Escape:

escape-onkeydown.html
const search = document.getElementById("search");

search.addEventListener("keydown", (e) => {
  if (e.key === "Escape") {
    search.value = "";
    search.blur();
  }
});
Try It Yourself

How It Works

Compare event.key to a string. No need for legacy keyCode unless supporting very old browsers.

♿ Accessibility

  • Do not block Tab — Avoid preventDefault() on Tab unless building a focused widget with proper trap semantics.
  • Document shortcuts — Tell users about custom keys (e.g. “Press Escape to close”).
  • Avoid alert() on keydown — Blocking dialogs interrupt screen readers and keyboard flow.
  • Prefer native controls — Buttons and links work with Enter/Space without custom key handlers.
  • Focus management — After Escape closes a panel, return focus to the element that opened it.

🧠 How onkeydown Works

1

Element has focus

Input or document.

Focus
2

User presses key

Physical key down.

Keyboard
3

keydown fires

onkeydown runs.

Event
=

Keyboard-driven UI

Shortcuts, games, feedback.

Browser Support

The keydown event and onkeydown handler are supported in all modern browsers — Chrome, Firefox, Safari, and Edge.

DOM Events · Fully supported

Universal onkeydown support

All major browsers fire keydown and honor the onkeydown handler on focusable elements.

99% Browser support
Google Chrome Fully supported
Full support
Mozilla Firefox Fully supported
Full support
Apple Safari Fully supported
Full support
Microsoft Edge Fully supported
Full support
Internet Explorer IE 9+ supported
Full support
Opera Fully supported
Full support
onkeydown attribute 99% supported

Bottom line: Use event.key and addEventListener for reliable keyboard handling across browsers.

💡 Best Practices

✅ Do

  • Pass event and use event.key for readable key checks
  • Use addEventListener("keydown", …) in production code
  • Use oninput when you care about value changes, not keys alone
  • Check event.repeat if repeat fires cause problems
  • Document custom keyboard shortcuts for users

❌ Don’t

  • Use alert() on every keydown
  • Block Tab or Escape without accessible alternatives
  • Rely on deprecated onkeypress for new projects
  • Use onkeydown alone for paste detection — use oninput
  • Attach handlers to non-focusable elements without tabindex

Conclusion

The onkeydown attribute runs JavaScript when a key is pressed down — essential for shortcuts, games, and immediate keyboard feedback.

Pass the event object, prefer addEventListener, and pair with oninput or onkeyup when those events fit better.

Key Takeaways

Knowledge Unlocked

Five truths every developer should know about onkeydown

Bookmark these before adding keyboard handlers.

5
Core concepts
📝 02

event.key

Which key.

API
🔄 03

vs oninput

Keys vs value.

Compare
04

Repeats

Held keys.

Gotcha
05

Don’t trap Tab

A11y first.

A11y

❓ Frequently Asked Questions

It runs JavaScript when the keydown event fires — when a key is pressed down while the element (or document) receives the event.
Focusable elements: input, textarea, button, select, links, and elements with tabindex. Also document via script.
onkeydown fires when the key goes down. onkeyup fires when it is released.
Use event.key (character or name like Enter) or event.code (physical key like KeyA).
addEventListener("keydown", handler) is preferred for production. Inline onkeydown works for learning.
Yes in all modern browsers; Internet Explorer 9+.

Master keyboard events

Practice the onkeydown attribute with key display and Escape-clear examples in the Try It editor.

Try onkeydown demo →

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