listen keydown swtich in javascript code example
Example 1: javascript detect arrow key press
document.addEventListener('keydown', 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;
}
});
Example 2: js detect right key click
document.addEventListener('keydown', function(e) {
var key = e.key || e.keyCode;
switch (key) {
case 'ArrowLeft': case 37:
alert('left');
break;
case 'ArrowUp': case 38:
alert('up');
break;
case 'ArrowRight': case 39:
alert('right');
break;
case 'ArrowDown': case 40:
alert('down');
break;
}
});