JavaScript Keyboard Events: keydown
& keyup
JavaScript provides keyboard event listeners to detect when a key is pressed or released. The main events are:
1️⃣ keydown
→ Fires when a key is pressed down.
2️⃣ keyup
→ Fires when a key is released.
1️⃣ Basic Syntax
event.key
→ Returns the name of the pressed key (e.g.,"Enter"
,"a"
).event.code
→ Returns the physical key identifier (e.g.,"KeyA"
,"ArrowUp"
).
2️⃣ keydown
Example – Detect Key Press
✅ Fires when a key is pressed and held down.
3️⃣ keyup
Example – Detect Key Release
✅ Fires after a key is released.
4️⃣ Detecting Specific Keys (e.g., Enter & Escape)
✅ Use case: Handling form submission on Enter or closing a modal with Escape.
5️⃣ Prevent Default Behavior
To stop the default action (e.g., prevent scrolling with arrow keys):
6️⃣ keypress
(Deprecated)
🚨 The the keypress
event was used before, but it's now deprecated. Use keydown
instead.
7️⃣ Holding Down Keys
keydown
fires continuously if a key is held down, while keyup
fires once when released.
8️⃣ Detecting Key Combinations
You can detect multiple keys at once (e.g., Ctrl + S
for saving).
✅ Useful for custom shortcuts in web apps.
9️⃣ Example: Move a Box with Arrow Keys
✅ Try moving the red box using arrow keys! 🏃♂️
🔹 Summary
Event | When it Fires | Continuous? |
---|---|---|
keydown | When a key is pressed | ✅ Yes (if held) |
keyup | When a key is released | ❌ No |
keypress | 🚨 Deprecated | ❌ No |
✔ Use keydown
for real-time input.
✔ Use keyup
for actions after key release.
✔ Handle specific keys for shortcuts.
🔥 Need a custom keyboard interaction? Let me know!