Home  >  Q&A  >  body text

How to change background color (green/red) in empty HTML on certain keys?

Does anyone have a solution on how to change the background color in HTML when certain buttons are pressed, for example the letter A. Whenever I press the button, the color switches to another color (red to green, or green to red) and stays that way. But the good thing is that it works when I'm not focused on the web browser, so it also works when I'm using other apps through the browser. Sorry for the noob questions and language barrier. thank you for your reply.

Similar to this link, but should be on the key: How to change different background color using only one button

P粉211273535P粉211273535378 days ago523

reply all(2)I'll reply

  • P粉345302753

    P粉3453027532023-09-08 09:34:22

    You can use JavaScript to detect key events and change the background color

    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="UTF-8">
        <title>Change background color on keypress</title>
      </head>
      <body>
        <p>Press the 'A' key to change the background color!</p>
        <script>
          var colors = ["red", "green"];
          var currentColorIndex = 0;
          document.addEventListener("keypress", function(event) {
            if (event.key === "a" || event.key === "A") {
              var body = document.getElementsByTagName("body")[0];
              body.style.backgroundColor = colors[currentColorIndex];
              currentColorIndex = (currentColorIndex + 1) % colors.length;
            }
          });
        </script>
      </body>
    </html>

    reply
    0
  • P粉015402013

    P粉0154020132023-09-08 00:33:04

    I don't think it's possible to make it so that it activates when the A key is pressed from another window, because on most operating systems the keyboard automatically focuses to the focused window. There's probably an app for it, but it's really inconvenient to use (if you try to press the A key within the app, it takes you to the window).

    But if you do find a way, this is your answer. For reference, I'm assuming your site's background 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;
          }
        }
      });

    reply
    0
  • Cancelreply