I want to make JavaScript check my css code and return me if background color = #222327 it will change background color to #29fd53 But if old background color = #29fd53 it will change background color to #222327
My Js 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 just try to use i++ (I use onclick on my html code) but it only changes the background color to #29fd53. When I press the button again it doesn’t do anything.
Here is what I try
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
}
}
4
Answers
Your problem lies in setting the i variable inside the function scope. So every time you call changeBgC() it will set i = 0.
Declare i outside the function and it should work
This can be achieved using a
class
instead of afunction
. This way thei
variable can be encapsulated. I have used private members (#
) as they are not required ouside of the class.as @Teemu mentioned above
getComputedStyle()
returns anrgb()
valueso to get the HEX code you can use a css variable rather than writing a function to convert from RGB to HEX,
trim function used to remove trailing spaces
You should not use JavaScript to directly change the styles of elements for the purpose of switching themes.
However, a better solution for switching themes is to use CSS variables instead of directly changing the styles of elements with JavaScript.
This approach has several benefits, including better performance, easier maintenance, and more flexibility.
Here’s an example of how you could use CSS variables to switch between light and dark themes: