Skip to content
← Back to Community
How do I detect if an arrow key is pressed in JS?
Profile icon
JoshuaRogers6

How do I detect if an arrow key is pressed in JS? I am using HTML, and JavaScript canvas on a project and need to detect arrow keys pressed.

Voters
Profile icon
JoshuaRogers6
Profile icon
lsikora
Comments
hotnewtop
Profile icon
Bookie0

Check this out:

The arrow keys have key codes, so for example the left arrow key has the code 37, right arrow key code is 39, up is 38, and down is 40.

Then you could use switch cases to determine which key was pressed:

document.onkeydown = function (event) { // to get the key switch (event.keyCode) { case 37: // if it's the left arrow console.log("Left key is pressed."); break; case 38: // if it's the up arrow console.log("Up key is pressed."); break; case 39: // if it's the right arrow console.log("Right key is pressed."); break; case 40: // if it's the down arrow console.log("Down key is pressed."); break; } };

Check the link I sent above for more :)

Good luck! :D

Profile icon
JoshuaRogers6

Thank you!

Profile icon
ZarmDev

function arrow() {
if (e.code == 'ArrowUp') {

}
if (e.code == 'ArrowDown') {

}
if (e.code == 'ArrowLeft') {

}
if (e.code == 'ArrowRight') {

}
}
document.addEventListener('keydown', arrow)

I used this in one of my projects, works but is not smooth.

Profile icon
lsikora

You use this

EventTarget. addEventListener()