DEV Community

Nathaniel
Nathaniel

Posted on • Originally published at endtimes.dev

4 2

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.

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay