Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

5
  • .code corresponds to physical location of the key on the keyboard whereas .key corresponds to the character generated by the key pressed regardless of location. Commented Sep 22, 2017 at 15:36
  • 1
    Both 'code' and 'key' have quirks in modern browsers. Using the "Try it out" example on MDN developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code in different browsers shows that IE11/IE Edge don't implement 'code' and the 'key' implementation doesn't match the implementation in Chrome/FF/Safari (differences appear to mainly be in control characters like Escape and Enter). I think using a library might be easiest unless you're willing to account for these vagaries yourself. I really want this to be the answer, but IE screws this one up :-( Commented Feb 14, 2018 at 15:43
  • Hmm... actually it doesn't look too bad to implement key in a cross browser way. Regular alphanumeric keys just return their value and for control keys (escape, enter, tab, etc) appear implemented identically in most browsers except IE11/Edge which implement an older version of the spec, so at least there are only two possible values for each key. Commented Feb 14, 2018 at 15:53
  • I would advise using key instead of code. For example, if you have a keyboard with media control keys, pressing Play/Pause outputs "MediaPlayPause" for key and "" for code. Commented Mar 21, 2018 at 22:45
  • IMO nothing will ever be dropped from browser implementations because this would break many existing sites and libraries. Commented Jul 19, 2021 at 7:42