Add theme switcher
This commit is contained in:
@@ -0,0 +1,45 @@
|
||||
// Toggle theme
|
||||
|
||||
const isOSLight = window.matchMedia("(prefers-color-scheme: light)").matches
|
||||
const localTheme = window.localStorage && window.localStorage.getItem("lightTheme")
|
||||
const themeToggle = document.querySelector(".theme-toggle")
|
||||
|
||||
function changeFavicon() {
|
||||
const src = document.documentElement.classList.contains("dark-theme") ? "/img/favicon-dark.png" : "/img/favicon.png";
|
||||
const link = document.createElement('link'),
|
||||
oldLink = document.getElementById('dynamic-favicon');
|
||||
link.id = 'dynamic-favicon';
|
||||
link.rel = 'shortcut icon';
|
||||
link.href = src;
|
||||
if (oldLink) {
|
||||
document.head.removeChild(oldLink);
|
||||
}
|
||||
document.head.appendChild(link);
|
||||
}
|
||||
|
||||
function changeTheme(useLight) {
|
||||
document.documentElement.classList.remove('light-theme', 'dark-theme', 'has-light-text', 'has-dark-text')
|
||||
if (useLight) {
|
||||
document.documentElement.classList.add('light-theme', 'has-dark-text')
|
||||
} else {
|
||||
document.documentElement.classList.add('dark-theme', 'has-light-text')
|
||||
}
|
||||
|
||||
if (window.localStorage) {
|
||||
window.localStorage.setItem(
|
||||
"lightTheme",
|
||||
useLight)
|
||||
}
|
||||
|
||||
changeFavicon()
|
||||
}
|
||||
|
||||
themeToggle.addEventListener("click", () => {
|
||||
changeTheme(document.documentElement.classList.contains('dark-theme'))
|
||||
});
|
||||
|
||||
if (localTheme instanceof Boolean) {
|
||||
changeTheme(localTheme)
|
||||
} else {
|
||||
changeTheme(isOSLight)
|
||||
}
|
||||
Reference in New Issue
Block a user