Skip to content

Instantly share code, notes, and snippets.

@cvan
Last active August 1, 2016 13:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cvan/29b512ec0adc326dce88 to your computer and use it in GitHub Desktop.
Save cvan/29b512ec0adc326dce88 to your computer and use it in GitHub Desktop.
polyfill `event.key` for Chrome (and other non-Firefox browsers) - named keys
// Disclaimer: for now, this works for only US ASCII keyboards.
var KEYCODES_TO_KEYS = {
3: 'Cancel',
6: 'Help',
8: 'Backspace',
9: 'Tab',
12: 'Clear',
13: 'Enter',
16: 'Shift',
17: 'Control',
18: 'Alt',
19: 'Pause',
20: 'CapsLock',
27: 'Escape',
28: 'Convert',
29: 'NonConvert',
30: 'Accept',
31: 'ModeChange',
33: 'PageUp',
34: 'PageDown',
35: 'End',
36: 'Home',
37: 'ArrowLeft',
38: 'ArrowUp',
39: 'ArrowRight',
40: 'ArrowDown',
41: 'Select',
42: 'Print',
43: 'Execute',
44: 'PrintScreen',
45: 'Insert',
46: 'Delete',
48: ['0', ')'],
49: ['1', '!'],
50: ['2', '@'],
51: ['3', '#'],
52: ['4', '$'],
53: ['5', '%'],
54: ['6', '^'],
55: ['7', '&'],
56: ['8', '*'],
57: ['9', '('],
91: 'OS',
93: 'ContextMenu',
144: 'NumLock',
145: 'ScrollLock',
181: 'VolumeMute',
182: 'VolumeDown',
183: 'VolumeUp',
186: [';', ':'],
187: ['=', '+'],
188: [',', '<'],
189: ['-', '_'],
190: ['.', '>'],
191: ['/', '?'],
192: ['`', '~'],
219: ['[', '{'],
220: ['\\', '|'],
221: [']', '}'],
222: ["'", '"'],
224: 'Meta',
225: 'AltGraph',
246: 'Attn',
247: 'CrSel',
248: 'ExSel',
249: 'EraseEof',
250: 'Play',
251: 'ZoomOut',
};
var i = 0;
// Function keys (F1-24).
for (i = 1; i < 25; i++) {
KEYCODES_TO_KEYS[111 + i] = 'F' + i;
}
// Printable ASCII characters.
var letter = '';
for (i = 65; i < 91; i++) {
letter = String.fromCharCode(i);
KEYCODES_TO_KEYS[i] = [letter.toLowerCase(), letter.toUpperCase()];
}
// Polyfill `key` on `KeyboardEvent`.
var testKeyboardEvent = new KeyboardEvent('keydown');
if (!('key' in testKeyboardEvent)) {
Object.defineProperty(KeyboardEvent.prototype, 'key', {
get: function (x) {
var key = KEYCODES_TO_KEYS[this.which || this.keyCode];
if (Array.isArray(key)) {
key = key[+this.shiftKey];
}
return key;
}
});
}
window.addEventListener('keydown', function (e) {
console.log(e);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment