Click here to Skip to main content
15,888,142 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to create a button that switches between light and dark colors, so basically this works:
JavaScript
document.body.style.backgroundColor = "gray";
if (document.body.style.backgroundColor == "gray") {
    document.body.style.backgroundColor = "red";
} else {
    document.body.style.backgroundColor = "blue";
}

But this doesn't:
JavaScript
document.body.style.backgroundColor = "#2a2a2a";
if (document.body.style.backgroundColor == "#2a2a2a") {
    document.body.style.backgroundColor = "#840000";
} else {
    document.body.style.backgroundColor = "#008400";
}


I don't want to limit myself to the premade colors of HTML, i want to have my own custom color scheme but at this time it does not seem possible.

What I have tried:

I tried using preset colors, and it worked. I don't want to use this way.
Posted
Updated 14-Apr-21 10:12am

1 solution

It is because backgroundColor is an rgb value, not a string. For example add
JavaScript
alert(document.body.style.backgroundColor)

right after you set it and you'll see it is not the string you just set it to. It does work, you just can't test for the background color that way.

If you want to test for the background color's hex value there is some code that looks like it will work, javascript - How to get hex color value rather than RGB value? - Stack Overflow[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900