Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Change background colour with javascript with 2 colours

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading