Adding keyboard input events in JavaScript

OpenJavaScript 0
Reading Time: 3 minutes 🕑

Last updated: September 27, 2022.

In some circumstances, you may want to add keyboard input events to your web page or app, such as when numeric input is required to make a calculation or for gaming.

Though it is a fairly straightforward process, there are several deprecated methods that can make the implementation of keyboard input problematic.

In this tutorial, we show you the right ways to add keyboard events to your web page or app in 2022.

Keyboard event types

To incorporate keyboard events, listen out for one of the following on the document object:

  1. keydown: fires when a key is pressed, provides code of key pressed
  2. keypress: fire when a key is pressed, provide code of which character is intended
  3. keyup: fired when a pressed down key is released

Each time a key is pressed, an event object is generated. You can check out these objects with the following code:

document.addEventListener('keydown', (event) => {
    console.log(event);
});

If you run this code and open the console log in your browser, the output will look something like this after some keys are pressed:

Keyboard input event objects logged to the console

These objects provide us with the necessary information to handle each key press. For example, you can see that the key and code property indicate the key pressed.

Now, we need to respond to this input.

Handling keyboard events

In each object generated by a key press, there are two properties you may want to use:

  • event.key: the logical value of the key pressed
  • event.code: based upon the physical position of the keys

We can see the values generated by pressing keys with the following code:

document.addEventListener('keydown', (event) => {
    console.log("event.key = " + event.key + "  " + "event.code = " + event.code);
});

This generates output like the following:

event.key and event.code values logged to the console

Notice that event.key and event.code generally match, but not always. The final two outputs were generated by pressing # and +. But event.code registered the values for these events as Backslash and BracketRight.

This is because the value of event.code is generated based on the physical placement of a key. Thus, it can often produce unintuitive results across different keyboard layouts.

For more predictable results, event.key is recommended.

From keyboard event to output

A simple way to handle the output is to append the event.key value to the DOM:

document.addEventListener('keydown', (event) => {
    document.body.append(event.key);
});

But is most situations, this is too simplistic. We instead need to specify what should have in response to a key press with a specific value, rather than using the value directly.

For example, when creating a JavaScript calculator, it would be undesirable for letters to be displayed.

Therefore, in most situations, it is a good idea to handle valid key presses inside an if...else statement:

document.addEventListener('keydown', (event) => {
    if (event.key == "0") {document.body.append("0")}
    else if (event.key == "1") {document.body.append("1")}
    else if (event.key == "2") {document.body.append("2")}
    else if (event.key == "3") {document.body.append("3")}
    else if (event.key == "4") {document.body.append("4")}
    else if (event.key == "5") {document.body.append("5")}
    else if (event.key == "6") {document.body.append("6")}
    else if(event.key == "7") {document.body.append("7")}
    else if(event.key == "8") {document.body.append("8")}
    else if(event.key == "9") {document.body.append("9")}
    else if(event.key == "+") {document.body.append("+")}
    else if(event.key == "-") {document.body.append("-")}
    else if(event.key == "*") {document.body.append("*")}
    else if(event.key == "/") {document.body.append("/")}
});

By handling each valid keyboard input in this way, non-valid keyboard input is ignored by default. So, in the above example, only the numbers 0-9 and +, -, * and / are appended to the DOM. Letters, for example, are not handled.

Summary

Adding keyboard events to your web page or app can greatly improve user experience, such as when input is required for a numeric calculation or for gaming.