-
Notifications
You must be signed in to change notification settings - Fork 26
Description
Prologue
We've all been there, all you want to do is check for a specific key event, like the character "?". So you go through the normal routines of Googling for the keycode, because you cannot just use "?", so you find out the keycode (or is it charcode?) is 191. You put in the JavaScript to check for the "?" keypress...
$('body').keyup(function (e) {
if((e.keyCode || e.charCode) === 191) { // 191 is ?, because, y'know, that makes sense
doStuff();
}
});Then you get French users complaining that their Azerty keyboards don't work when you use this because they have a different keyboard layout (shift+, gets them question mark, for US/UK Qwerty keyboards its shift+/). Then you get complaints from Opera users, because in Opera, ? actually has a keyCode of 47. So now you're code looks like:
$('body').keyup(function (e) {
if((e.keyCode || e.charCode) === 191 || (e.keyCode || e.charCode) === 47) {
doStuff();
}
});Why isn't there a simple answer for this?!
DOM Level 3 Specification
So it turns out W3C DOM Level 3 events specification actually has some details to simplify this. It describes a KeyboardEvent.key attribute which will be populated with printable characters, if they are printable (e.g 1, A, or ?), otherwise, it has a standard set of names for all other keyboard characters (see here: http://www.w3.org/TR/DOM-Level-3-Events/#key-values-list). There is also a KeyboardEvent.char attribute which will give a unicode representation of the key. Secondary to this there is also a KeyboardEvent.location which can tell you where in the keyboard the button was pressed, which can determine between the left/right ctrl keys, or if the device is a mobile phone, etc.
Proposal
We should push all browsers to adopt the DOM Lvl3 specs for KeyboardEvent.key, KeyboardEvent.char and KeyboardEvent.location.
Bug Links
- Firefox/Mozilla: https://bugzilla.mozilla.org/show_bug.cgi?id=680830
- Webkit/Chrome/Safari: ???
- Opera: ???