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

28 lines
772 B
JavaScript

2022-07-06 15:45:22 +07:00
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();