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

Why Does This Error Happen?

If you're getting the error, "TypeError: window.matchMedia(...).removeEventListener is not a function" then it means that the browser you're using does not yet have support for the removeEventListener 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 removeEventListener method available on the MediaQueryList object. However, in older browsers that was not the case. Instead, the MediaQueryList.removeListener() method was used in its place.

How to Fix This Error?

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

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

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

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

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