Created
November 19, 2021 04:21
-
-
Save CoderJay06/b850fe71377933fa0bd49b954e4ffeee to your computer and use it in GitHub Desktop.
dark mode toggle
This file contains hidden or 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
<div id="theme"> | |
<button id="toggle-btn" class="dark-mode-toggle">Toggle dark mode</button> | |
<h1>Theme!</h1> | |
<p> | |
Lorem ipsum dolor sit amet consectetur adipisicing elit. Maxime | |
mollitia, molestiae quas vel sint commodi repudiandae consequuntur | |
voluptatum laborum numquam blanditiis harum quisquam eius sed odit | |
fugiat iusto fuga praesentium optio, eaque rerum! Provident similique | |
accusantium nemo autem. Veritatis obcaecati tenetur iure eius earum ut | |
molestias architecto voluptate aliquam nihil, eveniet aliquid culpa | |
officia aut! Impedit sit sunt quaerat, odit, tenetur error, harum | |
nesciunt ipsum debitis quas aliquid. Reprehenderit, quia. | |
</p> | |
</div> |
This file contains hidden or 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
const toggleBtn = document.getElementById("toggle-btn"); | |
const theme = document.getElementById("theme"); | |
let darkMode = localStorage.getItem("dark-mode"); | |
const enableDarkMode = () => { | |
theme.classList.add("dark-mode-theme"); | |
toggleBtn.classList.remove("dark-mode-toggle"); | |
localStorage.setItem("dark-mode", "enabled"); | |
}; | |
const disableDarkMode = () => { | |
theme.classList.remove("dark-mode-theme"); | |
toggleBtn.classList.add("dark-mode-toggle"); | |
localStorage.setItem("dark-mode", "disabled"); | |
}; | |
if (darkMode === "enabled") { | |
enableDarkMode(); // set state of darkMode on page load | |
} | |
toggleBtn.addEventListener("click", (e) => { | |
darkMode = localStorage.getItem("dark-mode"); // update darkMode when clicked | |
if (darkMode === "disabled") { | |
enableDarkMode(); | |
} else { | |
disableDarkMode(); | |
} | |
}); |
This file contains hidden or 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
body { | |
font-family: sans-serif; | |
margin: 0; | |
} | |
#toggle-btn { | |
padding: 0.5em; | |
font-weight: 800; | |
} | |
#toggle-btn:hover { | |
cursor: pointer; | |
opacity: 0.8; | |
} | |
.dark-mode-toggle { | |
background: #000; | |
color: #fff; | |
} | |
#theme { | |
width: 100vw; | |
height: 100vh; | |
} | |
.dark-mode-theme { | |
background: #000; | |
color: #fff; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment