cosmo cosmo - 3 months ago 12
HTML Question

How to keep background color changes on page reload?

I have a table which contain cells that when clicked, will change the cell's background color to green. When I reload the page, however, the background color reverts back to its original color; white. Is there any way I can prevent it from reverting? To just keep it green after I clicked it?

JS:

function eight(){
var eight = document.getElementById("eight");
eight.style.backgroundColor = "green";
}


HTML:

<td id="eight" onclick="eight(); ">
<a>8</a>
<br>
<center>-</center>
<br>
<center>-</center>
<hr>
<center>-</center>
<br>
<center>-</center>
</td>


*Ignore the content inside the
<td>
tags.

Answer

You have to store the color value in Client side Cookie or Server Side Session. Modern browsers supports localStorage also..

Try this Code..

function changeBackground() {
        if (sessionStorage.getItem('colour')) {
            document.body.style.backgroundColor = sessionStorage.getItem('colour');
        }else{
            document.body.style.backgroundColor =  "#BB0A21";
            sessionStorage.setItem('colour', "#BB0A21");
        }
    }

  // then you'll need to call your function on page load
  changeBackground();