Skip to content

Instantly share code, notes, and snippets.

@royce002
Created February 6, 2020 02:53
Show Gist options
  • Save royce002/4dec4bd0849b907a72d71aa8ecd0e8e3 to your computer and use it in GitHub Desktop.
Save royce002/4dec4bd0849b907a72d71aa8ecd0e8e3 to your computer and use it in GitHub Desktop.
This little function detects the arrow keys on a keyboard. 2 Functions , one in an if else and the other in a switch case.
document.onkeydown = checkKey;
function checkKey(e) {
e = e || window.event;
if (e.keyCode == '38') {
// up arrow
}
else if (e.keyCode == '40') {
// down arrow
}
else if (e.keyCode == '37') {
// left arrow
}
else if (e.keyCode == '39') {
// right arrow
}
}
/*************************/
document.onkeydown = function(e) {
switch (e.keyCode) {
case 37:
alert('left');
break;
case 38:
alert('up');
break;
case 39:
alert('right');
break;
case 40:
alert('down');
break;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment