Key up and key down events in JS return a bunch of information in the Event object. This information includes the keycode data. In this tutorial we discuss how to get that info with JS.

Fingers pressing keys on a keyboard

When pressing keys on a keyboard, JavaScript can catch a few events: keydown, keyup, and keypress.

To get the keycode of an event, we use either the keydown or the keyup event, like this:

1
2
3
4
5
document.addEventListener('keydown', callBack);

function callBack(evt) {
    console.log(evt.keyCode)
}

For example, once we’ve run the above code in the console, then focused back on the browser’s webpage window, and pressed, for example, the β€œa” key on the keyboard, we’d get this value printed to the console: 65.

That means that the β€œa” key on the keyboard has the key code of 65.

Now we can do something whenever a user types the β€œa” key, like this:

1
2
3
4
5
6
7
8
9
10
document.addEventListener('keydown', callBack);

function callBack(evt) {
    if (evt.keyCode === 65) {
        alert("You pressed this key: 'a'");
        return;
    } else {
        console.log(evt.keyCode)
    }
}



Note:
This exercise comes from Book 3 of my book series on JS, available on Leanpub.com.