Listen for changes between dark and light mode with javascript

You can use javascript to listen for changes between light mode and dark mode.

Color preferences mostly effect style, and so are the realm of css. But some changes need to be made using javascript, like loading external resources.

Here's how:

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

darkModeMediaQuery.addListener((e) => {
  console.log(e.matches) // True if Dark Mode is on

When to use this? #

I first came accross this while making green quarantine. The site has two versions of the same mapbox map, one for dark mode and one for light mode.

When user preferences changed while on the site, the map would stay the same. I discovered this while trying to solve that issue.

You may think this is overkill, or an edge case. How likely is it that a user changes their color preferences while on your site?

But, many devices automatically change color schemes based on the time of day. If you're making a site, or web extension that stays open for a long time, it's very likely to happen.

Also, while developing it's nice to not have to refresh the page.

26 Dec 2020
26 Dec 2020
posts javascript css dark mode