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:
JavaScript
x
4
1
window.addEventListener('perfers-color-scheme-change', () => {
2
// do something
3
})
4
Advertisement
Answer
You can add an event-listener with callback on the MediaQueryList
returned by Window.matchMedia():
JavaScript
1
13
13
1
function activateDarkMode() {
2
// set style to dark
3
}
4
5
// MediaQueryList
6
const darkModePreference = window.matchMedia("(prefers-color-scheme: dark)");
7
8
// recommended method for newer browsers: specify event-type as first argument
9
darkModePreference.addEventListener("change", e => e.matches && activateDarkMode());
10
11
// deprecated method for backward compatibility
12
darkModePreference.addListener(e => e.matches && activateDarkMode());
13
Note: There are two method versions to register an event-listener:
- the recommended
addEventListener("change", listener))
which allows more fine-grained assignment to event-types - 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.