How to handle keyboard events?
Keyboard events in JavaScript let you detect when a user presses, holds, or releases a key. These are commonly used for things like shortcuts, form handling, and navigation.
๐ Types of Keyboard Events
- keydown โ Fires when a key is pressed down (fires repeatedly if the key is held).
- keypress โ (deprecated) โ Was used for character-producing keys only. Avoid using this.
- keyup โ Fires when a key is released.
โจ Example: Basic Key Handling
document.addEventListener("keydown", function(event) {
console.log("Key down:", event.key); // e.g., "a", "Enter"
});
document.addEventListener("keyup", function(event) {
console.log("Key up:", event.key);
});
๐ฏ Useful event Properties
- event.key โ The character value (e.g.,
"a","Enter","ArrowUp"). - event.code โ The physical key on the keyboard (e.g.,
"KeyA","ArrowLeft"). - event.altKey / event.ctrlKey / event.shiftKey / event.metaKey โ Boolean values indicating if modifier keys were pressed.
document.addEventListener("keydown", function(event) {
if (event.ctrlKey && event.key === "s") {
event.preventDefault(); // stop browserโs Save dialog
console.log("Ctrl + S shortcut detected!");
}
});
โจ๏ธ Example: Arrow Key Navigation
document.addEventListener("keydown", function(event) {
switch(event.key) {
case "ArrowUp":
console.log("Move up");
break;
case "ArrowDown":
console.log("Move down");
break;
case "ArrowLeft":
console.log("Move left");
break;
case "ArrowRight":
console.log("Move right");
break;
}
});
โ ๏ธ Best Practices
- Use
event.keyfor readable key names (instead of oldkeyCode). - Always use
preventDefault()if you donโt want the browserโs default action (like space scrolling). - Use event delegation if handling keys inside a specific input/area.
- Be mindful of accessibility โ donโt block standard navigation keys unnecessarily.
No comments yet! You be the first to comment.
