Switching background colors (green/red) in an HTML void when a specific key is pressed - What's the trick?

Is there a solution available for changing the background color in HTML when a specific button is pressed, like the letter A? I want the color to switch from red to green or green to red when button A is pressed, and I would like it to stay that way even if I am not focused on the web browser. Apologies for the basic question and any language barriers. Thank you in advance for any responses.

I found a link similar to what I am looking for, but it changes the background color based on a button click: how to change different background colors using only one button

Answer №1

JavaScript can be utilized to detect when a key is pressed and dynamically change the background color.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Changing background color on keypress event</title>
  </head>
  <body>
    <p>Press the 'A' key to see the magic happen!</p>
    <script>
      var colors = ["blue", "yellow"];
      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>

Answer №2

It may not be achievable to trigger an action when the A key is pressed from a different window because most operating systems automatically focus the keyboard on the active window. While there might be potential applications for this functionality, it could prove cumbersome to use, as pressing the A key within the designated app may result in activating your own window instead.

If you do manage to discover a workaround, here is a proposed solution: Assuming the background color of your website is initially set to 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;
      }
    }
  });

Answer №3

To keep your styles organized in CSS rather than JavaScript, you can easily toggle a class (such as ".is-active") on the <html> Element (the document.documentElement) using Element.classList.toggle():

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

As for the key "ć", simply replace "a" with that character in your code.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Animating an element from its center with pure CSS

I've dedicated countless hours to uncovering a solution that can be achieved using only CSS. My goal is to create an animation on a div element where its height and width decrease uniformly when hovered over. <div class="a"></div> Above ...

Guide to vertically aligning text in an overlay using CSS within Angular 2

I currently have an overlay on my page that displays a spinner (an Angular material component) and accompanying text. This overlay covers the entire page and prevents clicking on elements below it. The spinner is positioned in the center of the page, and ...

Beginner tips for adding padding in CSS

Could anyone clarify a discrepancy in the material provided here: w3schools.com code example According to the code : th,td { padding:5px; } Also, based on their explanation here: http://www.w3schools.com/cssref/pr_padding.asp The explanation states tha ...

Using Jquery Mobile to make an AJAX POST request with XML

Is it possible to use this code for XML parsing? I have successfully parsed using JSON, but there is no response from the web service. This is the status of the webservice: http/1.1 405 method not allowed 113ms $j.ajax({ type: "GET", async: false, ...

Spinning an object smoothly in the opposite direction of the OrbitControls camera's y rotation in three.js

Is there a way to use OrbitControls in three.js to make a planeMesh always remain facing the camera? I've attempted some code but it's not quite working as expected. I want the planeMesh to slowly readjust its orientation only when the camera mov ...

What is the best way to display a particular JavaScript variable in an HTML document?

Is there a way to display the value of a Javascript variable in an HTML form, such as showing it on the screen? Below is my JavaScript code: <script type="text/javascript"> var howLongIsThis = myPlayer.duration(); </script> The variable howL ...

Tips for effectively managing JSON data in my application

I'm working on a project to create a website that monitors the number of coronavirus cases in my country. The data is organized and stored in a file called cases.json using the following structure: { day: { city: { cases: 1 } ...

Steps to access the Link URL when the class name transforms to display as block:

I'm currently working on a function that needs to trigger a click on a link only if a specific classname is set to display: block; Unfortunately, my coding skills are not advanced enough to accomplish this task. Here is what I have so far: https://j ...

The ability to submit a conversation chat is currently

I encountered an issue when attempting to submit a chat, and I received the error message 'handlebar is not define'. I followed the code tutorial provided in this link: https://codepen.io/drehimself/pen/KdXwxR This is the screenshot of the error ...

What is the best way to access the width property within the style attribute of a span element with a specific class

https://i.sstatic.net/1YQdP.png Currently, I'm attempting to extract the content inside "width: 100%" and specifically the numerical part. My approach involves using beautifulsoup in Python, and you can see the snippet of my code below: rat ...

How can I set up a cycling image background for the main div and a floating menu?

I was wondering how I could keep a cycling image background stationary behind the main content while scrolling through the page. You can check out the project itself by following this link. Feel free to use any of the code, including the fixed header menu, ...

Using the React Router <Link> component inside a conditional ternary statement

I am trying to incorporate a Ternary operator into React JSX, specifically for creating a conditional React Router Link tag like so: <Table.Cell>{`${user.company !== null ? <Link to={`/companies/${user.company._id}`}>`${user.company.name}`< ...

Mysterious data organization - transform into an object

As I interact with an API, there is a value that I cannot quite pinpoint. My goal is to transform this string into a JavaScript object, but the process seems complex and confusing. Does anyone have insight on what this data represents and how it can be co ...

Experiencing a problem with the 'circle-color' data-driven styling feature in Mapboxgl.js & GeoJSON, yet everything is functioning correctly with the default color

I have been attempting to generate a map, plot data points using GeoJSON and Mapbox. Everything goes smoothly when I use a default color code for all points, but as soon as I try to implement data driven styling to assign different colors based on differen ...

Modify only unprocessed text within the HTML content

Consider the following string: html_string = '<span><span class=\"ip\"></span> Do not stare <span class=\"img\"></span> at the monitor continuously </span>\r\n' I am looking to ...

What is the best way to add multiple images into this particular class?

My code works fine for uploading a single image to my database, but I need to upload multiple images. I have three columns in my database table: e_img, e_img2, and e_img3. How can I upload image URLs to these 3 columns? This is my Upload class: ...

Validation errors are nowhere to be found post ajax submission of a rails form

My form validations stopped working when using ajax-rails. Upon submitting an empty form that should trigger validation, it seems like the validation rules are not being applied and the backend log indicates that the empty form was posted. Strangely, every ...

The function getoffer does not exist

I am encountering an issue with my factory declaration for Malls. It seems that I am getting the error message get offer is not a function! .controller('confirmCtrl', function($scope,Malls,$stateParams,$log) { $scope.offers = Malls.g ...

JavaScript library imports function correctly in Chrome but encounter issues in Internet Explorer

I'm currently working with ASP.NET MVC 5 and encountering an issue when trying to incorporate various JavaScript libraries such as jQuery, bootstrap.js, and others. While it's functioning well in Chrome, I'm facing compatibility problems in ...

Is it possible to transfer functions between components in React-Native, even if they are located in separate files?

In one of my classes, there's a method that I need to call. Specifically, the () => this.props.navigation.navigate('Detail'). Originally, I had a button on each FeedCard for navigation, but it seemed messy so I switched to using touchable ...