Created
November 18, 2021 13:10
-
-
Save sjns19/be87ad7b1a6234f52583069d0c3dcd7b to your computer and use it in GitHub Desktop.
This gist is used for a medium article
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Get the button that is used to toggle the dark mode | |
const themeBtn = document.getElementById("dark-mode-btn"); | |
// Get the <html> element | |
const docEl = document.documentElement; | |
// Handling the click event | |
themeBtn.addEventListener("click", () => { | |
// Toggle the dark-theme class inside of the html element | |
docEl.classList.toggle("dark-theme"); | |
// Set the dark theme value in user's browser. | |
// This time, we are going to have a boolean value | |
// stored so that we can add the dark-theme class to the body | |
// element by checking the value of this boolean | |
localStorage.setItem("dark-theme-toggled", docEl.classList.contains("dark-theme")); // This returns true/false | |
}); | |
// Load the storage item and check for its value | |
window.addEventListener("DOMContentLoaded", () => { | |
let theme = localStorage.getItem("dark-theme-toggled"); | |
// If the local storage value is not null (means there is something stored) | |
// and if it's true (apparently it's stored as string so comparing to real boolean won't help) | |
// toggle the dark-theme again | |
if (theme !== null && theme === "true") { | |
docEl.classList.toggle("dark-theme"); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment