Omnitored Omnitored - 1 month ago 9
HTML Question

<select> option stay same after changing pages

I added a theme select menu to my website, and I want to make the theme selection stay the same after you change the pages, as I added the selection menu to every page but it keeps resetting when changing pages, anyone could tell me how to do this? My code:

<select onchange="javascript:changeColor(this);">
<option selected disabled hidden>Theme</option>
<optgroup label="Themes"></optgroup>
<option value="white">Light</option>
<option value="#222222">Dark</option>
<option value="red">Red</option>
</select>

<script>
function changeColor(el) {
var theme = el.value;
document.body.style.background = theme;
}
</script>

Answer

You could store your desired color inside localStorage:

Playground: http://jsbin.com/cisicay/2/edit?html,css,js,console,output

// On page load let's see if we stored any theme color
var theme = window.localStorage.theme;

// This function can be both triggered as Standalone 
// or on Select onchange event:

function changeColor(el) {
  // If it was triggered by our Select element store the new theme color
  if(el) theme = window.localStorage.theme = el.value;
  // Set the color
  if(theme) document.body.style.background = theme;
}

// Trigger theme change on page load
changeColor();
<select onchange="changeColor(this);">
  <option selected disabled hidden>Theme</option>
  <optgroup label="Themes">
    <option value="#eee">Light</option>
    <option value="#222">Dark</option>
    <option value="red">Red</option>
  </optgroup>
</select>