Skip to content

Instantly share code, notes, and snippets.

@kragen
Created June 8, 2015 23:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kragen/d2110a995b74ebafc919 to your computer and use it in GitHub Desktop.
Save kragen/d2110a995b74ebafc919 to your computer and use it in GitHub Desktop.
A JavaScript micro-library for cross-browser keyboard event handling.
// This is an attempt to paper over the keycode differences between
// Gecko and WebKit (e.g. Iceweasel or Firefox and Chrome or
// Chromium), somewhat following the model of Mousetrap:
// <https://github.com/ccampbell/mousetrap>.
// The mapping tables herein are far from comprehensive, implementing
// more or less only what I need for this calculator.
function decodeKeyEvent(event) {
return decodeKeyEventProperties(event.key, event.keyCode, event.shiftKey);
}
var decodeKeyEventProperties = (
function() {
function decodeKeyEventProperties(key, keyCode, shift) {
if (key) return key;
var c =
_keyCodeMap[keyCode] || String.fromCharCode(keyCode).toLowerCase();
return (shift ? shifted(c) : c);
}
// Keys which, in WebKit browsers (and I guess IE?), have the
// wrong codes, or which have symbolic names in DOM 3.
// Too bad ← maps to % and → maps to ', no? ' in WebKit is 222.
// Fortunately Firefox gives us DOM 3 `key`, so this won’t break
// Firefox.
var _keyCodeMap = {187: '=', 189: "-", 191: "/",
37: "Left", 39: "Right",
222: "'", 8: "Backspace"};
var unshiftedKeys = "`1234567890-=,"
, reshiftedKeys = "~!@#$%^&*[]_+<"
;
var shiftMap = {};
for (var i = 0; i < unshiftedKeys.length; i++) {
shiftMap[unshiftedKeys.charAt(i)] = reshiftedKeys.charAt(i);
}
return decodeKeyEventProperties;
function shifted(c) {
return shiftMap[c] || c.toUpperCase();
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment