Project - 2

Project 2: Color Theme Switcher

Build a theme switcher that lets users choose between Dark, Light, Neon, and Retro themes.

Your challenge: Change the page theme with JavaScript and save the selected theme with localStorage so it can be restored later.

✦ HTML + CSS + JS Editor
▶ Live Output

Change the theme

Each button has a data-theme value such as dark or neon.

Use document.body.className = theme; to apply the matching CSS class.

Save the choice

Use localStorage.setItem("theme", theme); to store the selected theme.

Load the saved theme

Read it with localStorage.getItem("theme"). If no theme has been saved yet, use dark as the default.

Try it: Switch between all four themes, then reload the page and check that your last theme is restored.

Good JavaScript habit: Put the theme-changing logic inside one function so every button can reuse it.

👀 Show Full Working Solution
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Theme Switcher</title>

  <style>
    body {
      font-family: 'Courier New', monospace;
      padding: 40px;
      margin: 0;
      text-align: center;
      transition: background 0.3s, color 0.3s;
    }

    button {
      margin: 5px;
      padding: 10px 15px;
      cursor: pointer;
    }

    button:focus-visible {
      outline: 3px solid currentColor;
      outline-offset: 3px;
    }

    .dark {
      background: #000;
      color: #8A8A8A;
    }

    .light {
      background: #fff;
      color: #222;
    }

    .neon {
      background: #020024;
      color: #39ff14;
    }

    .retro {
      background: #f4ecd8;
      color: #5b4636;
    }
  </style>
</head>

<body class="dark">

  <h2>Color Theme Switcher</h2>

  <p>Choose a theme:</p>

  <div>
    <button type="button" data-theme="dark">Dark</button>
    <button type="button" data-theme="light">Light</button>
    <button type="button" data-theme="neon">Neon</button>
    <button type="button" data-theme="retro">Retro</button>
  </div>

  <script>
    const themeButtons =
      document.querySelectorAll("[data-theme]");

    function setTheme(theme) {
      document.body.className = theme;

      try {
        localStorage.setItem("theme", theme);
      } catch (error) {
        console.log("Theme could not be saved.");
      }
    }

    themeButtons.forEach(function(button) {
      button.addEventListener("click", function() {
        setTheme(button.dataset.theme);
      });
    });

    let savedTheme = "dark";

    try {
      savedTheme =
        localStorage.getItem("theme") || "dark";
    } catch (error) {
      savedTheme = "dark";
    }

    setTheme(savedTheme);
  </script>

</body>
</html>