skip to Main Content

In Firefox (and its forks) that dark mode doesn’t apply to all pages automatically. If you select dark mode it only works on one page, you have to set it manually on each page. In other browsers (Brave, Opera, etc), if you set the dark mode once, all the pages will be in dark mode automatically.
Why doesn’t this code work properly in Firefox? Local storage doesn’t work on it? Will I have to use cookie instead?

let trilho = document.getElementById('trilho');
let body = document.querySelector('body');

// Check local storage for the user's theme preference
const theme = window.localStorage.getItem("theme");

// Set the initial theme based on localStorage
if (theme === "dark") {
    body.classList.add("dark");
    trilho.classList.add("dark"); // Ensure the button reflects dark mode
} else {
    trilho.classList.remove("dark"); // Ensure the button reflects light mode
}

// Add event listener to toggle dark mode
trilho.addEventListener('click', () => {
    trilho.classList.toggle('dark');
    body.classList.toggle('dark');

    // Update localStorage with the current theme
    if (body.classList.contains("dark")) {
        window.localStorage.setItem("theme", "dark");
        trilho.classList.add("dark"); // Dark mode button
    } else {
        window.localStorage.setItem("theme", "light");
        trilho.classList.remove("dark"); // Light mode button
    }
});

2

Answers


  1. @Kay8 The proper way to handle dark mode is through CSS. Users should set their dark mode preferences in the browser. This provides users the most consistent experience.

    Example:

    @media (prefers-color-scheme: dark) {
      .theme-a.adaptive {
        background: #753;
        color: #dcb;
        outline: 5px dashed #000;
      }
    }
    
    Login or Signup to reply.
  2. You can achieve dark mode by using the prefers-color-scheme media query which can be used to detect the user’s system color scheme preferences, it can have two possible values: light and dark. MDN

    another method is to use a body class e.g. dark-theme, and a toggle function using JavaScript. This method can be used to override the system color scheme.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search