loading...
Cover image for "Checking which keyboard key was pressed" in JavaScript (update for 2020)

"Checking which keyboard key was pressed" in JavaScript (update for 2020)

hanakivan profile image Ivan Hanák ・6 min read

"This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time."

This message might have surprised you if you checked an article on MDN (https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode) about handling which key on the keyboard was pressed.

And your worry about this code:

document.addEventListener('keydown', e => {
    if(e.keyCode === 13) {
        //enter was pressed
    } else if (e.keyCode === 27) {
        //esc was pressed
    }
});

... is actually correct - you should not be using keyCode 😤 .

How should you handle and check which key was pressed then? 🤔

Time and again, once an obsolete javascript feature has been deprecated a completely new would emerge, that would be even more powerful than was we known before.

In this article I am going to walk you through the new approach so as you can completely ditch keyCode and happily start using the new recommended way.

Table of contents:

  1. The old way .keyCode
  2. The new way: code and key
    • 2.1 How to differentiate which physical key was pressed
    • 2.2 How to get a value of the key that was pressed
    • 2.3 Differentiating "a textual representation and an actual value"
  3. Recap
    • 3.1 What's the difference between .code and .key?
    • 3.2. Where do I find all of the possible value for both the .code and the .key?
    • 3.3 What's the browser support for both the .code and the .key?

1. The old way with Event.keyCode

Before we dive into the new recommended way of checking which key was pressed, let's quickly recap the old functionality, so as we know exactly how it worked and what use cases we need to replace.

So for this purpose let's use the very standard functionality on the web, and that is "close the modal window after pressing ESC".

Let's say you have a landing page with a popup and once the user presses ESC in their keyboard, you would make it disappear. This is how we would approach it up until now:

import Modal from 'modal';

document.addEventListener("keydown",  e => {
    //code 27 is a code of a key ESC on your keyboard
    if(e.keyCode === 27)  {
        e.preventDefault();
        Modal.closeModal();
    }
});

Simple, right? Every key on our keyboard has some code, for example the aforementioned ESC key is 27, ENTER is 13 and so on. You can check out others keys' codes on this website: https://keycode.info/.

It was super easy and super straightforward 🙂 .

Me personally could not fully comprehend the reason behind the deprecation because I've never encountered the issue that keyCode caused. For me also the reason is currently not so important since I love learning new things and this is a perfect opportunity to do so.

If you however would like to know more details about the deprecations, check out very good article on MDN that explains exactly that 👉 https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode.

2. The new way: code and key

So what's the new way then?

In order to fully comprehend the new way, I split it into two parts. One is identifying which physical key on your keyboard is pressed and the other one is getting the actual value of the key being pressed.

It may seem more work, but I think that being that explicit it makes the development way easier.

2.1 How to differentiate which physical key was pressed

The new and recommended way of checking, which key was pressed on the keyboard is by using the Event's property called code.

The code property is a string value that might look like "ArrowLeft", "KeyQ", "Backspace", "BracketRight" and so on.

Really important thing to grasp is, that code property is a string representation of a physical key and not the actual character being written!

For example on a very widely used keyboard with QWERTY layout, once you press "Q" on your keyboard, the property code value will be "KeyQ". But provided that you switched to some crazy keyboard layout via your operating system, for example a Bulgarian keyboard, after pressing a key "Q", the character being written is "," (a comma), but the value of the .code property would still be "KeyQ".

//QUERTZ keyboard layout
//bulgarian keyboard set via OS
document.addEventListener("keydown", e => {
    //by pressing "Q" letter on your keyboard, the bulgarian keyboard will print "," (a comma), but you will get information about the physical key being pressed 
    console.log(e.code); // prints "KeyQ"
});

So that basically mean, that no matter the physical layout of the keyboard, you can still get 100% accurate information what physical key was pressed - and that is super useful, right? 😎

2.2 How to get a value of the key that was pressed

I don't think this was quite possible to accomplish this in a nice way that would be also cross-browser.

But this problem will no longer be a problem with the new update. The new update is the new Event's property called .key.

.key is a string representation of the actual character being written - or in other words, the exact opposite of what the .code property does.

Let's look at the example mentioned above with application of .key property:

//QUERTZ keyboard layout
//bulgarian keyboard set via OS
document.addEventListener("keydown", e => {
    //by pressing "Q" letter on your keyboard, the bulgarian keyboard will print "," (a comma) and you will get the value of the key being pressed
    console.log(e.key); // prints ","
});

2.3 "textual representation and the actual value" are not the same

A word of caution guys here, by employing .key property in your code, you will not get the exact value of what is being written, even though it might seem in lots of cases. For example even though in most cases you will get an actual value of what is being written, there is also a situation, in where for example the .key property you will get a string "Shift". By pressing a dead key (https://en.wikipedia.org/wiki/Dead_key) on your keyboard, you will get a string "Dead" and not an empty string as might be expected.

To get an actual value of what is really being written into an input field, there are two ways, that cane be used:

3. Recap

I think to really understand the difference between the two keys we need to put it all together:

3.1 What's the difference between .code and .key?

To get the textual representation of a physical key being pressed:

  • use Event.code

To get the textual representation of the actual character being written:

  • use Event.key

3.2. Where do I find all of the possible value for both the .code and the .key?

All of the possible values for .code can be found here:

All of the possible values for .code can be found here:

  • developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values

3.3 What's the browser support for both the .code and the .key?

It's actually very good and you can start using the both properties right now.

The only browser that does not support them is Internet Explorer - but for many of us that is no wonder and probably not an issue at all.

Final thoughts

There you have it guys. A new and updated way of checking, which key was pressed on the keyboard is here. Even though it looks straightforward, I think we are going to experience lot of fun with those two properties, because there is already an interesting situation here, since when using .code property and pressing ESC key on your keyboard, most of web browsers will return "Esc" as a value, but our favourite product from Microsoft called EDGE will return "Escape"; when pressing arrows on your keyboard, majority of web browsers will use "ArrowLeft", "ArrowUp"... but EDGE and Firefox will use "Left", "Up" ... and so on 😂😂 .

For me personally it is not understandable at all why there always has to be a black sheep amongst browsers, but who knows, maybe it is supposed be that way!

Anyways, because of that it is a perfect opportunity for people to create custom libraries that takes care of similar browser inconsistencies and that's exactly what I did as well. I created this JS library for cross-browser checking, which key was pressed and you can check it out on this link: https://www.npmjs.com/package/@ivanhanak_com/keycodes.

You can check it out, I will be grateful for any feedback you will have and also let me know in the comments, what JavaScript issue you would like to have explained in detail the next time!

I will be continuing writing similar articles in the future and if you don't want to miss them or would like to be informed about new updates in JavaScript, subscribe to my newsletter right here.

Anyways, thanks for reading and I’ll see you in the next article! 🤓

Yours in coding,

Ivan

--

Credits for the image: Photo by Raphael Nogueira on Unsplash

Posted on by:

hanakivan profile

Ivan Hanák

@hanakivan

#softwareengineer 👨‍💻 · #blogger 📝 · #thoughtspammer 🥺 · #businessstudent 🕴️

Discussion

pic
Editor guide