Created
March 20, 2017 00:27
-
-
Save avioli/2ef519f12a5458e5d4ab8bcf34500a61 to your computer and use it in GitHub Desktop.
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
// From: https://hacks.mozilla.org/2017/03/internationalize-your-keyboard-controls/ | |
window.addEventListener('keydown', function(e) { | |
if (e.defaultPrevented) { | |
return; | |
} | |
// We don't want to mess with the browser's shortcuts | |
if (e.ctrlKey || e.altKey || e.metaKey || e.shiftKey) { | |
return; | |
} | |
// We try to use `code` first because that's the layout-independent property. | |
// Then we use `key` because some browsers, notably Internet Explorer and | |
// Edge, support it but not `code`. Then we use `keyCode` to support older | |
// browsers like Safari, older Internet Explorer and older Chrome. | |
switch (e.code || e.key || e.keyCode) { | |
case 'KeyW': // This is 'W' on QWERTY keyboards, but 'Z' on AZERTY keyboards | |
case 'KeyI': | |
case 'ArrowUp': | |
case 'Numpad8': | |
case 38: // keyCode for arrow up | |
changeDirectionUp(); | |
break; | |
// ... Other letters: ASD, JKL, arrows, numpad | |
default: | |
return; | |
} | |
e.preventDefault(); | |
doSomethingUseful(); | |
}); | |
// touch handling | |
// A real implementation would want to use touchstart and touchend as well. | |
window.addEventListener('touchmove', function(e) { | |
// don't forget to throttle the event | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment