Media queries are core to responsive design. Usually they live in CSS, but sometimes you need to run logic at a breakpoint from JavaScript. Here's the clean way to do it.
The old way: resize + innerWidth
The common approach listens to resize and checks window.innerWidth:
function checkMediaQuery() {
if (window.innerWidth > 768) {
doResponsiveThings();
}
}
window.addEventListener('resize', checkMediaQuery);
It works, but resize fires constantly while dragging — wasteful, and the check runs even when the breakpoint hasn't actually changed.
The better way: matchMedia()
window.matchMedia() takes the same string you'd use in CSS and gives you a MediaQueryList with a .matches boolean. Browser support is excellent (back to IE10).
const mediaQuery = window.matchMedia('(min-width: 768px)');
if (mediaQuery.matches) {
doResponsiveThings();
}
React to changes
Instead of polling on resize, listen for the query's change event — it only fires when the match state actually flips:
const mediaQuery = window.matchMedia('(min-width: 768px)');
function handleChange(e) {
if (e.matches) {
// viewport is now >= 768px
} else {
// viewport is now < 768px
}
}
mediaQuery.addEventListener('change', handleChange);
// run once on load for the initial state
handleChange(mediaQuery);
Why it's better
- Fires only on actual breakpoint changes — not every pixel of resize.
- Same syntax as your CSS breakpoints, so logic stays in sync.
- No manual width math.
Reach for matchMedia whenever JavaScript needs to know about a breakpoint.
