AI Hints
Home›JavaScript Tutorial›Practice Projects 4
JavaScript · Lesson 125 of 138

Practice: Dark Mode

A remembered setting.

⏱ 2 min read▶ Video at 2:30:03🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

Many people prefer dark mode. Let's add a toggle that switches the page's colours, and remembers the choice in local storage, so the page opens in the same mode next time.

Practice: Dark Mode
From the video: Practice: Dark Mode
  • People like dark mode
  • A toggle
  • Remember the choice

Theme toggle

The dark class on the body changes the colours, using CSS variables. Apply sets or removes the class, and updates the button's label. On load, we read the saved theme from local storage. Clicking the button flips the theme, and saves it. We clicked the button, then reloaded the page, and it's still dark.

index.htmlpython
<link rel="stylesheet" href="style.css">
<style>
  body { --bg: #fafafa; --fg: #222; background: var(--bg); color: var(--fg) }
  body.dark { --bg: #1e1e2e; --fg: #f1f1f1 }
</style>
<h1>My Blog</h1>
<button id="toggle"></button>
<script>
  function apply(theme) {
    document.body.classList.toggle("dark", theme === "dark");
    toggle.textContent = theme === "dark" ? "☀ Light mode" : "🌙 Dark mode";
  }
  apply(localStorage.getItem("theme") ?? "light");
  toggle.onclick = () => {
    const next = document.body.classList.contains("dark") ? "light" : "dark";
    localStorage.setItem("theme", next);
    apply(next);
  };
</script>
Also uses style.css
body{font-family:-apple-system,Helvetica,Arial,sans-serif;margin:22px;font-size:21px;color:#1d1d1f;background:#fafafa}
h1{font-size:34px;margin:0 0 14px} h2{font-size:26px;margin:0 0 10px}
button{font-size:19px;padding:9px 18px;border-radius:9px;border:0;background:#f7df1e;color:#111;font-weight:600;margin:4px 6px 4px 0}
input{font-size:19px;padding:8px 10px;border:2px solid #bbb;border-radius:8px}
li{margin:5px 0} .box{padding:14px;border-radius:12px;background:#fff;border:2px solid #ddd;margin:8px 0}
.done{text-decoration:line-through;color:#999} small{color:crimson;display:block;font-size:16px} .big{font-size:64px;font-weight:800}
Also uses actions.json
[{"click": "#toggle"}, {"reload": true}]

Respect the system

Operating systems have their own dark mode setting. CSS can read it with prefers color scheme, and JavaScript with match media. A good default is to follow the system, and only use the saved choice when the person has picked one themselves.

keyvalue
CSS variablesone place for colours
classList.toggleswitch the theme
localStorageremember it
matchMediathe system setting

Summary

The dark mode toggle used a class, CSS variables, and local storage to remember the choice. Next, checking a sign up form before it's sent.

Key takeaways
  • body.dark
  • CSS variables
  • Saved in localStorage
Next up: Practice: Form Validation — helpful error messages