Key Code Constants

3.1.0 · active · verified Wed Apr 22

keycode-js is a JavaScript package providing a comprehensive set of constants for keyboard events, specifically mapping to KeyboardEvent.keyCode, KeyboardEvent.code, and KeyboardEvent.key properties. The current stable version is 3.1.0. The package maintains a steady release cadence, incorporating new key event codes and values while addressing compatibility and consistency across browser environments. A key differentiator is its provision of constants for all three KeyboardEvent properties, allowing developers to choose the most appropriate and future-proof method for handling keyboard input. It also ships with TypeScript types, enhancing developer experience in TypeScript projects, and offers direct support for Deno environments.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to import and use key code, key value, and key event constants from `keycode-js` within a browser's keyup event listener, showing both modern and deprecated approaches.

import * as KeyCode from 'keycode-js';

window.addEventListener('keyup', function(e) {
  // It's recommended to check 'code' or 'key' properties for modern browsers.
  // 'keyCode' is deprecated by the W3C.

  // Check the code value (e.g., 'Enter').
  if (e.code === KeyCode.CODE_RETURN) {
    console.log('It was the Return key using event.code.');
    return;
  }

  // OR, check the key value (e.g., 'Enter').
  if (e.key === KeyCode.VALUE_RETURN) {
    console.log('It was the Return key using event.key.');
    return;
  }

  // OR, check the keyCode value (e.g., 13) (deprecated).
  if (e.keyCode === KeyCode.KEY_RETURN) {
    console.log('It was the Return key using deprecated event.keyCode.');
    return;
  }

  console.log('It was any other key:', e.key, e.code, e.keyCode);
});

view raw JSON →