Created
February 26, 2018 09:33
-
-
Save okj579/352d877ccd802f9b025da0ec07975846 to your computer and use it in GitHub Desktop.
Vanilla-JS Hotkeys
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
function hotkey(hotkeys, fn) { | |
hotkeys = hotkeys.split(' '); | |
function test(testObj, e) { | |
if (testObj.key !== e.key.toLowerCase()) return false; | |
for (var key in testObj) if (key !== 'key' && testObj[key] !== e[key]) return false; | |
return true; | |
} | |
var tests = hotkeys.map(function(hotkey){ | |
var testObj = { | |
shiftKey: false, | |
ctrlKey: false, | |
altKey: false, | |
metaKey: false, | |
isComposing: false | |
}, | |
keys = hotkey.toLowerCase().split('+'); | |
for (var i in keys) { | |
switch (keys[i]) { | |
case 'shift': | |
case 'umschalt': | |
testObj.shiftKey = true; | |
break; | |
case 'ctrl': | |
case 'strg': | |
testObj.ctrlKey = true; | |
break; | |
case 'alt': | |
case 'option': | |
testObj.altKey = true; | |
break; | |
case 'meta': | |
case 'win': | |
case 'super': | |
case 'mod4': | |
case 'command': | |
case 'propeller': | |
testObj.metaKey = true; | |
break; | |
case 'compose': | |
testObj.isComposing = true; | |
break; | |
default: | |
if (keys[i].length !== 1) throw new Error('Unknown key: ' + keys[i].toUpperCase()); | |
testObj.key = keys[i]; | |
} | |
} | |
return test.bind(null, testObj); | |
}); | |
window.addEventListener('keydown', function(e){ | |
for (var i in tests) if (tests[i](e)) { | |
e.hotkey = hotkeys[i]; | |
fn.call(this, e); | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment