Skip to content

Instantly share code, notes, and snippets.

@2thecrow
Last active February 28, 2023 20:56
Show Gist options
  • Save 2thecrow/c7b08741e3176392ae802a1e83d3e5a4 to your computer and use it in GitHub Desktop.
Save 2thecrow/c7b08741e3176392ae802a1e83d3e5a4 to your computer and use it in GitHub Desktop.
Simply theme switcher
// Get the theme toggle input
const currentTheme = localStorage.getItem("theme");// If the current local storage item can be found
// Function that will switch the theme based on the if the theme toggle is checked or not
function switchTheme() {
if (document.documentElement.getAttribute("data-theme") === "dark") {
document.documentElement.setAttribute("data-theme", "light");
// Set the user's theme preference to dark
localStorage.setItem("theme", "light");
} else {
document.documentElement.setAttribute("data-theme", "dark");
// Set the user's theme preference to light
localStorage.setItem("theme", "dark");
}
}
// Get the current theme from local storage
if (currentTheme) {
// Set the body data-theme attribute to match the local storage item
document.documentElement.setAttribute("data-theme", currentTheme);// If the current theme is dark, check the theme toggle
if (currentTheme === "dark") {
themeToggle.click();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment