blog/themes/hello-friend-ng/assets/js/main.js

28 lines
772 B
JavaScript

const themeToggle = document.querySelector(".theme-toggle");
function getTheme() {
const theme = window.localStorage && window.localStorage.getItem("theme");
return [theme === "dark", theme === "light"];
}
function detectOSColorTheme() {
const [dark, light] = getTheme();
let attribute;
if (dark) attribute = "dark"
else if (light) attribute = "light"
else if (window.matchMedia("(prefers-color-scheme: dark)").matches) attribute = "dark"
else attribute = "light"
document.documentElement.setAttribute("data-theme", attribute);
}
function switchTheme(e) {
const [dark] = getTheme();
localStorage.setItem("theme", dark ? "light": "dark")
detectOSColorTheme();
}
themeToggle.addEventListener("click", switchTheme, false);
detectOSColorTheme();