I’m trying to have a button on my webiste that if you press it the background color will change to blue which i have, but i’m trying to code that if you press it again it’ll change to white again.
function myFunction() {
document.body.style.backgroundColor= "lightblue";
}
function my1Function() {
document.body.style.backgroundColor= "lightgrey";
}
function my2Function() {
document.body.style.backgroundColor= "pink";
}
function my3Function() {
document.body.style.backgroundColor= "lightgreen";
}
<header>
<h1></h1>
</header>
<br>
<form action="#">
<label for="fname">Uw naam:</label>
<input type="text" id="fname" name="fname">
<input type="submit" value="Submit">
</form>
<button type="button" onclick="myFunction()">Lightblue</button>
<button type="button" onclick="my1Function()">Lightgrey</button>
<button type="button" onclick="my2Function()">Pink</button>
<button type="button" onclick="my3Function()">Lightgreen</button>
I tried using alternatives such as case1, case2, case3 etc.
>Solution :
If you are not saving the state of color on refresh or rerendering then this could be one of the solutions.
var blue = 0;
function myFunction() {
if(blue == 0){
document.body.style.backgroundColor= "lightblue";
blue = 1;
}
else{
document.body.style.backgroundColor= "white";
blue = 0;
}
}
function my1Function() {
document.body.style.backgroundColor= "lightgrey";
}
function my2Function() {
document.body.style.backgroundColor= "pink";
}
function my3Function() {
document.body.style.backgroundColor= "lightgreen";
}
<header>
<h1></h1>
</header>
<br>
<form action="#">
<label for="fname">Uw naam:</label>
<input type="text" id="fname" name="fname">
<input type="submit" value="Submit">
</form>
<button type="button" onclick="myFunction()">Lightblue</button>
<button type="button" onclick="my1Function()">Lightgrey</button>
<button type="button" onclick="my2Function()">Pink</button>
<button type="button" onclick="my3Function()">Lightgreen</button>