Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

KeyboardEvent: key value and text composition state

Use `key` to recognize a key's meaning and `isComposing` to avoid triggering a shortcut while an input method is still composing text.

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

Syntax

event.key // string, read-only
 event.isComposing // boolean, read-only

// event is a KeyboardEvent instance.
// To construct a synthetic event:
new KeyboardEvent("keydown", { key: "Enter", isComposing: true })

KeyboardEvent.key/isComposing refers to two read-only properties on a KeyboardEvent instance: event.key and event.isComposing. They are web platform APIs, not part of ECMAScript 2024, and support depends on the runtime.

key is a string that reflects the keyboard layout and modifiers: for example, "a" or "A" with Shift on a typical layout. Special keys have named values such as "Enter" and "Escape". If the browser cannot identify the key, it reports "Unidentified". Unlike code, key does not describe the physical key position. To observe text changes, listen for input instead of reconstructing text from keystrokes.

isComposing is a per-event boolean. For a browser-generated event, it is true if the event occurred after compositionstart and before compositionend. An input method editor (IME) can use Enter to accept a text candidate, so skip your shortcut in a keydown handler when isComposing is true.

At the start or end of composition, event ordering can leave isComposing false even when the IME handles the key. Test the browser and IME combinations you support. If needed, consider event.keyCode === 229 as a deprecated compatibility fallback, not a universal guarantee.

Examples

{
  const shouldRunShortcut = (event) =>
    event.key === "Enter" && !event.isComposing;

  for (const options of [
    { key: "Enter", isComposing: true },
    { key: "Enter", isComposing: false },
    { key: "Escape", isComposing: false },
  ]) {
    // Without KeyboardEvent, test the predicate with a plain object.
    const event = typeof KeyboardEvent === "function"
      ? new KeyboardEvent("keydown", options)
      : options;
    console.log(shouldRunShortcut(event) ? "run" : "skip");
  }
}

Result

skip
run
skip

Run this with Node.js or in a supported browser's console. If `KeyboardEvent` is unavailable, the example uses plain objects with the same test values. Only Enter outside composition logs `run`. The example does not dispatch events or activate a real IME.

Related lessons

  • JavaScript · Lesson 41 · Intermediate · Version: 3

Sources