Understanding JavaScript Keyboard Events
Master the differences between event.key, event.code, and the deprecated event.keyCode with practical examples and best practices.
Table of Contents
Introduction
When building interactive web applications, capturing keyboard input is a common requirement. JavaScript provides several properties on keyboard event objects to identify which key was pressed. However, the differences between event.key
, event.code
, and the deprecated event.keyCode
can be confusing.
This comprehensive guide will break down each property, explain when to use them, and provide practical examples to help you make the right choice for your applications.
The Modern Standard: event.key
The event.key
property returns a string representing the printed value of the key. If the key is a character key, it returns the character itself (e.g., "a"
, "$"
, " "
). For non-character keys, it returns a descriptive name (e.g., "Enter"
, "ArrowLeft"
, "Backspace"
).
Key Features
- Value: The actual character or name of the key
- International Friendly: Works across keyboard layouts
- Modern Standard: Widely supported in current browsers
Best Use Cases
- Text input handling
- Keyboard shortcuts (Ctrl+S, etc.)
- Form submission on "Enter"
Example Code
document.addEventListener('keydown', (event) => { console.log('Key pressed:', event.key); if (event.key === 'Enter') { console.log('Enter key pressed!'); } if (event.key === 's' && event.ctrlKey) { console.log('Save shortcut pressed!'); event.preventDefault(); } });
The Physical Key: event.code
The event.code
property returns a string representing the physical key that was pressed on the keyboard, ignoring the current layout or language. The value is based on the standard US QWERTY layout.
Key Features
- Value: Physical key code (e.g., "KeyA", "Digit1")
- Layout Independent: Same regardless of keyboard layout
- Consistent: Always represents the same physical key
Best Use Cases
- Gaming controls (WASD keys)
- Layout-independent shortcuts
- Creative applications
Real-World Example:
On a French AZERTY keyboard, pressing the "A" key (which is where "Q" is on a QWERTY keyboard) will produce event.key: "a"
and event.code: "KeyQ"
.
Example Code
document.addEventListener('keydown', (event) => { console.log('Physical key:', event.code); // WASD movement (works on any keyboard layout) switch (event.code) { case 'KeyW': moveUp(); break; case 'KeyA': moveLeft(); break; case 'KeyS': moveDown(); break; case 'KeyD': moveRight(); break; } });
The Deprecated Relic: event.keyCode
The event.keyCode
property returns a number representing the key. This was the original way to identify keys, but it is now deprecated and should be avoided in modern development.
Why You Should Avoid It
- Inconsistent: Values vary between browsers and operating systems
- Not Standardized: Never had a formal standard, leading to implementation quirks
- Layout Dependent: Not reliable for international users
- Deprecated: Officially deprecated in favor of modern alternatives
Legacy Example (Don't Use This)
// DON'T DO THIS - Deprecated approach document.addEventListener('keydown', (event) => { if (event.keyCode === 65) { // 'A' key console.log('A key pressed'); } if (event.keyCode === 13) { // Enter key console.log('Enter pressed'); } });
Side-by-Side Comparison
Property | Value Type | Example | Best For | Status |
---|---|---|---|---|
event.key | String | "a", "#", "Enter" | Text input, shortcuts, UI actions | Recommended |
event.code | String | "KeyA", "Slash", "Enter" | Gaming, layout-independent controls | Recommended |
event.keyCode | Number | 65, 13, 32 | Legacy browser support only | Deprecated |
Practical Examples
Form Handling with event.key
const searchInput = document.getElementById('search'); searchInput.addEventListener('keydown', (event) => { if (event.key === 'Enter') { performSearch(event.target.value); } else if (event.key === 'Escape') { clearSearch(); } });
Game Controls with event.code
const gameControls = { KeyW: () => player.moveUp(), KeyA: () => player.moveLeft(), KeyS: () => player.moveDown(), KeyD: () => player.moveRight(), Space: () => player.jump() }; document.addEventListener('keydown', (event) => { const action = gameControls[event.code]; if (action) { action(); event.preventDefault(); } });
Best Practices
Use event.key for Most Cases
For text input, form handling, and most UI interactions, event.key
is your best choice. It's intuitive and works well across different keyboard layouts.
Use event.code for Physical Key Mapping
When you need consistent physical key mapping (like game controls), use event.code
. This ensures your controls work the same way regardless of the user's keyboard layout.
Avoid event.keyCode
Only use event.keyCode
if you absolutely must support very old browsers. For modern development, stick with event.key
and event.code
.
Conclusion
Understanding the differences between event.key
, event.code
, and event.keyCode
is crucial for building robust keyboard interactions in web applications.
For most modern web development, you should prefer event.key
. When you need to track physical keys regardless of layout, event.code
is the reliable choice. Avoid event.keyCode
unless you're supporting legacy browsers.
Ready to Practice?
Use KeyPress.io's interactive tester to see these properties in action with any key on your keyboard!
Try the Interactive Tester