DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Nathaniel
Nathaniel

Posted on • Originally published at endtimes.dev

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((event) => {
  console.log(event.matches) // True if Dark Mode is on
});

Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)

🌚 Browsing with dark mode makes you a better developer.

It's a scientific fact.