JS Keyboard events

·

2 min read

Mouse events are relatively simple: you've either clicked or moused down, moved or upped etc or you haven't. And we know what it is you did it on because that's what the event listener is on.

Keyboard events are harder.

Let's say you have a calculator in JavaScript. You've got it all working when you click the buttons, but want it to work when you use the keyboard too.

First, you don't put a keyboard event listener on a button, you put it on the document. Why? Because the listener needs to listen to what's in focus and when you use the keyboard, generally one of the calculator buttons won't be in focus. Maybe you require users to click on or tab to something on the calculator before they do anything else, in which case you can put your event listener on the calculator. But that would be a very strange design.

And then you have to work out which button on the keyboard the user pressed. And there are a multitude of ways of doing this. Doing

console.log(event);

will give you a whole load of information.

If I press "1" I get the following information:

  • code: "Digit1"
  • key: "1"
  • keyCode: 49
  • which: 49

In a lot of code you might see something like

if (event.keyCode === 49) {
  //do something
}

That's because once upon a time, that was the only information we had. These days, this is much easier to read:

if (event.key === '1') {
  //do something
}

There are other pitfalls. Some keys also do other things: for example the down arrow, page down and space keys will all scroll the page down. And therefore will scroll down as well as also doing whatever you've told them to do. event.preventDefault() is your friend here: but not if there's potential to scroll and your listener is on the document. Your user who wants to scroll with the keyboard will get very frustrated if it doesn't work.

To check exactly how the keys are named, without having to console log every single one, I recommend JavaScript Event KeyCodes