Skip to main content

Command Palette

Search for a command to run...

CSS Media Query in Javascript

A quick look at matchMedia

Updated
2 min read
CSS Media Query in Javascript
G

I'm a frontend engineer with 5+ years of experience in building modern web-apps. I like to share my experience through writing, hoping to help other devs learn something interesting or useful.

Quick Summary

CSS media queries are very effective and optimal for applying styles based on device properties and settings. We’re going to look at a feature in javascript that let’s us use CSS media queries in our JS.

What’s matchMedia?

matchMedia is a method available on the window object that can be used to match or track a CSS media query on the document. Read more about it on MDN.

Syntax

Taking a CSS media query for example

@media (max-width: 480px) {
  body {
    font-size: 16px;
    background-color: lightgray;
  }
}

We would need what’s written after @media as it is

const matchMobileQuery = window.matchMedia("(max-width: 480px)");

Testing it on the browser console, here’s what the matchMedia returns

So we can take the matches variable to check whether the query matched or not.

To Track a media query, we can add a change event listener on the same MediaQueryList object given by the matchMedia.

Let’s test this with an example of prefers-color-scheme media query

const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');

function handleChange(e) {
  if (e.matches) {
    console.log('Dark mode');
  } else {
    console.log('Light mode');
  }
}

mediaQuery.addEventListener('change', handleChange);

We should see a console log whenever the color scheme changes

When to use?

  • To replace window.innerWidth to find out what device we’re on

  • Replace any element size tracking with resizeObserver, if it can be solved with a media query

  • It’s not just for screen size—use it to react to dark mode, device orientation, and more

Thanks for reading!

If you made it till here, let’s hear your thoughts on this in the comments!