What's the Substitute for the Deprecated matchMedia() .addListener() Method?

Alternative for MediaQueryList "addListener()" method in JavaScript

As an alternative to the MediaQueryList.addListener() method, you can simply use MediaQueryList.addEventListener(), and listen to the "change" event. This will run the provided callback function when the media query status changes.

For example, let's suppose you have the following code that uses the deprecated MediaQueryList.addListener() method:

const mediaQuery = window.matchMedia('(max-width: 425px)');

mediaQuery.addListener(function (e) {
    // ...
});

Its equivalent using the MediaQueryList.addEventListener() method would be the following:

const mediaQuery = window.matchMedia('(max-width: 425px)');

mediaQuery.addEventListener('change', function (e) {
    // ...
});

This works because the MediaQueryList object (which is returned by window.matchMedia()), now inherits from the EventTarget object. In older browsers, however, that was not the case. This is why MediaQueryList.addListener() was used instead of EventTarget.addEventListener().

Please note that, for versions prior to Safari 14, you should stick to MediaQueryList.addListener(), as using MediaQueryList.addEventListener() will give you an error; "TypeError: window.matchMedia(...).addEventListener is not a function". This is because in those versions, the MediaQueryList object does not inherit from the EventTarget object.


Hope you found this post useful. It was published . Please show your love and support by sharing this post.