matchMedia().addListener marked as deprecated, addEventListener equivalent?

JavascriptAddeventlistenerMatchmedia

Javascript Problem Overview


I'm making use of matchMedia().addListener to detect dark/light mode theme preference changes in Safari, however in WebStorm using addListener is marked as deprecated but simply says to refer to documentation for what should replace it.

I've had a read through the MDN docs and I don't understand what event type I should be listening for in addEventListener to replace addListener?

window.matchMedia("(prefers-color-scheme: dark)").addListener(() => this.checkNative());
window.matchMedia("(prefers-color-scheme: light)").addListener(() => this.checkNative());

Javascript Solutions


Solution 1 - Javascript

From the doc - https://developer.mozilla.org/en-US/docs/Web/API/MediaQueryList/addListener

> A function or function reference representing the callback function you want to run when the media query status changes.

It should be change event. https://developer.mozilla.org/en-US/docs/Web/API/MediaQueryList/onchange.

const mql = window.matchMedia("(prefers-color-scheme: dark)");

mql.addEventListener("change", () => {
    this.checkNative();
});

Solution 2 - Javascript

Chrome and Firefox handle it differently than Safari, I solved it with way:

const darkMediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
  
  try {
    // Chrome & Firefox
    darkMediaQuery.addEventListener('change', (e) => {
      this.$vuetify.theme.dark = !this.$vuetify.theme.dark;
    });
  } catch (e1) {
    try {
      // Safari
      darkMediaQuery.addListener((e) => {
        this.$vuetify.theme.dark = !this.$vuetify.theme.dark;
      });
    } catch (e2) {
      console.error(e2);
    }
  }

If you're interested in how to support Dark Mode with your website, read this blogpost.

Solution 3 - Javascript

If you just do as MDN writes it works cross browser (where it's supported):

const mql = window.matchMedia('(max-width: 767px)');
mql.onchange = (e) => { 
  /* ... */
}

Should be supported above IE. E.g. all Edge + modern browsers.

https://developer.mozilla.org/en-US/docs/Web/API/MediaQueryList/onchange

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMatt CowleyView Question on Stackoverflow
Solution 1 - JavascriptrandomView Answer on Stackoverflow
Solution 2 - JavascriptSzabó CsabaView Answer on Stackoverflow
Solution 3 - JavascriptOZZIEView Answer on Stackoverflow