The HTML onkeypress event
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
<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 inlineonkeypressattribute; 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 onkeypress event?
keypress.How do I detect which key was pressed?
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?
event.key. The keyCode property is deprecated.Should I use the onkeypress attribute or addEventListener?
keypress is deprecated. Use addEventListener('keydown', …) with event.key, or listen for input/beforeinput to react to the text changing.