How to change background color (green/red) in empty HTML on certain keys?
P粉211273535
P粉211273535 2023-09-07 10:08:19
0
2
621

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粉211273535
P粉211273535

reply all(2)
P粉345302753

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>
P粉015402013

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;
      }
    }
  });
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template