Using matchMedia for JavaScript media queries

  • JavaScript

Media queries revolutionised responsive website design by allowing us to target specific devices or viewports with CSS. This spurred the responsive movement and gave birth to modern practices such as "mobile first" design.

Unfortuntely, this methodology is often forlorn when it comes to JavaScript. However, by utilising the matchMedia method; you can change that.

Using the matchMedia method

The matchMedia method allows you to define JavaScript media queries by binding an event handler to a breakpoint.

The method accepts a string - which should look familiar - as it is identical to a CSS media query breakpoint.

The example below uses a breakpoint of max-device-width: 480px:

  
  // Define media query
  const mql = window.matchMedia("screen and (max-device-width: 480px)");

In the past, it was common to bind an event handler to the window.resize() event, which would fire every time the window was resized. This is a lacklustre solution and inefficient.

Fortunately, the matchMedia handler will only trigger once; each time the viewport condition is matched or unmatched. This should be enough to appease the hunger of every performance-hungry developer.

The method returns a new MediaQueryList object with a pair of members:

  • addListener
  • removeListener

These two methods respectively bind and unbind a callback method, that is executed when the browser's viewport matches or unmatches the breakpoint specified by the media query.

Using the matches method

The example below creates a MediaQueryList that executes a callback when the viewport matches or unmatches the defined breakpoint of max-device-width: 480px.


  // Define media query
  const mql = window.matchMedia("screen and (max-device-width: 480px)");
    
  if (mql.matches) {
    // Device width is <= 480px
  } else {
    // Device width is >= 481px
  }

The matches property is a boolean and returns either true or false, depending on the query result. Using the example above:

  • When the viewport width is less than or equal to 480px pixels, the matches check would return true.
  • When the viewport width is equal to or greater than 481px, the matches check would returns false.

Afterword

Combining these two methods allows you to approach your JavaScript with methodology similar to that used for responsive CSS.

Browser support

Both matchMedia and MediaQueryList are supported in all common, modern browsers.