Skip to main content
javascript

JavaScript key events: use key and code, not keyCode

Use KeyboardEvent.key for user intent and KeyboardEvent.code for physical-key shortcuts; keyCode is legacy.

Thien Nguyen
By Thien Nguyen
Updated April 3, 2026 · 1 min read

For a keyboard shortcut, prefer event.key when the meaning matters and event.code when the physical key position matters. Do not start new code with keyCode; it is deprecated and fails badly across layouts and input methods.

window.addEventListener('keydown', (event) => {
  if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 'k') {
    event.preventDefault();
    openSearch();
  }
});
PropertyExampleUse it for
key"k", "Enter", "ArrowLeft"The character or logical key
code"KeyK", "NumpadEnter"A physical keyboard location
repeattrueSuppressing held-key repeats

Keep shortcuts accessible

Do not hijack browser and assistive-technology shortcuts. Ignore shortcuts while a text input is receiving ordinary typing unless the shortcut includes an explicit modifier. For custom controls, use actual <button> elements where possible so Enter and Space behaviour comes for free.

keydown is for commands. beforeinput and input events are better tools for observing text entry, especially with IMEs and mobile keyboards.

Test a non-US layout and keyboard navigation before declaring a shortcut done. The reference is small; the edge cases are in the user's keyboard, browser, and assistive technology.

References

Primary documentation and specifications checked when this article was last updated.

javascriptaccessibilityweb-development

Related articles

All articles