Keyboard events
Discover the basics of working with keyboard events in JavaScript
React Masterclass
Launching on November 4th
There are 3 types of events when interacting with keyboard events:
keydownthe keyboard key has been pressedkeyupthe keyboard key has been released
keydown is also fired when the key repeats while the button stays pressed.
While mouse and touch events are typically listened on a specific element, it’s common to listen for keyboard events on the document:
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 us (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 meta key was pressed when the event was firedrepeattrue if the key has been repeated (e.g. the key has not been released)shiftKeytrue if shift key was pressed when the event was fired
This demo is a keylogger which will show you the values of some of the properties I listed above: https://codepen.io/flaviocopes/pen/LopWmq/
I wrote 20 books to help you become a better developer:
- JavaScript Handbook
- TypeScript Handbook
- CSS Handbook
- Node.js Handbook
- Astro Handbook
- HTML Handbook
- Next.js Pages Router Handbook
- Alpine.js Handbook
- HTMX Handbook
- React Handbook
- SQL Handbook
- Git Cheat Sheet
- Laravel Handbook
- Express Handbook
- Swift Handbook
- Go Handbook
- PHP Handbook
- Python Handbook
- Linux/Mac CLI Commands Handbook
- C Handbook