KeyboardEvent Key Normalizer

1.1.0 · active · verified Sun Apr 19

`keyboard-key` is a lightweight utility library designed to provide a consistent and reliable way to determine the `KeyboardEvent.key` property from keyboard events across different browsers, addressing inconsistencies in native browser implementations. Released as version 1.1.0, this package aims to normalize keyboard event key values, stepping in where `KeyboardEvent.key` lacked full cross-browser support or where older, deprecated properties like `keyCode` and `which` were still in use. It differentiates itself by attempting to infer key values, including interpreting shift key presses, which, while helpful for `en-US` layouts, introduces a locale-specific caveat. The library also offers `getCode()` for obtaining normalized `keyCode` values and provides constants for common key codes, promoting the use of modern `KeyboardEvent.key` semantics while providing a fallback.

Common errors

Warnings

Install

Imports

Quickstart

This code snippet demonstrates how to import and use `getKey()` and `getCode()` to normalize keyboard events, and how to use the provided key code constants for robust keyboard input handling.

import { getKey, getCode, Escape } from 'keyboard-key';

document.addEventListener('keydown', (event: KeyboardEvent) => {
  const key: string = getKey(event);
  const code: number = getCode(event);

  console.log(`Key pressed: ${key}, Code: ${code}`);

  switch (key) {
    case 'Escape':
      console.log('Escape key detected via getKey!');
      break;
    case 'Enter':
      console.log('Enter key detected via getKey!');
      break;
    default:
      break;
  }

  // Using getCode with named constant
  if (code === Escape) {
    console.log('Escape key detected via getCode and constant!');
  }
});

// Simulate keydown events for demonstration purposes in a browser-like environment.
// In a real application, these would come from user interaction.
setTimeout(() => {
  const escapeEvent = new KeyboardEvent('keydown', { key: 'Escape', keyCode: 27, which: 27 });
  document.dispatchEvent(escapeEvent);
}, 100);

setTimeout(() => {
  const enterEvent = new KeyboardEvent('keydown', { key: 'Enter', keyCode: 13, which: 13 });
  document.dispatchEvent(enterEvent);
}, 200);

view raw JSON →