2023-10-21 17:18:04 -04:00
|
|
|
// Light / Dark theme toggle
|
|
|
|
(function () {
|
|
|
|
const defaultTheme = '{{ site.Params.theme.default | default `system`}}'
|
2023-07-30 21:50:41 +01:00
|
|
|
|
2023-10-21 17:18:04 -04:00
|
|
|
const themeToggleButtons = document.querySelectorAll(".theme-toggle");
|
2023-07-30 21:50:41 +01:00
|
|
|
|
2023-10-21 17:18:04 -04:00
|
|
|
// Change the icons of the buttons based on previous settings or system theme
|
|
|
|
if (
|
|
|
|
localStorage.getItem("color-theme") === "dark" ||
|
|
|
|
(!("color-theme" in localStorage) &&
|
|
|
|
((window.matchMedia("(prefers-color-scheme: dark)").matches && defaultTheme === "system") || defaultTheme === "dark"))
|
|
|
|
) {
|
|
|
|
themeToggleButtons.forEach((el) => el.dataset.theme = "dark");
|
|
|
|
} else {
|
|
|
|
themeToggleButtons.forEach((el) => el.dataset.theme = "light");
|
|
|
|
}
|
2023-07-30 21:50:41 +01:00
|
|
|
|
2023-10-21 17:18:04 -04:00
|
|
|
// Add click event handler to the buttons
|
|
|
|
themeToggleButtons.forEach((el) => {
|
|
|
|
el.addEventListener("click", function () {
|
|
|
|
if (localStorage.getItem("color-theme")) {
|
|
|
|
if (localStorage.getItem("color-theme") === "light") {
|
|
|
|
setDarkTheme();
|
|
|
|
localStorage.setItem("color-theme", "dark");
|
|
|
|
} else {
|
|
|
|
setLightTheme();
|
|
|
|
localStorage.setItem("color-theme", "light");
|
|
|
|
}
|
2023-08-07 23:48:07 +01:00
|
|
|
} else {
|
2023-10-21 17:18:04 -04:00
|
|
|
if (document.documentElement.classList.contains("dark")) {
|
|
|
|
setLightTheme();
|
|
|
|
localStorage.setItem("color-theme", "light");
|
|
|
|
} else {
|
|
|
|
setDarkTheme();
|
|
|
|
localStorage.setItem("color-theme", "dark");
|
|
|
|
}
|
2023-08-07 23:48:07 +01:00
|
|
|
}
|
2023-10-21 17:18:04 -04:00
|
|
|
el.dataset.theme = document.documentElement.classList.contains("dark") ? "dark" : "light";
|
|
|
|
});
|
|
|
|
});
|
|
|
|
|
|
|
|
// Listen for system theme changes
|
|
|
|
window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change", (e) => {
|
|
|
|
if (defaultTheme === "system" && !("color-theme" in localStorage)) {
|
|
|
|
e.matches ? setDarkTheme() : setLightTheme();
|
|
|
|
themeToggleButtons.forEach((el) =>
|
|
|
|
el.dataset.theme = document.documentElement.classList.contains("dark") ? "dark" : "light"
|
|
|
|
);
|
2023-07-30 21:50:41 +01:00
|
|
|
}
|
2023-08-07 23:48:07 +01:00
|
|
|
});
|
2023-10-21 17:18:04 -04:00
|
|
|
})();
|