References

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

The HTML onkeyup event

Event All modern browsers Updated
Quick answer

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

Overview

The onkeyup event attribute runs JavaScript when a key is released. In JavaScript the event itself is named keyup — 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 onkeyup HTML attribute, but the modern, recommended approach is element.addEventListener('keyup', 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 onkeyup="handler()">…</element>

element.addEventListener('keyup', handler);

Best practices

  • Prefer element.addEventListener('keyup', handler) over the inline onkeyup 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 onkeyup event?
It runs JavaScript when a key is released. In JavaScript the event is named keyup.
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 onkeyup attribute or addEventListener?
Prefer addEventListener('keyup', …) in JavaScript. The inline onkeyup attribute works but mixes behavior into the markup and allows only one handler per element.