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)
What do you mean using change event in this context?
document.addEventListener('change', () => {
window.matchMedia('(max-width: 480px)') {
// do something
}
})
?
Not quite you have to put the event listener on the returned
matchMedia
instance, like this.Here's a quick example you can play with
Very nice :) Thank you. I suppose this is more optimal than window resize event ? :)
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.