How to Fix the JavaScript TypeError "matchMedia(...) .addEventListener is not a function"?

Why Does This Error Happen?

If you're getting the error, "TypeError: window.matchMedia(...).addEventListener is not a function" then it means that the browser you're using does not yet have support for the addEventListener method on the MediaQueryList object (which is returned by window.matchMedia(...)).

In modern browsers, the MediaQueryList object inherits from the EventTarget object, which makes the addEventListener method available on the MediaQueryList object. However, in older browsers that was not the case. Instead, the MediaQueryList.addListener() method was used in its place.

How to Fix This Error?

You can fix this error by using the MediaQueryList.addListener() method as a fallback for browsers that don't yet support MediaQueryList.addEventListener(), for example, like so:

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

if (mediaQuery?.addEventListener) {
    mediaQuery.addEventListener('change', handler);
} else {
    mediaQuery.addListener(handler);
}

Please be aware that the MediaQueryList.addListener() method has been deprecated. The official W3 spec states that it merely exists as an alias for MediaQueryList.addEventListener() (for backward compatibility reasons).


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.