Checking for Keyboard Events in JavaScript with Cross-Browser Support

What We Used To Do — And Still Do

How to Follow the Spec and Support All Browsers

Use event.key first with graceful degradation to event.keyCode

var key = event.key || event.keyCode;

Other Fallback Options

Add the Event Listener

Prefer the use of document over window when adding event listeners.

document.addEventListener('keyup', function (event) { });
  1. Prefer the use of document over window when adding event listeners. They’re consequentially the same, but document is closer to DOM elements than window is. So, adding listeners on document prevents the window from receiving them, which keeps the window clean and uninvolved with any keypress listeners. (source)
  2. Use keyup as the trigger event for UX reasons. For most behaviors (not games), people typing expect that the key they have pressed won’t get “entered” until they release the button. That’s why you don’t want to use keydown, probably (I say probably because there are cases where you do want to listen for keydown instead). They also expect that holding down a key won’t trigger the associated action unless they’re typing (If you are intercepting and reproducing regular text entry to this degree, my advice would be to re-evaluate whether you really need to do that. You probably don’t.). That’s why you don’t want to use keypress, probably. keypress also can't be used with Alt, Shift, or Ctrl.

The Add Listener Function

if (event.defaultPrevented) {
return;
}
var key = event.key || event.keyCode;
if (key === 'Escape' || key === 'Esc' || key === 27) { }
doWhateverYouWantNowThatYourKeyWasHit();

Put It All Together

function keyListener(event) {
if (event.defaultPrevented) {
return;
}

var key = event.key || event.keyCode;

if (key === 'Escape' || key === 'Esc' || key === 27) {
doWhateverYouWantNowThatYourKeyWasHit();
}
}
document.addEventListener('keyup', keyListener);

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

MAY CHALLENGE~ LEETCODE/DAY- 2/

Trigger Firebase Storage Image Resize with Cloud Functions

Introducing Watchers in Vue JS

Designing a scalable application with Elixir: from umbrella project to distributed system

RxJS Subjects Explained with Examples

The For Loop Is Dead. Long Live the For Loop 👑

Asynchronous and Synchronous

REAL DOM VS VIRTUAL DOM!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Stephen

Stephen

More from Medium

Config ESLint, Prettier in Typescript React App.

[Frontend] One-way binding vs Two-way binding

Understanding Array.sort() Method In JavaScript

JavaScript syntax for CRUD operations