DEV Community

Cover image for One Byte Explainer: matchMedia

One Byte Explainer: matchMedia

Andrew Bone on March 20, 2024

This is a submission for DEV Challenge v24.03.20, One Byte Explainer: Browser API or Feature. Explainer matchMedia, which exists on the...
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.