brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: matchMedia() with a change listener follows dark mode while the page is open

Javascript
~/tips/tip-js-matchmedia-change-dark-mode

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

React in a script when the visitor switches between light and dark mode.

CSS media queries update by themselves, but a chart or map drawn by a script keeps its old colors when someone switches to dark mode. matchMedia() gives a script the same information, plus an event when it changes.

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

function applyTheme() {
  chart.setTheme(dark.matches ? "dark" : "light");
}

applyTheme();
dark.addEventListener("change", applyTheme);

matchMedia() takes any media query and returns a MediaQueryList. Its matches property says whether the query applies right now, and its change event fires when that flips. I call the function once at startup and then on every change. On macOS with automatic appearance, that means the chart switches at sunset without a reload.

The same pattern works for other queries: (prefers-reduced-motion: reduce) to stop a carousel, or (min-width: 60rem) to switch a component between layouts without listening to every resize.

A compatibility note: older code uses dark.addListener(fn). MDN marks that method as deprecated; addEventListener("change", ...) works in Chrome 39, Firefox 55 and Safari 14 and later. Before Safari 14 only addListener existed, which is why you still see it in old snippets.

Further reading: MDN: Window.matchMedia(), MDN: MediaQueryList change event

More Javascript tips node --inspect-brk app.js obj?.prop const filePath = String.raw`C:\Development\profile\about.html`; const observer = new ResizeObserver((entries) => { URL.parse("not a url"); // null All Javascript tips (40) All topics

Link