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

As an alternative to the MediaQueryList.removeListener() method, you can simply use MediaQueryList.removeEventListener(), for example, like so:

const mediaQuery = window.matchMedia('(max-width: 425px)');
const handler = function (e) {
    // ...
};

mediaQuery.removeEventListener('change', handler);

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.removeListener() was used instead of EventTarget.removeEventListener().

The equivalent of the code above, using MediaQueryList.removeListener() would be the following:

const mediaQuery = window.matchMedia('(max-width: 425px)');
const handler = function (e) {
    // ...
};

mediaQuery.removeListener(handler);

Please note that, for versions prior to Safari 14, you should stick to MediaQueryList.removeListener(), as using MediaQueryList.removeEventListener() will give you an error; "TypeError: window.matchMedia(...).removeEventListener 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.