The HTML onkeyup event
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 inlineonkeyupattribute — it separates behavior from markup and allows multiple handlers. - Read
event.keyto identify the key — do not use the deprecatedkeyCode. - 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?
keyup.How do I detect which key was pressed?
event.key, which gives the character or a named value like "Enter", "Escape" or "ArrowUp".Should I use keyCode or key?
event.key. The keyCode property is deprecated.Should I use the onkeyup attribute or addEventListener?
addEventListener('keyup', …) in JavaScript. The inline onkeyup attribute works but mixes behavior into the markup and allows only one handler per element.