Inspecting CSS values through Javascript is an important aspect of front

How can I create a JavaScript function that checks my CSS code and changes the background color to #29fd53 if it is currently #222327? Likewise, how do I make it switch back to #222327 if the current background color is #29fd53?

This is my JavaScript code:

function changeBgC(){
var body = document.getElementsByTagName("body")[0];

var computedStyle = window.getComputedStyle(body)

var bodyBackgroundValue = computedStyle.getPropertyValue("background-color")
console.log(bodyBackgroundValue);
if (bodyBackgroundValue == "#222327") {
    document.querySelector('body').style.backgroundColor = "#29fd53"
  } else {
    document.querySelector('body').style.backgroundColor = "#222327"
  }
}
.body{
    width: 100%;
    height: 100vh;
    min-height: 100vh;
    background: #222327;
}
<div class="box">
<button onclick="changeBgC()" class="menuButton">≣</button>
</div>
          

I tried using i++ in my code (by adding an onclick event in my HTML) but it only changes the background color to #29fd53. Pressing the button again doesn't trigger any change.

Here's what I attempted:

function changeBgC(){
    var i = 0
    if (i % 2 === 0){
        document.querySelector('.body').style.backgroundColor = "#29fd53"
        console.log(i);
        i+=1
    }else{
        document.querySelector('.body').style.backgroundColor = "#222327"
        i+=1
    }
}

Answer №1

The issue is with how you've defined the i variable within the function scope. Each time changeBgC() is called, it resets i to 0.

To fix this, declare i outside the function so that its value persists between function calls.

let i = 0;
function changeBgC(){
    if (i % 2 === 0){
        document.querySelector('.body').style.backgroundColor = "#29fd53";
        console.log(i);
        i+=1;
    }else{
        document.querySelector('.body').style.backgroundColor = "#222327";
        i+=1;
    }
}

Answer №2

