blob: d660e3ba5cca00da452760bd8d264a70fd126cb2 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
|
/* Toggle Dark/Light Mode */
function initThemeToggle() {
const rootHtml = document.documentElement;
const toggleThemeBtn = document.getElementById("theme-toggle");
// 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 { label: newLabel, title: newTitle } = getThemeTexts(theme);
setLabelAndTitle(newLabel, newTitle);
rootHtml.setAttribute("data-theme", theme);
}
// 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", () => {
const newTheme = rootHtml.getAttribute("data-theme") === "dark" ? "light" : "dark";
setTheme(newTheme);
localStorage.setItem("theme", newTheme);
});
}
export default initThemeToggle;
|