Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

KeyboardEvent: key values and auto-repeat

Use `key` to identify the key value and `repeat` to distinguish an initial press from automatic repeats while a key is held down.

Version: ECMAScript 2024 and the current web platform; runtime support varies

Syntax

event.key     // string, read-only
 event.repeat  // boolean, read-only
new KeyboardEvent("keydown", { key: "Enter", repeat: true })

KeyboardEvent.key/repeat refers to two read-only properties on a keyboard event. key is a string, such as "Enter", "a", or "A". It reflects the keyboard layout and active modifiers such as Shift. Unlike code, which identifies the physical key position, key can change between events if a modifier changes.

repeat is a boolean. For real keydown events, it is false on the initial press and true on subsequent events generated by auto-repeat. It does not tell you whether a key is currently down. Not all keys repeat, and the repeat rate depends on the environment.

To run an action once per Enter press, check event.key === "Enter" && !event.repeat in a keydown handler. If the action should repeat while the key is held, do not filter out events based on repeat.

KeyboardEvent is a web platform API, not part of ECMAScript 2024. Do not assume it exists in every JavaScript runtime; check support in your target environment.

Examples

{
  function handleKeydown(event) {
    if (event.key !== "Enter" || event.repeat) return;
    console.log("activate");
  }

  handleKeydown({ key: "Enter", repeat: false });
  handleKeydown({ key: "Enter", repeat: true });
  handleKeydown({ key: "Escape", repeat: false });
}

Result

activate

Run the code in Node.js or a browser console. It passes three plain objects with `key` and `repeat` directly to the handler instead of creating keyboard events. Only the first makes the handler log `activate`; this tests the condition, not the repeat rate.

Related lessons

  • JavaScript · Lesson 34 · Intermediate · Version: 3
  • JavaScript · Lesson 35 · Intermediate · Version: 3
  • JavaScript · Lesson 38 · Intermediate · Version: 3

Sources