summaryrefslogtreecommitdiff
path: root/assets/js/theme.js
diff options
context:
space:
mode:
Diffstat (limited to 'assets/js/theme.js')
-rw-r--r--assets/js/theme.js41
1 files changed, 28 insertions, 13 deletions
diff --git a/assets/js/theme.js b/assets/js/theme.js
index f22afe5..d660e3b 100644
--- a/assets/js/theme.js
+++ b/assets/js/theme.js
@@ -3,24 +3,39 @@ function initThemeToggle() {
const rootHtml = document.documentElement;
const toggleThemeBtn = document.getElementById("theme-toggle");
- // If no saved theme, determine user preference, otherwise default to light
- const savedTheme = localStorage.getItem("theme");
- const prefersDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
- const initialTheme = savedTheme ?? (prefersDark ? "dark" : "light");
+ // The dataset of toggleThemeBtn comes with translated label & title texts for site's language
+ function getThemeTexts(theme) {
+ const isDarkMode = theme === "dark";
+
+ return {
+ label: isDarkMode
+ ? toggleThemeBtn.dataset.labelLight
+ : toggleThemeBtn.dataset.labelDark,
+ title: isDarkMode
+ ? toggleThemeBtn.dataset.titleLight
+ : toggleThemeBtn.dataset.titleDark,
+ };
+ }
+
+ // Apply correct aria-label and title to the theme toggle button
+ function setLabelAndTitle(labelText, titleText) {
+ toggleThemeBtn.setAttribute("aria-label", labelText);
+ toggleThemeBtn.setAttribute("title", titleText);
+ }
+ // Apply different theme description to button & root, the display is handled by CSS
function setTheme(theme) {
- const isDarkMode = theme === "dark";
- // toggleThemeBtn dataset comes with translated labels & title for site's language
- const label = isDarkMode ? toggleThemeBtn.dataset.labelLight : toggleThemeBtn.dataset.labelDark;
- const title = isDarkMode ? toggleThemeBtn.dataset.titleLight : toggleThemeBtn.dataset.titleDark;
+ const { label: newLabel, title: newTitle } = getThemeTexts(theme);
- rootHtml.setAttribute("data-theme", theme); // display handled by CSS
- toggleThemeBtn.setAttribute("aria-label", label);
- toggleThemeBtn.setAttribute("title", title);
+ setLabelAndTitle(newLabel, newTitle);
+ rootHtml.setAttribute("data-theme", theme);
}
- // Apply initial theme
- setTheme(initialTheme);
+ // Initial data-theme attribute is set by inline script in <head> on first page load
+ const initialTheme = rootHtml.getAttribute("data-theme") ?? "light";
+ const { label: initialLabel, title: initialTitle } = getThemeTexts(initialTheme);
+
+ setLabelAndTitle(initialLabel, initialTitle);
// Change theme on click and save user's choice
toggleThemeBtn.addEventListener("click", () => {