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 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 onkeypress HTML attribute, but the modern, recommended approach is element.addEventListener('keypress', 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.

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 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 onkeypress attribute or addEventListener?
Prefer addEventListener('keypress', …) in JavaScript. The inline onkeypress attribute works but mixes behavior into the markup and allows only one handler per element.