-2

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.

poopdealer43
  • 9
  • 1
  • 3
  • Yes, this is explained in the very first sentence of the [documentation](//developer.mozilla.org/en/docs/Web/API/Element/keypress_event) (right below the big deprecation warning). – Sebastian Simon Dec 25 '22 at 19:54

1 Answers1

0

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");
  }
})
Konrad
  • 21,590
  • 4
  • 28
  • 64