Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do you detect directional arrow keypresses in JavaScript?

I’m trying to detect keypresses on the left and right arrow keys. Here is my current code (nothing gets printed):

this.addEventListener('keypress', event => {
    if (event.key == "ArrowLeft") {
        console.log("Left key");
    } else if (event.key == "ArrowRight") {
        console.log("Right key");
    }
});

I’ve tried console.log(event.key) and pressing the directional arrow buttons as well, but again, nothing gets printed.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

As you can read here keypress event is deprecated and shouldn’t be used

Use keydown or keyup instead

window.addEventListener('keydown', event => {
  if (event.key == "ArrowLeft") {
    console.log("Left key");
  } else if (event.key == "ArrowRight") {
    console.log("Right key");
  }
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading