DEV Community

Cover image for One Byte Explainer: matchMedia
Andrew Bone
Andrew Bone

Posted on

One Byte Explainer: matchMedia

This is a submission for DEV Challenge v24.03.20, One Byte Explainer: Browser API or Feature.

Explainer

matchMedia, which exists on the window, is a method that facilitates checking CSS media queries in JavaScript. You can even use event listeners, with the change event, to detect media changes which can be super useful and, more importantly, cheap!

Additional Context

matchMedia is just so useful for those rare instances where media queries in CSS aren't enough and it's so much lighter than manually getting the size of the page and rechecking on every resize 😅.

Top comments (4)

Collapse
 
pablojakub profile image
pablojakub

What do you mean using change event in this context?
document.addEventListener('change', () => {
window.matchMedia('(max-width: 480px)') {
// do something
}
})

?

Collapse
 
link2twenty profile image
Andrew Bone • Edited

Not quite you have to put the event listener on the returned matchMedia instance, like this.

// set up the matchMedia instance
const isSmall = window.matchMedia('(max-width: 480px)');

// send true/false value off to some function to handle it
someFunction(isSmall.matches) // this will be true/false depending on the media matching

// set up a listener to detect media match changes
isSmall.addEventListener('change', (event) => {
  // set the new true/false value to some function
  someFunction(event.matches);
});
Enter fullscreen mode Exit fullscreen mode

Here's a quick example you can play with

Collapse
 
pablojakub profile image
pablojakub

Very nice :) Thank you. I suppose this is more optimal than window resize event ? :)

Thread Thread
 
link2twenty profile image
Andrew Bone

Very much so! It's why I love it so much it's fast and only fires when the media changes so no need to debounce.