0

Detecting arrow key presses in JavaScript

keycodes are:

  • left = 37
  • up = 38
  • right = 39
  • down = 40
function checkKey(e) {
  
    e = e || window.event;

    if (e.keyCode == '38') {
        console.log('up arrow');
    }
    else if (e.keyCode == '40') {
        console.log('down arrow');
    }
    else if (e.keyCode == '37') {
       console.log('left arrow');
    }
    else if (e.keyCode == '39') {
        console.log('right arrow');
    }

}

document.onkeydown = checkKey;
<h1>
  Press arrow key
</h1>
h1 {
  font-size: 32px;
}
RUN
add comment
Suggest a different solution or add another example