Skip to content

Instantly share code, notes, and snippets.

@praveen001
Created March 28, 2020 21:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save praveen001/dfd5a6c79d90cec8e0dcc7ca4a07bfde to your computer and use it in GitHub Desktop.
Save praveen001/dfd5a6c79d90cec8e0dcc7ca4a07bfde to your computer and use it in GitHub Desktop.
Multiple themes using css variables
<!DOCTYPE html>
<html>
<style>
.default {
--primary-color: #f00;
--secondary-color: #000;
--background-default: #efefef;
--background-paper: #fff;
}
.dark {
--primary-color: #0f0;
--secondary-color: #fff;
--background-default: #444;
--background-paper: #111;
}
body {
background: var(--background-default);
}
.primary-div {
background: var(--primary-color);
width: 250px;
height: 250px;
}
.secondary-div {
background: var(--secondary-color);
width: 250px;
height: 250px;
}
</style>
<script>
window.onload = function() {
// Try to read from local storage, otherwise set to default
let currentTheme = localStorage.getItem("mytheme") || "default";
setTheme("default", currentTheme);
const themeSelector = document.getElementById("theme-selector");
themeSelector.value = currentTheme;
themeSelector.addEventListener("change", function(e) {
const newTheme = e.currentTarget.value;
setTheme(currentTheme, newTheme);
});
function setTheme(oldTheme, newTheme) {
const body = document.getElementsByTagName("body")[0];
body.classList.remove(oldTheme);
body.classList.add(newTheme);
currentTheme = newTheme;
// Store the new theme in local storage
localStorage.setItem("mytheme", newTheme);
}
};
</script>
<body class="default">
<div>
Choose your theme
<select id="theme-selector">
<option value="default">Default</option>
<option value="dark">Dark mode</option>
</select>
</div>
<div class="primary-div">Primary Color</div>
<div class="secondary-div">Secondary Color</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment