darkmode.js

The darkmode.js file is used to manage the user’s theme preference and is associated with the navigation/top.html partial layout.

                <div class="flex items-center space-x-4">
                    <button id="chatTocToggle" aria-label="Toggle Chat" class="hidden md:block"><img src="/icons/toggle-left.svg" class="w-5 h-5" alt="left/right toggle"></button>
                    <button id="darkModeToggle" aria-label="Toggle Darkmode" class=""><img src="/icons/light.svg" class="w-5 h-5" alt="sun/moon toggle"></button>
                </div>
            </div>
        </div>
    </div>
</nav>

How it Works

  1. This script checks to if the user has darkmode saved in their local storage.
  2. If not, when toggled it:
    • Saves the setting to local storage
    • Adds the dark class to the html element
    • Swaps the path for all image elements associated with the icon class from /icons/light/ to /icons/dark/
You can find the .dark class styling overrides in the assets/css/src/input.css file.

Source Code

document.addEventListener("DOMContentLoaded", function (event) {
  const darkModeToggle = document.getElementById("darkModeToggle");

  // Load saved theme preference
  const savedTheme = localStorage.getItem("theme-mode");
  if (savedTheme) {
    document.documentElement.classList.toggle("dark", savedTheme === "dark");
    updateButtonText();
    updateSectionIcons();
  }

  darkModeToggle.addEventListener("click", () => {
    const isDarkMode = document.documentElement.classList.contains("dark");
    document.documentElement.classList.toggle("dark", !isDarkMode);

    // Update the theme mode and button text
    localStorage.setItem(
      "theme-mode",
      document.documentElement.classList.contains("dark") ? "dark" : "light"
    );
    updateButtonText();

    // Update the section icons
    updateSectionIcons();
  });

  function updateButtonText() {
    const isDarkMode = document.documentElement.classList.contains("dark");

    darkModeToggle.innerHTML = isDarkMode
      ? '<img src="/icons/dark.svg" aria-label="activate lightmode" class="w-5" alt="moon">'
      : '<img src="/icons/light.svg" aria-label="activate darkmode" class="w-5" alt="sun">';
  }

  function updateSectionIcons() {
    const isDarkMode = document.documentElement.classList.contains("dark");
    const sectionIcons = document.querySelectorAll(".icon");

    sectionIcons.forEach((icon) => {
      const src = icon.getAttribute("src");
      const newSrc = isDarkMode
        ? src.replace("/icons/light/", "/icons/dark/")
        : src.replace("/icons/dark/", "/icons/light/");
      icon.setAttribute("src", newSrc);
    });
  }
});