1

I am developing the Snake game to practice my HTML/JS/CSS skills. I want to have a menu screen that lets the user choose the keyboard keys that control the left/right/up/down movements. I know that I could use an input tag and limit the maximum length to 1, but I want to allow for keys such as Spacebar and the Enter key to be included. Is there a simple way to allow a user to just press and key on their keyboard and have their key press stored and displayed somehow using HTML/JS/CSS?

bmb
  • 361
  • 2
  • 13
  • 1
    Wait, you say that you want to practice your JavaScript skills, but then you ask if this can be done using HTML and CSS? Can you not use JavaScript? (I also notice that the question isn't tagged with JavaScript...) – OOPS Studio Mar 08 '21 at 06:56
  • @OOPSStudio Good points.. I made adjustments to my post based on your comment. – bmb Mar 08 '21 at 06:58
  • Ah cool, thanks! I wasn't trying to make any point, I was actually genuinely curious. Glad to have it cleared up now. – OOPS Studio Mar 08 '21 at 07:00

1 Answers1

2

You can use keydown and keyup.

document.addEventListener('keydown', function(event) {
   console.log(event);
   if (event.key == 'ArrowDown') {
      event.preventDefault(); // prevent it from doing default behavior, like downarrow moving page downward
   }
});

You should run event.preventDefault() if the pressed key is a key your game is using, that way it doesn't mess with page behavior (such as downarrow scrolling the page down).

cseitz
  • 1,116
  • 4
  • 16