JS

JavaScript media queries

John Sylvain - November 07, 2019

CSS Media queries are great, and thanks to matchMedia we can use them in JavaScript just as easily.

MDN Reference

A helper function

This is a handy function for attaching listening to a media query, and a cleanup function.

function mediaQuery(query, handler) {
  const media = window.matchMedia(query);
  const listener = () => {
    if (media.matches) {
      handler();
    }
  };
  media.addListener(listener);

  return () => media.removeListener(listener);
}

Examples

Detecting screen size:

const unsubscribe = mediaQuery('(max-width: 768px)', () => {
  console.log('window is less than 768px'):
});

unsubscribe();

Detecting dark mode preference:

const unsubscribe = mediaQuery('(prefers-color-scheme: dark)', () => {
  console.log('use dark mode'):
});

unsubscribe();