DEV Community

Discussion on: Media queries in JS

Collapse
 
rvxlab profile image
RVxLab • Edited
// Register event listener
mediaQuery.addListener(handleWindowChange)
Enter fullscreen mode Exit fullscreen mode

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:

const mediaQuery = window.matchMedia('(min-width: 768px)')

function handleTabletChange(e) {
  // Check if the media query is true
  if (e.matches) {
    doResponsiveThings();
  }
}

// Register event listener
if (mediaQuery.addEventListener) {
  mediaQuery.addEventListener('change', handleWindowChange);
} else {
  mediaQuery.addListener(handleWindowChange);
}

// Initial check
handleWindowChange(mediaQuery);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
dannyviiprus profile image
Dannyvpz

Thanks for the update solution!