Skip to content
Advertisement

How to detect prefers-color-scheme change in javascript?

I can use window.matchMedia to detect whether user is in dark mode, but how to listen dark mode change event?

Is there any API like:

window.addEventListener('perfers-color-scheme-change', () => {
  // do something
})

Advertisement

Answer

You can add an event-listener with callback on the MediaQueryList returned by Window.matchMedia():

function activateDarkMode() {
  // set style to dark
}

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

// recommended method for newer browsers: specify event-type as first argument
darkModePreference.addEventListener("change", e => e.matches && activateDarkMode());

// deprecated method for backward compatibility
darkModePreference.addListener(e => e.matches && activateDarkMode());

Note: There are two method versions to register an event-listener:

  1. the recommended addEventListener("change", listener)) which allows more fine-grained assignment to event-types
  2. the deprecated addListener(listener)

See also


Thanks to lukaszpolowczyk for pointing out that method addListener(listener) has become deprecated and to AsukaSong for initiating a complete rewrite of this answer.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement