Last active
January 21, 2020 22:14
-
-
Save alexcmgit/a10074ceb1fb94257e99b3ae19e41e23 to your computer and use it in GitHub Desktop.
script that implements a window api to control the user's choice of theme with localstorage support and without the flash bug
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
//window.__theme: variable with the current theme: "dark" or "light" | |
//window.__setPreferredTheme: function that receives the new theme to be applied | |
//window.__onThemeChange: function that will be called every time the theme changes | |
(function() { | |
window.__onThemeChange = function() {}; | |
function setTheme(newTheme) { | |
window.__theme = newTheme; | |
preferredTheme = newTheme; | |
document.body.className = newTheme; | |
window.__onThemeChange(newTheme); | |
} | |
var preferredTheme; | |
try { | |
preferredTheme = localStorage.getItem("theme"); | |
} catch (err) {} | |
window.__setPreferredTheme = function(newTheme) { | |
setTheme(newTheme); | |
try { | |
localStorage.setItem("theme", newTheme); | |
} catch (err) {} | |
}; | |
setTheme(preferredTheme || "dark"); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment