0

I have a drop-down selector that lets you chose the theme of the site with options "white" and "black".

<select name="Invert" onchange="changeColor(this)">
   <option value="white">White</option>
   <option value="black">Black</option>
</select>

Then i have the folowing js function changeColor()

function changeColor(x) {
  var body = document.getElementById('body');

  if (x.value == 'black') {
    body.style.backgroundColor = x.value;
    body.style.color = 'white';
  } else if (x.value == 'white') {
    body.style.backgroundColor = x.value;
    body.style.color = 'black';
  }
}

I have the same selector and js function set for other pages in separate js files for each page.

When i select a theme option and then refresh or go to another page the theme color goes back to the default white.

The question is, how do i keep the changed theme for other pages, also after refreshing the website?

  • 1
    Possible duplicate of [Persist variables between page loads](https://stackoverflow.com/questions/29986657/persist-variables-between-page-loads) –  Aug 01 '18 at 08:45

2 Answers2

3

Save the selection in localStorage, and on page load, set the style to the value in localStorage, if there is any.

For example:

var body = document.getElementById('body');
if (localStorage.color) body.style.backgroundColor = localStorage.color;
function changeColor(x) {
  if (x.value == 'black') {
    body.style.backgroundColor = x.value;
    body.style.color = 'white';
    localStorage.color = 'white';
  } else if (x.value == 'white') {
    body.style.backgroundColor = x.value;
    body.style.color = 'black';
    localStorage.color = 'white';
  }
}
לבני מלכה
  • 15,925
  • 2
  • 23
  • 47
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

You could set it with cookies. Using this :

<script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script>

And then just:

Cookies.set('color', dark);
Cookies.get('color'); // if you console log it it will say "dark"
Cookies.set('color', white);
Cookies.get('color'); // if you console log it it will say "white"

EDIT:

Final code should look something like:

HTML:

<select id="Invert" onchange="changeColor()">
    <option value="white">White</option>
    <option value="black">Black</option>
</select>

JavaScript:

document.body.style.backgroundColor = Cookies.get('color');

function changeColor() {
    var select = document.getElementById("Invert");
    var option = select.options[select.selectedIndex].value;
    document.body.style.backgroundColor = option;
    Cookies.set('color', option);
}

NOTE

Cookies will not work if you're not using a domain like localhost!

This should work just fine, but you should improve upon it :)

Duma
  • 124
  • 2
  • 12