Home
🌝

Dark themes made easy

The 🌙/☀️ button at the top of this screen toggles the dark/light theme
First we Detect the user's preference. Then we leverage CSS variables for theming. We allow users to toggle the theme, and Save the theme to localStorage. Finally, we make sure to Load the themed syntax highlighter.
The code in its entirety can be found below.

🔗 script.js

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);
  }
}

if (!localStorage.getItem("theme")) {
  const osTheme = window.matchMedia("(prefers-color-scheme: dark)").matches
    ? "dark"
    : "light";
  localStorage.setItem("theme", osTheme);
}

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

🔗 style.css

:root {
  --font-color: black;
  --background-color: white;
  --footer-label-color: #444444;
  --dimmer: #e6e6e6;
  --dimmest: #f6f6f6;
  --link-color: #787672;
  --image-width: 360px;
}

body.dark {
  --font-color: rgba(255, 255, 255, 0.9);
  --background-color: #2f3437;
  --footer-label-color: #eee;
  --dimmer: #64686a;
  --dimmest: #464b4f;
  --link-color: #b2b4b5;
}