hugo-theme-hello-friend/assets/js/theme.js

32 lines
949 B
JavaScript
Raw Normal View History

2018-07-20 19:14:22 +02:00
// Toggle theme
const localTheme = window.localStorage && window.localStorage.getItem("theme");
2018-12-21 19:07:37 +01:00
const themeToggle = document.querySelector(".theme-toggle");
2018-07-20 19:14:22 +02:00
if (localTheme) {
document.body.classList.remove("light-theme", "dark-theme");
document.body.classList.add(localTheme);
2018-12-21 19:07:37 +01:00
}
2018-07-20 19:14:22 +02:00
2018-12-21 19:07:37 +01:00
themeToggle.addEventListener("click", () => {
const themeUndefined = !new RegExp("(dark|light)-theme").test(document.body.className);
const isOSDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
if (themeUndefined) {
if (isOSDark) {
document.body.classList.add("light-theme");
} else {
document.body.classList.add("dark-theme");
}
} else {
document.body.classList.toggle("light-theme");
document.body.classList.toggle("dark-theme");
}
window.localStorage &&
window.localStorage.setItem(
2018-12-21 19:07:37 +01:00
"theme",
document.body.classList.contains("dark-theme") ? "dark-theme" : "light-theme",
2018-12-21 19:07:37 +01:00
);
});