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.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.