Search code examples
javascripthtmlcssbuttonevents

How to change background colors (green/red) in empty HTML on certain keypress?


Does someone has solution on how to change background color in HTML on certain button press, example letter A. Whenever I press button A color switches to other color (red to green, or green to red), and stays that way. But bonus would be that it works when I'm not focused on web browser, so it can work when I use other app over browser. Sorry for noob question and language barrier. Thank you for replies.

Similar to this link, but should be on presskey button: how to change different background colors using only one button


Solution

  • I don't think it's possible to make it so that when the A key is pressed from another window, it'll activate, since on most operating systems, the keyboard is automatically focused to the window that's focused. There could possibly be an application for it, but it would be really inconvenient to use (if you're trying to press the A key inside of that app, it'll go to your window instead).

    But, if you do find a way, here's your answer. For reference, I would assume that the background of your website is already red.

          let isRed = true;
      document.addEventListener('keydown', (event) => {
        if (event.key === 'a') {
          if (isRed) {
            document.body.style.backgroundColor = 'green';
            isRed = false;
          } else {
            document.body.style.backgroundColor = 'red';
            isRed = true;
          }
        }
      });