Created
June 8, 2015 23:20
-
-
Save kragen/d2110a995b74ebafc919 to your computer and use it in GitHub Desktop.
A JavaScript micro-library for cross-browser keyboard event handling.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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