summaryrefslogtreecommitdiffstats
path: root/toggle-theme.js
blob: 7ab7ddc661b52a883aeaf7e3f33b80d9282c0ff7 (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
  {
    const flip = document.getElementById("flip");
    const root = document.documentElement;
    const osDark = matchMedia("(prefers-color-scheme: dark)");
    const current = () => root.style.colorScheme || (osDark.matches ? "dark" : "light");
    const label = (scheme) => (flip.textContent = scheme === "dark" ? "Light" : "Dark");
    // match the tab icon to the theme
    const favicon = (scheme) => {
      const icon = document.getElementById("favicon");
      icon.href = icon.href.replace(/favicon-(light|dark)/, "favicon-" + scheme);
    };
    const show = () => {
      label(current());
      favicon(current());
    };

    flip.onclick = () => {
      const next = current() === "dark" ? "light" : "dark";
      root.style.colorScheme = next;
      localStorage.setItem("theme", next);
      show();
    };

    osDark.addEventListener("change", show);
    show();
  }