DEV Community

Discussion on: JavaScript detecting which key is pressed

Collapse
 
lexlohr profile image
Alex Lohr

Here's an interesting thing. A keypress will yield a slightly different event than a keyup. For example, pressing the 'ö' on a german keyboard will get you

// keypress (removed some noise)
{
altKey: false,
charCode: 246,
code: "Semicolon", // this is ignoring other keyboard layouts!
ctrlKey: false,
key: "ö", // correct
keyCode: 246, // the correct char code
location: 0,
metaKey: false,
shiftKey: false,
type: "keypress",
which: 246, // the correct char code
}
// keyup (removed some noise)
{
altKey: false,
charCode: 0,
code: "Semicolon", // this is ignoring other keyboard layouts!
ctrlKey: false,
key: "ö", // correct
keyCode: 192, // not the char code
location: 0,
metaKey: false,
shiftKey: false,
type: "keyup",
which: 192, // not the char code
}
Enter fullscreen mode Exit fullscreen mode

So if you want the code of the character and not of the key, you'll want the keypress, not the keyup event.

Collapse
 
filatovv profile image
Yuri Filatov

Thank you for such wonderful information!

Collapse
 
dailydevtips1 profile image
Chris Bongers

Ah yes correct, I'll get to the keyup in a next one actually for a specific reason, but valid point thanks Alex!

Collapse
 
priitpu profile image
Priit

According to MDN, the keypress event is deprecated and should not be used in new websites.

Collapse
 
lexlohr profile image
Alex Lohr

Not yet deprecated, though it might be at some point in the future: w3c.github.io/uievents/#event-type...