Last active
January 5, 2022 10:47
-
-
Save sjns19/252d583cbba9683e6add8497b9b20966 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 <link> element | |
const stylesheet = document.getElementById("main-style"); | |
// Get the button that is used to toggle the dark mode | |
const themeBtn = document.getElementById("dark-mode-btn"); | |
// Just an object literal that holds the file paths | |
const cssPath = { | |
light: "src/style.css", | |
dark: "src/style.dark.css", | |
}; | |
// Handling the click event | |
themeBtn.addEventListener("click", () => { | |
// Get the current (default) path of the file from the data attribute | |
let currentPath = stylesheet.getAttribute("data-src"); | |
// If the current path is set to the light one (from the object above) | |
if (currentPath == cssPath.light) { | |
// Replace the path with style.dark.css one | |
stylesheet.href = cssPath.dark; | |
// Also set the path to the data attribute to indicate this is | |
// the current path | |
stylesheet.setAttribute("data-src", cssPath.dark); | |
// Store this style path to user's browser so that we can load this style when the users reload their browser | |
localStorage.setItem("theme", cssPath.dark); | |
} else if (currentPath == cssPath.dark) { | |
// If the path is dark then do the opposite again | |
stylesheet.href = cssPath.light; | |
stylesheet.setAttribute("data-src", cssPath.light); | |
// Store this style path to user's browser | |
localStorage.setItem("theme", cssPath.light); | |
} | |
}); | |
// Load the user-preferred theme | |
window.addEventListener("DOMContentLoaded", () => { | |
let theme = localStorage.getItem("theme"); | |
stylesheet.href = theme; | |
stylesheet.setAttribute("data-src", theme); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment