skip to Main Content

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

3

Answers


  1. 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;
          }
        }
      });
    
    Login or Signup to reply.
  2. you can use JavaScript to detect the keypress event and changing 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>
    Login or Signup to reply.
  3. Since styles should be in CSS rather than in JavaScript, all you need is to Element.classList.toggle() a class (like ".is-active") on the <html> Element (the document.documentElement):

    addEventListener("keydown", (evt) => {
      if (evt.key === "a") document.documentElement.classList.toggle("is-active");
    });
    .is-active body { background-color: gold; }
    /* or like:   .is-active #someID { background-color: gold; } */

    For the "ć" key, well, simply use that character instead of "a"

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search