Keyboard events
Coding with JavaScript
🕑 This lesson will take about 10 minutes
There are two different types of keyboard events we can work with:
keydown - this event is triggered when a button on the keyboard has been pressed down
keyup - this event is triggered when a button that has been pressed on the keyboard is released
Using an event listener, we can detect when keydown or keyup events occur and we can also check which key was pressed by checking the key property of the event.
keydown example
In the example below, an event listener is used to detect a keydown event. The keydown event is triggered as soon as a key on the keyboard is pressed down. When a keydown event occurs, the paragraph element with the ID “result” will display a message that includes the name of the key that was pressed.
keyup example
In the example below, an event listener is used to detect a keyup event. The keyup event is triggered when a key that has been pressed down is released. When a keyup event occurs, the paragraph element with the ID “result” will display a message that includes the name of the key that was released.
Checking if a specific key has been pressed
Using the event’s key property, you can check if a specific key was pressed in a conditional statement. For example, in the code below, we will check if the ‘A’ key has been pressed, and if so, display a message to the user.
The key and keyCode event properties
In these examples, we have used the key property to check which key has been pressed. The key property is a string value representing the name of a key (eg. ArrowLeft) whereas the keyCode property is a numeric value representing the key pressed (eg. 37). It is recommended to use the key value. You can find a list of the key and keyCode values used in JavaScript here.