Created
July 8, 2023 07:05
-
-
Save codepedia-top/10aafbeb15dd2c725cabf5ab4cbfd03d to your computer and use it in GitHub Desktop.
Theme Toggler with javascript and css simple code
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 darkModeToggle = document.getElementById("darkModeToggle"); | |
| // Listen for a click event on the toggle button | |
| darkModeToggle.addEventListener("click", function () { | |
| // Toggle the dark mode class on the body element | |
| document.body.classList.toggle("dark-mode"); | |
| // Store the user's preference in localStorage | |
| if (document.body.classList.contains("dark-mode")) { | |
| localStorage.setItem("darkMode", "enabled"); | |
| darkModeToggle.innerText = "Light Mode"; | |
| } else { | |
| localStorage.setItem("darkMode", "disabled"); | |
| darkModeToggle.innerText = "Dark Mode"; | |
| } | |
| }); | |
| // Check if dark mode preference is saved in localStorage | |
| if (localStorage.getItem("darkMode") === "enabled") { | |
| document.body.classList.add("dark-mode"); | |
| } else { | |
| document.body.classList.remove("dark-mode"); | |
| } |
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
| /* Light mode styles */ | |
| body { | |
| background-color: #ffffff; | |
| color: #000000; | |
| font-family: sans-serif; | |
| } | |
| .head { | |
| display: flex; | |
| align-items: center; | |
| justify-content: center; | |
| flex-direction: column; | |
| } | |
| h1 { | |
| font-size: 3rem; | |
| } | |
| /* Dark mode styles */ | |
| body.dark-mode { | |
| background-color: #1f1f1f; | |
| color: #ffffff; | |
| } | |
| button { | |
| border: none; | |
| padding: 1rem; | |
| font-size: 1.4rem; | |
| } | |
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
| <!DOCTYPE html> | |
| <html> | |
| <head> | |
| <link rel="stylesheet" type="text/css" href="styles.css" /> | |
| </head> | |
| <body> | |
| <header class="head"> | |
| <h1>Theme Toggler</h1> | |
| <button id="darkModeToggle"></button> | |
| </header> | |
| <main> | |
| <!-- Main content goes here --> | |
| </main> | |
| <footer> | |
| <!-- Footer content goes here --> | |
| </footer> | |
| <script src="script.js"></script> | |
| </body> | |
| </html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment