Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.
Let’s now dive into keyboard events.
There are two types of events when using the keyboard:
keydownthe keyboard key has been pressedkeyupthe keyboard key has been released
keydown is also fired repeatedly while the key is held down.
While you typically listen to mouse and touch events on a specific element, it’s common to listen for keyboard events on the document object:
document.addEventListener('keydown', event => {
// key pressed
})
The parameter passed to the event listener is a KeyboardEvent.
This event object, in addition to the Event object properties, offers (among others) these unique properties:
altKeytrue if alt key was pressed when the event was firedcodethe code of the key pressed, returned as a stringctrlKeytrue if ctrl key was pressed when the event was firedkeythe value of the key pressed, returned as a stringlocalethe keyboard locale valuelocationthe location of the key on the keyboardmetaKeytrue if the meta key was pressed when the event was firedrepeattrue if the key is repeating (e.g. the user is holding the key down)shiftKeytrue if the shift key was pressed when the event was fired
The demo is a keylogger that will show you the values of some of the properties I listed above.
Lessons in this unit:
| 0: | Introduction |
| 1: | Handling events |
| 2: | The `DOMContentLoaded` event |
| 3: | The `event` object |
| 4: | Mouse events |
| 5: | ▶︎ Keyboard events |
| 6: | `preventDefault()` |
| 7: | Stopping event propagation |
| 8: | Bubbling and capturing |
| 9: | Form submit event |
| 10: | Input fields events |
| 11: | Creating custom events |
| 12: | ▶︎ Keyboard Events |
| 13: | Mouse Events |
| 14: | Touch Events |
| 15: | Form Events |