Home

Save the theme to localStorage

Save the preference to localStorage so users retain their theme choice across page loads.
localStorage.setItem("theme", osTheme);
We can similarly fetch the currently value with getItem().
localStorage.getItem("theme")
We make use of this in two functions below to set and toggle the theme. In doing so we also Load the themed syntax highlighter.
let stylesheet = document.getElementById("prism");
let toggleBtn = document.getElementById("toggle-btn");

function setTheme(isDark) {
  if (isDark) {
    localStorage.setItem("theme", "dark");
    document.body.classList.add("dark");
    toggleBtn.innerHTML = "☀️";
    toggleBtn.setAttribute("aria-label", "enable light theme");
    stylesheet.setAttribute("href", "/prism-tomorrow.css");
  } else {
    localStorage.setItem("theme", "light");
    document.body.classList.remove("dark");
    toggleBtn.innerHTML = "🌙";
    toggleBtn.setAttribute("aria-label", "enable dark theme");
    stylesheet.setAttribute("href", "/prism-coy.css");
  }
}

function toggleTheme() {
  if (localStorage.getItem("theme") === "dark") {
    setTheme(false);
  } else {
    setTheme(true);
  }
}

toggleBtn.addEventListener("click", (e) => {
  e.preventDefault();
  toggleTheme();
});
setTheme(localStorage.getItem("theme") === "dark");