Free Web & Developer Tools

Fast, lightweight, and built to solve daily coding and blogging tasks.

Explore All Tools

How to Detect System Theme Dynamically in JavaScript

Learn how to detect the system theme in JavaScript using matchMedia, prevent page flash on load, and let visitors override it with a manual toggle.

Most operating systems let people choose a light or dark appearance, and browsers pass that choice on to web pages. A page that ignores it can blind someone who has dark mode on at midnight. A page that reads it once on load still gets it wrong when the system switches to dark at sunset while the tab stays open.

This guide shows how to detect the system theme with matchMedia(), react when it changes, avoid the flash of the wrong theme on load, and let visitors override the system choice.

How the browser exposes the system theme

The prefers-color-scheme media feature reports the theme the user has chosen at the operating system or browser level. In JavaScript you read it through window.matchMedia(), which returns a MediaQueryList object with a matches property and a change event. All current browsers support it, and it has worked in the major browsers since 2019.

Media query matches is true when
(prefers-color-scheme: dark) The user prefers a dark appearance.
(prefers-color-scheme: light) The user prefers a light appearance.

The early version of the spec also had a no-preference value, but browsers now report only light or dark. The simplest reliable check is therefore to test for dark and treat everything else as light.

Detect the theme and listen for changes

const darkQuery = window.matchMedia("(prefers-color-scheme: dark)");

// Current theme
console.log(darkQuery.matches ? "dark" : "light");

// Runs every time the system theme changes
darkQuery.addEventListener("change", (event) => {
  console.log(event.matches ? "dark" : "light");
});

The first line gives you the current theme. The listener runs whenever the user switches the system theme, including automatic switches at sunset on devices that have that option, and it does not need a page reload.

Note: Safari before version 14 has no addEventListener() on a MediaQueryList and only supports the older addListener() method. If you support those versions, call addListener() as a fallback.

Apply the theme in CSS

Keep your colors in CSS custom properties and let JavaScript set a single data-theme attribute on the <html> element. The media query in the stylesheet covers visitors whose JavaScript has not run, and the attribute rules take over once it has.

/* Default (light) colors */
:root {
  color-scheme: light dark;
  --bg: #ffffff;
  --text: #1a1a1a;
  --link: #0b5fff;
}

/* JavaScript has not set a theme yet, or is turned off: follow the system */
@media (prefers-color-scheme: dark) {
  :root:not([data-theme]) {
    --bg: #121212;
    --text: #e8e8e8;
    --link: #7aa7ff;
  }
}

/* JavaScript has chosen a theme */
:root[data-theme="light"] {
  color-scheme: light;
}

:root[data-theme="dark"] {
  color-scheme: dark;
  --bg: #121212;
  --text: #e8e8e8;
  --link: #7aa7ff;
}

body {
  background: var(--bg);
  color: var(--text);
}

a {
  color: var(--link);
}

color-scheme tells the browser to draw built-in elements, such as form controls, scrollbars and the default page background, in the matching theme. Without it, a dark page can still show a bright scrollbar.

The attribute selector :root[data-theme="dark"] has higher specificity than a plain :root rule, which is why the JavaScript-chosen theme wins. If you mix media queries, attributes and classes and your styles stop applying, CSS specificity explained shows how to work out which rule is winning.

A shorter option: light-dark()

The CSS light-dark() function picks a color based on the active color-scheme, so each color is written once instead of twice. It works in browsers released since mid-2024, so check your audience before you rely on it.

:root { color-scheme: light dark; }
:root[data-theme="light"] { color-scheme: light; }
:root[data-theme="dark"] { color-scheme: dark; }