To achieve this, consider using a class in place of a function. This allows for encapsulation of the i variable. Private members (#) were utilized within the class since they are not needed outside of it.

class background {

#i=0;
#elem=document.body.style;

change() {
  this.#i=!this.#i;
  this.#elem.backgroundColor = this.#i?"#29fd53":"#222327";
 }
}

bkg=new background();
.body{
    width: 100%;
    height: 100vh;
    min-height: 100vh;
    background: #222327;
}
<div class="box">
<button onclick="bkg.change();" class="menuButton">≣</button>
</div>
          

Answer №3

As previously mentioned by @Teemu, the getComputedStyle() function returns an rgb() value. To obtain the HEX code, you can utilize a CSS variable instead of creating a conversion function from RGB to HEX.

The trim function is utilized to eliminate trailing spaces.

function changeBgC(){
  let bgColor = getComputedStyle(document.body).getPropertyValue('--bg-color').trim();
  if(bgColor == "#222327"){
    document.body.style.setProperty('--bg-color', '#29fd53');
  } else {
    document.body.style.setProperty('--bg-color', '#222327');
  }
}
body{
   --bg-color: #222327;
    width: 100%;
    height: 100vh;
    min-height: 100vh;
    background-color: var(--bg-color);
}
<div class="box">
  <button onclick="changeBgC()" class="menuButton">≣</button>
</div>

Answer №4

To optimize performance and simplify maintenance, it's recommended to avoid using JavaScript for directly altering element styles when switching themes.

Instead, a more efficient solution is to utilize CSS variables for theme changes, offering benefits such as enhanced performance, ease of maintenance, and increased flexibility.

Here's how you can implement CSS variables to toggle between light and dark themes:

  1. Utilize CSS variables for color adjustments:
.theme-light {
  --bg-primary: #29fd53;
}

.theme-dark {
  --bg-primary: #222327;
}

body {
  background: var(--bg-primary);
}
  1. Switching between different themes:
function switchTheme() {
    let themes = ['theme-light', 'theme-dark'];
    let currentTheme = [...document.body.classList].find(c => themes.includes(c)) ?? themes[0]
    let nextTheme = themes[themes.indexOf(currentTheme)+1] ?? themes[0]
    document.body.classList.remove(...themes) // removes all theme classes, including the current one
    document.body.classList.add(nextTheme)
}
  1. Include the HTML snippet:
<div class="box">
  <button onclick="switchTheme()" class="menuButton">≣</button>
</div>
  1. Ensure to set an initial body class with one of the theme options:
<body class="theme-light">
<body class="theme-dark">

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

Why Form Validation in JavaScript is Failing to Display Alerts or Update Input Background Colors

Having created this script to validate my forms, I encountered an issue where leaving a textfield blank does not trigger the expected behavior. There is no red background or alert message displayed as intended. function validateForm() { /* Loop through al ...

Customize bootstrap cards to have a full height and add a bottom margin to enhance the

My current project involves creating a grid of Bootstrap 4 cards that need to meet specific requirements: All cards must be contained within a single class="row" div. This is because the number of cards is unknown and I want the layout to adjust well acr ...

How can I retrieve the current value of a text element using jQuery?

Having an issue with my text input element where an event is triggered on blur and when the user presses enter. The problem arises when the user inputs "foo" and presses enter; the val() function returns null initially, but after the blur event, it return ...

Are Css3 Transition and Transform properties dysfunctional in older versions of IE?

Snippet of HTML Code: <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="css/demo.css" /> </head> <body> <div></div> </body> </html> CSS Snippet: div { width: 100p ...

The issue arises when attempting to use Bootstrap date and time components simultaneously

I am encountering an issue with the date picker and datetimepicker when used together in my form. If I only work on time or date individually, they function properly. However, when both are included, the time is not working correctly as it displays the dat ...

Tips for customizing the Bootstrap 4 grid system for a seamless mobile viewing experience

My form consists of 3 steps, each row containing multiple inputs. You can see an example of my form here. Below is a sample of the grid system I have used: <div class="row"> <div class="col"> <input asp-for="First_N ...

Creating multiple divs with input fields dynamically using JavaScript is a useful skill to have

I need to generate 3 input text boxes for gathering user input on names and email addresses. These inputs must be created dynamically, meaning that as the user clicks on the email input field, a new line with all three elements should be generated. Below i ...

Tips for adding an asterisk to the label of a Material-UI switch component

I am trying to include an asterisk symbol in the label by passing a required prop with a property, but it doesn't seem to be functioning correctly. <FormControlLabel control={ <Switch onChange={event => ...

Tips for structuring route dependencies in Node.js and Express

Although I have a good grasp of exporting routes to an index.js file, my struggle lies in properly referencing external route dependencies without having to copy them to the top of the file. For instance, if I have the main entry point of the program (ind ...

Increase the size of the parent div as the height of the position:absolute child div grows

I am facing an issue with a parent div and its 2 child divs. <div id="parent"> <div class="child1 col-2"></div> <div class="child2 col-10"></div> </div> The child1 div has absolute positioning a ...

Combining numerous arrays of objects by a specific key

I'm struggling to merge multiple arrays of objects by a key. I've searched online for resources, but I only found information on merging two arrays of objects. My challenge is that I have an array containing multiple arrays of objects. response ...

Error: Unable to access the property '_locals' of an undefined value

I have been experimenting with nodejs on my Ubuntu 16.04 system, where I successfully installed Node and npm. However, I encountered an error stating "TypeError: Cannot read property '_locals' of undefined" while trying the following code: var e ...

An error occurred with the authorization headers when attempting to retrieve the requested JSON

I am attempting to retrieve JSON data from the Bing Search API. Here is what I have implemented: <!DOCTYPE html> <html> <body> <p id="demo"></p> <script language="JavaScript" type="text/javascript" src="jquery-1.12.3.js"& ...

Experience a seamless transition to the next section with just one scroll, allowing for a full

I've been attempting to create a smooth scroll effect to move to the next section using Javascript. However, I'm encountering issues with the window's top distance not being calculated correctly. I'm looking to have the full screen div ...

How can I efficiently update Vue data externally?

const app = createApp({ data() { return { unique_id: 0 } } }) I implemented an autocomplete feature on a specific input field. My goal is to send the chosen id to a Vue application when a label is selected. onSelectItem: ({label, value}) ...

Utilizing clip-path polygons for effective styling on Firefox and iOS

I have been working on a plugin to create animated modal boxes by utilizing the clip-path property. However, I have encountered an issue where this code only seems to work in Chrome. You can view the codepen demo here. Unfortunately, it appears that Firef ...

A comprehensive guide to using Reactive Forms in Angular

I need help understanding how FormGroup, FormControl, FormArray work in Angular. The error message I'm encountering is: Type '{ question: FormControl; multi: true; choices: FormArray; }' is not assignable to type 'AbstractControl' ...

JSON parsing throws an error due to encountering an 'unexpected end of input' issue

Here's some code I'm working with: var default_links = '{ "name" : "Google", "url": "https://encrypted.google.com/", "fav_url": "https://encrypted.google.com/favicon.ico" }\n'+ '{ "name" : "Yahoo", "url": "http://www. ...

Error: The filter argument must be in object form

Currently I am in the process of developing a REST API with an endpoint for posting movies. The request body is expected to contain only the movie title, which needs to be validated for presence. Upon receiving the title, I need to fetch other movie detail ...

`Enhancing the appearance of code in PHP`

I'm struggling with customizing the data pulled from the database. Can anyone provide assistance? I attempted to define $style within the while loop and assign it to $questions, but nothing is displaying on the webpage. While I have some familiarity w ...