Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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()); 
like image 268
Matt Cowley Avatar asked Jun 05 '19 18:06

Matt Cowley


2 Answers

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(); }); 
like image 141
random Avatar answered Sep 19 '22 14:09

random


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.

like image 43
Szabó Csaba Avatar answered Sep 20 '22 14:09

Szabó Csaba