Option to change the CSS theme

Topics related to client-side programming language.
Post questions and answers about JavaScript, Ajax, or jQuery codes and scripts.
Marius
Posts: 107

Option to change the CSS theme

Hi,
Does anyone know how to add option in web page to change the css theme?
For example, i have two css files: "light.css", and "dark.css". I want to add option so the users to can change and use one of these themes, but when the user visits the site again, to see the theme he /she has chosen.

Admin Posts: 805
Welcome
It can be made with html and javascript:
- Add an id to the html <link> tag which loads the css file.
- Create a <select> with options for various themes / css files.
- Make a javascript script that takes the value of the chosen option from <select> and changes the one in the <link> tag, then adds / saves that value in the user's browser (in localStorage).
- When the page loads, check if there is a localStorage with a css theme, if exists, add it in the <link> tag.
Here's an example:

Code: Select all

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Title</title>
<link href="css/light.css" rel="stylesheet" type="text/css" id="css_id" />
</head>
<body>

<select id="change_css">
  <option value="css/light.css">Light</option>
  <option value="css/dark.css">Dark</option>
</select>
 
<script>
// if the css option is saved in browser, use it
if(localStorage.getItem('css_teme')) {
  document.getElementById('css_id').href = localStorage.getItem('css_teme');

  // change the selected option in select
  var sel_op = document.getElementById('change_css').querySelectorAll('option');
  for(var i=0; i<sel_op.length; i++) {
    if(sel_op[i].value == localStorage.getItem('css_teme')) {
      sel_op[i].setAttribute('selected', 'selected');
      break;
    }
  }
}

// when the select option is changed
document.getElementById('change_css').addEventListener('change', function(e) {
  // change the used css file
  document.getElementById('css_id').href = this.value;

  // stores the value in browser's localstorage
  localStorage.setItem('css_teme', this.value);
});
</script>

</body>
</html>

Similar Topics