KeyboardEvent Properties: key, code, and Modifiers
You'll learn how to identify exactly which key was pressed and whether modifier keys like Ctrl or Shift were held down.
When handling keyboard events, the KeyboardEvent object provides crucial properties to understand what the user typed. Two essential properties help you identify keys:
event.key vs event.code
event.key tells you the character value produced by the key press. For example, pressing "a" gives "a", but pressing "Shift+a" gives "A". It represents what the user intended to type.
event.code tells you the physical key location on the keyboard, regardless of keyboard layout or modifiers. Pressing the "A" key always gives "KeyA", whether Shift is held or not.
Think of it this way: key is what appears on screen, code is the physical button pressed.
document.addEventListener('keydown', (event) => {
console.log(`Key: ${event.key}`); // "A" or "a"
console.log(`Code: ${event.code}`); // "KeyA"
});
Detecting Modifier Keys
Four boolean properties detect modifier keys held during the event:
event.ctrlKey–trueif Ctrl was heldevent.shiftKey–trueif Shift was heldevent.altKey–trueif Alt was heldevent.metaKey–trueif Meta (Command on Mac, Windows key) was held
document.addEventListener('keydown', (event) => {
if (event.ctrlKey && event.key === 's') {
event.preventDefault();
console.log('Ctrl+S pressed - Save action!');
}
});
This pattern is essential for creating keyboard shortcuts in web applications.
Key Takeaway: Use event.key for character input, event.code for physical key detection, and modifier properties (ctrlKey, shiftKey, altKey, metaKey) to detect key combinations.