diff options
| author | Arne Rief <riearn@proton.me> | 2026-06-22 20:10:19 +0200 |
|---|---|---|
| committer | Arne Rief <riearn@proton.me> | 2026-06-22 20:10:19 +0200 |
| commit | 5e870d78000ca23e38f1b7c1fab700fd4fb67979 (patch) | |
| tree | 79447f3e655c78a0f102da394af1be533900162c /assets/js/theme.js | |
| parent | 4c82042f990ffd6c48e547cefb861a1f516b7b4f (diff) | |
Diffstat (limited to 'assets/js/theme.js')
| -rw-r--r-- | assets/js/theme.js | 41 |
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", () => { |
