1. keydown
The keydown event is triggered as soon as a key on the keyboard is pressed down.
This event will repeat if the key is held down, depending on the operating system and browser settings.
document.addEventListener('keydown', function(event) {
console.log(`Key pressed: ${event.key}`);
});
2. keyup
The keyup event is triggered once a key on the keyboard is released.
It is often used in conjunction with keydown to determine the duration a key was pressed or to trigger an action after text input.
document.addEventListener('keyup', function(event) {
console.log(`Key released: ${event.key}`);
});
3. keypress
The keypress event is triggered when a character key is pressed and released. It doesn't get triggered for non-character keys (like Shift, Ctrl, Alt, or the arrow keys).
It's less common nowadays due to keydown and keyup being more versatile, but it can still be useful for character input detection.
document.addEventListener('keypress', function(event) {
console.log(`Key typed: ${event.key}`);
});
Common properties of the event object:
event.key: Represents the value of the key pressed.
event.code: Represents the physical key on the keyboard (independent of keyboard layout).
event.shiftKey: true if the Shift key was held down during the event, else false.
event.ctrlKey: true if the Ctrl key was held down during the event, else false.
event.altKey: true if the Alt key was held down during the event, else false.
event.metaKey: true if the Command key (Mac) or Windows key (Windows/Linux) was held down during the event, else false.
Tips:
To detect specific key combinations, you can use the properties like event.key along with event.shiftKey, event.ctrlKey, etc.
document.addEventListener('keydown', function(event) {
if (event.ctrlKey && event.key === 'a') {
console.log('CTRL + A was pressed!');
}
});
Remember, different browsers may have slight variations in how they handle keyboard events, so always test across multiple browsers when developing.