Skip to content

Instantly share code, notes, and snippets.

@hokie-sam
Created November 1, 2020 06:56
Show Gist options
  • Save hokie-sam/51edf2e6ffdcd889ae2595b2e484de48 to your computer and use it in GitHub Desktop.
Save hokie-sam/51edf2e6ffdcd889ae2595b2e484de48 to your computer and use it in GitHub Desktop.
Simple javascript and css to allow user to chose between a light/dark theme on webpage, and save their choice with HTML5 localStorage, instead of using cookies.
<!DOCTYPE html>
<html>
<style>
/* By making the light/dark buttons 30px squares,
they will not need text labels,
but they'll still be large enough to easily click. */
.light-dark-button {
border-style: solid;
border-color: blue;
height: 30px;
width: 30px;
}
.dark-mode {
background-color: black;
color: white;
}
</style>
<body>
<script>
// Turn ON .dark-mode CSS style, and save choice in localStorage
function darkBackground() {
document.body.classList.add("dark-mode");
localStorage.setItem("backgroundColor", "dark"); }
// Turn OFF .dark-mode CSS style, and save choice in localStorage
function lightBackground() {
document.body.classList.remove("dark-mode");
localStorage.setItem("backgroundColor", "light"); }
// When the page loads, recall and set saved theme, if any
const savedTheme = localStorage.getItem("backgroundColor");
if (savedTheme == "dark") { document.body.classList.add("dark-mode"); }
document.write("When the page loaded, the saved theme was " + savedTheme + "<br>");
</script>
<!-- 1 black and 1 white button, both with the .light-dark-button class. -->
<button type="button" class="light-dark" style="background-color:black;" onclick="darkBackground()"></button>
<button type="button" class="light-dark" style="background-color:white;" onclick="lightBackground()"></button>
</body>
</html>
@hokie-sam
Copy link
Author

Loading the page after previously selecting the dark theme

darktheme

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment