Find Any JavaScript Keycode by Pressing the Key
Writing a keyboard shortcut means knowing exactly what the browser reports for a key, and that is easy to get wrong. This JavaScript keycode finder shows the live KeyboardEvent values for whatever you press: event.key, event.code, the legacy keyCode, location, the active modifiers and whether the event is an auto-repeat. Your own browser, keyboard layout and operating system produce the values, so what you see is what your handler will receive.
event.key vs event.code vs keyCode
event.keyis the character or named key produced, respecting layout and Shift:"a","A","Enter","ArrowUp". Use it when the meaning matters, such as "save on S".event.codenames the physical key position, ignoring layout:"KeyA","Digit1","NumpadEnter". Use it for games and WASD controls, where the position matters on AZERTY and QWERTY keyboards alike.keyCodeis a deprecated number (Enter is 13, A is 65). It is inconsistent across layouts and browsers, so only read it when you maintain old code.
event.location tells left from right modifiers and numpad keys: 0 is standard, 1 left, 2 right and 3 numpad. That is how you tell the two Shift keys apart.
Example: a Ctrl+S handler
Pressing Ctrl + S on a US layout generates this snippet:
document.addEventListener('keydown', (event) => {
if (event.ctrlKey && event.key === "s") {
event.preventDefault();
// ...
}
});
// Physical key (layout independent): event.code === "KeyS"
The preventDefault() call stops the browser's own Save dialog. On macOS users expect Cmd, which shows up as metaKey, so many apps check event.ctrlKey || event.metaKey.
Common pitfalls
- Shift changes
event.key. Shift + S reports"S", not"s", and Shift + 1 reports"!"on a US layout. - Some shortcuts never reach the page. Combinations reserved by the OS or browser, like closing a tab, are handled before JavaScript sees them.
- IME input. While composing text in Chinese or Japanese, keydown can report
"Process"(keyCode 229) andisComposingis true, so skip shortcuts then. - Held keys repeat. Check
event.repeatif an action should fire once per press.
To test a pattern on shortcut strings, try the regex tester, and to see the Unicode code point behind a character such as "é", use the Unicode character inspector.
Privacy
Key presses are read only inside the key pad while it has focus, and nothing is logged or sent anywhere. Everything runs in your browser.