21

The Mozilla Developers Network docs say MediaQueryList.addListener() is deprecated.

Though it's working in my (Angular 8) code, the linting in VS Code is warning about deprecation.

What's the replacement for MediaQueryList.addListener()?

hc_dev
  • 8,389
  • 1
  • 26
  • 38
Chaitanya
  • 847
  • 1
  • 8
  • 15
  • The [MDN docs for addListener](https://developer.mozilla.org/en-US/docs/Web/API/MediaQueryList/addListener) not only mention deprecation but also recommend the replacement: "Use `addEventListener()` instead of addListener() if it is available in the browsers you need to support." – hc_dev Sep 25 '22 at 10:25

2 Answers2

45

Quoting from the MDN docs about MediaQueryList:

MediaQueryList.addListener() Adds a listener to the MediaQueryListener that will run a custom callback function in response to the media query status changing. This is basically an alias for EventTarget.addEventListener(), for backwards compatibility purposes.

addEventListener needs an event type as the first argument, so it becomes this:

// deprecated: MediaQueryList.addListener(listener);
MediaQueryList.addEventListener('change', listener);

The same stands true for removeListener():

// deprecated: MediaQueryList.removeListener(listener);
MediaQueryList.removeEventListener('change', listener);
Penny Liu
  • 15,447
  • 5
  • 79
  • 98
mutil
  • 3,205
  • 1
  • 27
  • 34
  • 6
    Please mind the compatibility table at MDN. One year later the new format is still not supported on Safari, I learned that the hard way :( – Kos Sep 11 '20 at 11:59
  • 2
    Here's a [link to the compatibility table](https://developer.mozilla.org/en-US/docs/Web/API/MediaQueryList#browser_compatibility) for those who want it, look for the "MediaQueryList inherits EventTarget" row. It's now supported from Safari 14 and upwards. – Ethan Jun 30 '21 at 04:57
3

Do this to ensure compatibility with browsers that do not support MediaQueryList.addEventListener:

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

if (darkModeQuery.addEventListener) {
  darkModeQuery.addEventListener('change', setDarkMode)
} else {
  darkModeQuery.addListener(setDarkMode)
}
Aparajita
  • 508
  • 3
  • 8