-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtoggle-theme.js
More file actions
1 lines (1 loc) · 1.14 KB
/
toggle-theme.js
File metadata and controls
1 lines (1 loc) · 1.14 KB
1
const primaryColorScheme="",darkColor="rgb(38, 38, 38)",lightColor="rgb(251, 254, 251)",currentTheme=localStorage.getItem("theme");function getPreferTheme(){return currentTheme||primaryColorScheme||(window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light")}let themeValue=getPreferTheme();function setPreference(){localStorage.setItem("theme",themeValue),reflectPreference()}function reflectPreference(){document.firstElementChild.setAttribute("data-theme",themeValue);const e=document.querySelector("#theme-button");e&&(e.dataset.darkMode=themeValue==="dark"?"true":"false",e.querySelector("input").checked=themeValue==="dark"),document.querySelector("meta[name='theme-color']")?.setAttribute("content",themeValue==="dark"?darkColor:lightColor)}reflectPreference(),window.onload=()=>{function e(){reflectPreference(),document.querySelector("#theme-button input")?.addEventListener("change",()=>{themeValue=themeValue==="light"?"dark":"light",setPreference()})}e(),document.addEventListener("astro:after-swap",e)},window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",({matches:e})=>{themeValue=e?"dark":"light",setPreference()});