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

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.


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.