docs.rodeo

MDN Web Docs mirror

Element: keypress event

{{APIRef}}  {{deprecated_header}} 

The keypress event is fired when a letter, number, punctuation, or symbol key is pressed, or else when the Enter key is pressed — including when the Enter key is pressed in combination with the Shift key or Ctrl key. Otherwise, when a modifier key such as the Alt, Shift, Ctrl, Meta, Esc, or Option key is pressed in isolation, the keypress event is not fired.

[!WARNING] Since this event has been deprecated, you should use beforeinput or keydown instead.

The event bubbles. It can reach {{domxref("Document")}}  and {{domxref("Window")}} .

Syntax

Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}} , or set an event handler property.

addEventListener("keypress", (event) => {});

onkeypress = (event) => {};

Event type

A {{domxref("KeyboardEvent")}} . Inherits from {{domxref("UIEvent")}}  and {{domxref("Event")}} .

{{InheritanceDiagram("KeyboardEvent")}} 

Event properties

This interface also inherits properties of its parents, {{domxref("UIEvent")}}  and {{domxref("Event")}} .

Examples

addEventListener keypress example

This example logs the {{domxref("KeyboardEvent.code")}}  value whenever you press a key after focussing the {{htmlelement("input")}}  element.

To see which keys cause a keypress event to fire, and which keys don’t, try pressing the following:

<div>
  <label for="sample">Focus the input and type something:</label>
  <input type="text" name="text" id="sample" />
</div>
<p id="log"></p>
const log = document.getElementById("log");
const input = document.querySelector("input");

input.addEventListener("keypress", logKey);

function logKey(e) {
  log.textContent += ` ${e.code}`;
}

{{EmbedLiveSample("addEventListener_keypress_example")}} 

onkeypress equivalent

input.onkeypress = logKey;

Specifications

{{Specifications}} 

Browser compatibility

{{Compat}} 

See also

In this article

View on MDN