MDN self-hosted library · e01.org

KeyboardEvent: keyCode property

Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.

js
window.addEventListener("keydown", (event) => {
  if (event.defaultPrevented) {
    return; // Should do nothing if the default action has been canceled
  }

  let handled = false;
  if (event.key !== undefined) {
    // Handle the event with KeyboardEvent.key
    handled = true;
  } else if (event.keyCode !== undefined) {
    // Handle the event with KeyboardEvent.keyCode
    handled = true;
  }

  if (handled) {
    // Suppress "double action" if event handled
    event.preventDefault();
  }
});