How JavaScript Keyboard Events Work
In modern web development, the KeyboardEvent interface
provides several properties to describe a user's key interaction. This tool visualizes the most critical
ones.
Key Properties Explained
- event.key: Represents the value of the key pressed. If you press "a", it prints "a". If you press Shift+"a", it prints "A". This is the standard for text input.
- event.code: Represents the physical key on the keyboard. Left Shift is always
ShiftLeft, regardless of language layout. - event.which / keyCode: Deprecated legacy properties returning a numeric code. Still widely used in older codebases.
- Modifiers: Booleans like
ctrlKey,shiftKey,altKeyindicating if a modifier key was held down.
Common Use Cases
1. Game Controls
Using event.code ensures that WASD movement keys work
correctly regardless of the user's keyboard layout (e.g. AZERTY vs QWERTY).
2. Keyboard Shortcuts
Implementing hotkeys like Cmd+S (Save) or Ctrl+Z (Undo) by checking modifier flags.
3. Form Navigation
Listening for the Enter key to submit forms or
Escape to close modals.
4. Input Validation
Blocking non-numeric input in legacy applications by checking
keyCode.
FAQ
Why are event.which and keyCode deprecated?
key and code.
How to distinguish Left Shift vs Right Shift?
event.code. Left returns ShiftLeft, Right returns
ShiftRight.
Difference between event.key and event.code?
event.key is the character generated (layout dependent), while
event.code is the physical key (layout independent).
What is the Meta key on Windows?
What is event.location?
How to prevent default key action?
event.preventDefault() in your handler. e.g. prevent F5 from refreshing.
Does this work on mobile keyboards?
What is the code for Enter?
keyCode is 13, code is "Enter", and key is "Enter".
More Free Tools
JSON Formatter
Format, validate, and minify JSON instantly with error highlighting.
CSS Box Shadow Generator
Create smooth, layered shadows. Real-time preview with inset support and one-click CSS copy.
Color Converter
Convert between HEX, RGB, HSL, and CMYK formats with real-time preview.
Chmod Calculator
Interactive Chmod permission grid. Convert between numeric (755) and symbolic (rwxr-xr-x) formats.
Base Converter
Convert numbers between Binary, Octal, Decimal, and Hexadecimal instantly.
Regex Tester
Real-time regular expression tester with highlighting and cheat sheet.