javascripthtmlcsskeyboard-input

HTML/CSS Single Key Input


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?


Solution

  • 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).