body {
  background: light-dark(#ffffff, #121212);
  color: light-dark(#1a1a1a, #e8e8e8);
}

a {
  color: light-dark(#0b5fff, #7aa7ff);
}

Avoid the flash of the wrong theme

If your theme script sits at the end of the page, the browser can paint a light page first and switch to dark a moment later. To prevent that, run a tiny inline script in the <head>, before your stylesheet, and add a color-scheme meta tag so the browser starts with the right default colors.

<head>
  <meta name="color-scheme" content="light dark">
  <script>
    (function () {
      var saved = null;
      try { saved = localStorage.getItem("theme"); } catch (e) {}

      var dark = saved === "dark" ||
        (saved !== "light" && window.matchMedia("(prefers-color-scheme: dark)").matches);

      document.documentElement.dataset.theme = dark ? "dark" : "light";
    })();
  </script>
  <link rel="stylesheet" href="/styles.css">
</head>

The script reads the saved choice, falls back to the system theme and sets data-theme before the first paint. It uses the same theme key as the helper in the next section, so change both together if you rename it. It wraps the storage read in try/catch, because browsers can block storage access.

Info! If you paste this script into the theme editor of a Blogger blog, the editor treats the theme as XML. Characters such as && and < can cause a parse error. Wrap the script body in //<![CDATA[ and //]]> to avoid it.

Let visitors override the system theme

Many people want a site to differ from their system setting. A three-way choice covers every case:

Preference Theme used Follows system changes Saved
system Whatever the operating system reports Yes No. Nothing is stored, so the system decides.
light Light No Yes, in localStorage
dark Dark No Yes, in localStorage

The helper below keeps the preference apart from the theme that results from it. That split matters: the media query listener must react to system changes only while the preference is system, and ignore them once the visitor has picked a side.

function createThemeManager({ storageKey = "theme", onChange = () => {} } = {}) {
  const media = window.matchMedia("(prefers-color-scheme: dark)");
  const root = document.documentElement;
  const OPTIONS = ["system", "light", "dark"];

  // "system" means: follow the operating system.
  function readPreference() {
    try {
      const saved = localStorage.getItem(storageKey);
      return saved === "light" || saved === "dark" ? saved : "system";
    } catch {
      return "system"; // storage blocked
    }
  }

  let preference = readPreference();

  const resolve = () =>
    preference === "system" ? (media.matches ? "dark" : "light") : preference;

  function apply() {
    root.dataset.theme = resolve();
    onChange({ preference, theme: resolve() });
  }

  function setPreference(next) {
    if (!OPTIONS.includes(next)) {
      throw new RangeError(`Theme must be one of: ${OPTIONS.join(", ")}`);
    }
    preference = next;
    try {
      if (next === "system") localStorage.removeItem(storageKey);
      else localStorage.setItem(storageKey, next);
    } catch {}
    apply();
  }

  // The system theme only matters while the preference is "system".
  media.addEventListener("change", () => {
    if (preference === "system") apply();
  });

  // Keep other open tabs in step (key is null when storage is cleared).
  window.addEventListener("storage", (event) => {
    if (event.key === storageKey || event.key === null) {
      preference = readPreference();
      apply();
    }
  });

  apply();

  return {
    get preference() { return preference; },
    get theme() { return resolve(); },
    setPreference,
    cycle() {
      setPreference(OPTIONS[(OPTIONS.indexOf(preference) + 1) % OPTIONS.length]);
    },
  };
}

What the helper does

  • Reads the saved preference on creation and treats missing, invalid or unreadable values as system.
  • Sets data-theme on the root element every time the preference or the system theme changes, and calls your onChange function with both the preference and the resulting theme.
  • Removes the saved value when the visitor goes back to system, so later system changes apply again.
  • Listens to the storage event, so a change made in one tab shows up in the other open tabs.
  • Throws a RangeError for an unknown preference instead of saving a value it cannot use later.
  • Keeps working when localStorage is blocked. The choice just lasts until the page closes.

Connect it to a button

<button id="theme-toggle" type="button"></button>
const button = document.querySelector("#theme-toggle");
const labels = { system: "System", light: "Light", dark: "Dark" };

const theme = createThemeManager({
  onChange({ preference }) {
    button.textContent = `Theme: ${labels[preference]}`;
  },
});

button.addEventListener("click", () => theme.cycle());

Each click moves to the next option in the order system, light, dark. The label shows the preference rather than the current theme, so a visitor on System can see that the page is following their device.

Images and other assets

A logo with a dark background can disappear on a dark page. The <picture> element can swap files based on prefers-color-scheme.

<picture>
  <source srcset="logo-dark.png" media="(prefers-color-scheme: dark)">
  <img src="logo-light.png" alt="Site logo" width="160" height="40">
</picture>
Warning! A media attribute on <source> follows the system theme only. It does not know about your data-theme override, so a visitor who chose Light on a dark system still gets the dark image. For sites with a manual toggle, use SVG images that take their color from currentColor, or swap the image src from the onChange callback. How to use srcset and picture tags covers the element in detail.

Test it

  1. In Chrome or Edge, open DevTools, press Ctrl+Shift+P, type Show Rendering and open the panel. Set Emulate CSS media feature prefers-color-scheme to dark, then to light.
  2. In Firefox, open the Inspector and use the sun and moon buttons at the top of the Rules panel.
  3. Watch the data-theme attribute on the <html> element. While the button says System, it should change with each emulation switch.
  4. Click the button until it says Light, then emulate dark again. The page should stay light.
  5. Reload the page. The saved choice should apply with no flash of the other theme.
  6. For a real device test, switch your operating system between light and dark while the page is open. On Windows this is under Settings, Personalization and Colors. On macOS it is under System Settings and Appearance.
Done! If the page follows the system on System and ignores it on Light and Dark, the setup works.

Troubleshooting

The page flashes light before turning dark

The theme script runs too late. Move it into the <head> before your stylesheet, and add the color-scheme meta tag. Make sure the script is inline, because an external file adds a request before the first paint.

The theme does not follow the system after the visitor used the toggle

The saved choice overrides the system. Switching the preference back to system removes it. Clearing site data does the same.

The theme does not change when I switch it in DevTools

DevTools emulation changes only what the page sees, and only while the panel is open. If the toggle is set to Light or Dark, the helper ignores system changes on purpose.

Form controls and scrollbars stay light

The page has no color-scheme declaration. Add color-scheme: light dark to :root, and set it to the active theme in your data-theme rules, as shown earlier.

SecurityError when reading localStorage

Error! Some browsers throw when storage is blocked, for example in strict privacy modes or sandboxed frames.

Both scripts above catch this error and fall back to the system theme. If you add your own storage calls, wrap them the same way.

FAQs

How do I detect dark mode in JavaScript?

Call window.matchMedia("(prefers-color-scheme: dark)").matches. It returns true when the system or browser is set to dark and false otherwise.

How do I react when the user changes the system theme?

Add a change listener to the MediaQueryList object. The event has a matches property that is true for dark. Keep the object in a variable, because you need it to remove the listener later.

Do I need JavaScript to support dark mode?

No. A @media (prefers-color-scheme: dark) block in CSS follows the system on its own. You need JavaScript only for a manual toggle, for saving a choice, or for changing things CSS cannot reach, such as swapping an image source.

Where should I store the user's theme choice?

localStorage is enough for a client-side choice, and it is readable by an inline script in the head. Use a cookie only if your server needs the value to render the right theme on the first response. Store the explicit choice, and store nothing for the system option.

Why does my dark page still show a white flash while loading?

Either the theme is applied after the first paint, or the browser has no hint that the page supports dark. Set the theme with an inline script in the head, add <meta name="color-scheme" content="light dark">, and declare color-scheme in your CSS.

Conclusion

Read the system theme with matchMedia("(prefers-color-scheme: dark)"), listen to its change event, and set one data-theme attribute that your CSS responds to. Apply the saved choice from a small script in the head to prevent a flash, and keep the visitor's preference separate from the resulting theme so that system, light and dark each behave predictably.

About the author

Suptojit Modak
Suptojit Modak
I'm Suptojit Modak, a web developer and the person behind BytebaseX — a blog with tutorials, guides, and free resources for developers and bloggers, built to be simple and easy to follow.

Instagram · GitHub · Facebook

Post a Comment