Repository navigation
Expand file tree
/
Copy pathsite.js
More file actions
45 lines (42 loc) · 1.85 KB
/
Copy pathsite.js
File metadata and controls
45 lines (42 loc) · 1.85 KB
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
// Shared by every page of codelightjs.github.io: theme switch, mobile menu, current page in the nav.
{
const root = document.documentElement;
const header = document.querySelector(".site-header");
/* Theme: auto (follows the system) → light → dark. Remembered in this browser only. */
const modes = ["auto", "light", "dark"];
const labels = { auto: "Theme: follows your system", light: "Theme: light", dark: "Theme: dark" };
let mode = "auto";
try { mode = localStorage.getItem("cl-theme") || "auto"; } catch {}
const themeBtn = document.getElementById("theme");
const applyTheme = () => {
if (mode === "auto") root.removeAttribute("data-theme");
else root.setAttribute("data-theme", mode);
if (themeBtn) {
themeBtn.setAttribute("aria-label", labels[mode] + ". Click to change.");
themeBtn.title = labels[mode];
themeBtn.dataset.mode = mode;
}
};
if (themeBtn) themeBtn.addEventListener("click", () => {
mode = modes[(modes.indexOf(mode) + 1) % modes.length];
try { localStorage.setItem("cl-theme", mode); } catch {}
applyTheme();
});
applyTheme();
/* Mobile menu */
const menuBtn = document.getElementById("menu");
if (menuBtn && header) {
const setOpen = (open) => {
header.classList.toggle("open", open);
menuBtn.setAttribute("aria-expanded", String(open));
};
menuBtn.addEventListener("click", () => setOpen(!header.classList.contains("open")));
header.querySelectorAll(".site-nav a").forEach((a) => a.addEventListener("click", () => setOpen(false)));
document.addEventListener("keydown", (e) => { if (e.key === "Escape") setOpen(false); });
}
/* The current page in the nav */
const page = document.body.dataset.page;
document.querySelectorAll(".site-nav a[data-page]").forEach((a) => {
if (a.dataset.page === page) a.setAttribute("aria-current", "page");
});
}