References

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

The HTML onkeypress event

Event Updated
Quick answer

The onkeypress attribute is deprecated. It ran JavaScript when a character-producing key was pressed. In modern code use onkeydown for key handling, or oninput / onbeforeinput to react to text changes.

Overview

The onkeypress event attribute runs JavaScript when a character key is pressed (deprecated). In JavaScript the event itself is named keypress. Drop the on prefix when you call addEventListener.

It is a keyboard event. The handler receives a KeyboardEvent exposing key (the character produced, such as "a" or "Enter"; non-character keys like "ArrowLeft" and "Escape" never fire keypress, so use keydown for those) and modifier flags such as ctrlKey and shiftKey.

You can wire this up with the inline onkeypress HTML attribute or with addEventListener, but neither is right for new code: keypress is deprecated. Listen for keydown with event.key, or for input/beforeinput when you want to react to the text actually changing.

Deprecated. The keypress event is deprecated. Use onkeydown with the event.key property instead.

Syntax

<!-- Deprecated. Prefer onkeydown / oninput. -->
<input onkeypress="handler(event)">

Example

Live example
<input onkeypress="this.nextElementSibling.textContent = 'Pressed: ' + (event.key || '')" placeholder="Type here" style="padding:8px;"><span></span>

Best practices

  • Prefer element.addEventListener('keypress', handler) over the inline onkeypress 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 onkeypress event?
It runs JavaScript when a character key is pressed (deprecated). In JavaScript the event is named keypress.
How do I detect which key was pressed?
Read event.key, which gives the character produced, such as "a" or "Enter". Non-character keys like "Escape" and the arrow keys never fire keypress, so use keydown for those.
Should I use keyCode or key?
Use event.key. The keyCode property is deprecated.
Should I use the onkeypress attribute or addEventListener?
Neither in new code: keypress is deprecated. Use addEventListener('keydown', …) with event.key, or listen for input/beforeinput to react to the text changing.