Mind you that MediaQueryList.addListener is deprecated, MediaQueryList extends from EventTarget so you can use addEventListener instead.
Notable exception being Safari 13 and earlier, which doesn't do this.
The ideal solution is to check for addEventListener and fall back to addListener when it's not available:
constmediaQuery=window.matchMedia('(min-width: 768px)')functionhandleTabletChange(e){// Check if the media query is trueif(e.matches){doResponsiveThings();}}// Register event listenerif(mediaQuery.addEventListener){mediaQuery.addEventListener('change',handleWindowChange);}else{mediaQuery.addListener(handleWindowChange);}// Initial checkhandleWindowChange(mediaQuery);
Mind you that
MediaQueryList.addListener
is deprecated,MediaQueryList
extends fromEventTarget
so you can useaddEventListener
instead.Notable exception being Safari 13 and earlier, which doesn't do this.
The ideal solution is to check for
addEventListener
and fall back toaddListener
when it's not available:Thanks for the update solution!