Lisa
Lisa

Reputation: 25

Changing Background colour with Javascript and keeping it after refreshing the page

I'm changing the colour of the background when a button is clicked with Javascript.

This is the JS code:

<script>
function myFunction() {
    document.body.style.backgroundColor = "#BB0A21";
}
</script>

It works fine, but the problem is that when the user refreshes the page, the background colour is being reset to the original colour. Is there a way to stop this from happening?

Thanks, Lisa

Upvotes: 1

Views: 1094

Answers (2)

atmd
atmd

Reputation: 7490

you can store the colour change in a local session. You'll need to check if the session already has the value, setting it if not. this will survive page refreshes etc

    function myFunction() {
        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
  myFunction();

Upvotes: 1

user5038678
user5038678

Reputation:

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

Upvotes: 1

Related Questions