0

I want to maintain the selected color after the page is refreshed or closed and opened again. I've added three buttons to my page for changing background color.

<div id="color">
        <button id="blue" onclick="colorBlue()"></button>
        <button id="red" onclick="colorRed()"></button>
        <button id="green" onclick="colorGreen()"></button>
</div>

And functions in script file.

function colorBlue() {
    document.body.style.backgroundColor = '#002E5C';
}
function colorRed() {
    document.body.style.backgroundColor = '#BA1616';
}
function colorGreen() {
    document.body.style.backgroundColor = '#118E1B';
}

This is for a school project and it should be done using cookies. I tried to do it myself, but with no success. Thanks in advance!

Predrag
  • 3
  • 3
  • Possible duplicate of [How do I create and read a value from cookie?](https://stackoverflow.com/questions/4825683/how-do-i-create-and-read-a-value-from-cookie) – mhodges Jun 11 '18 at 16:37

1 Answers1

0

You could use localStorage for this. More info at MDN

Set storage item with function:

localStorage.setItem('bgcolor', 'blue'); 

and then check when the page or whatever loads.

localStorage.getItem('bgcolor');
Mario
  • 870
  • 9
  • 20
  • Sorry, i forgot to mention that i need to use cookies. It's for a school project and one of requirements is the usage of cookies. I'll edit that right away. – Predrag Jun 11 '18 at 16:41
  • you can do exactly the same with sessionStorage or Cooikies. All information is on MDN https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie – Mario Jun 11 '18 at 16:43