Using window.matchMedia

Window matchmedia

Responsive web design has become a natural approach, and developers attend it using CSS media queries. However, there is another option to do that, window.matchMedia is a javascript option to do media queries and I'll explain how to use it.

Introduction to matchMedia
It's very easy to approach media queries in Javascript. It's very similar than CSS, but with Javascript syntax.

var widthMediaQuery = window.matchMedia("(min-width: 680px)");

This code returns an object, a MediaQueryList object which has these list of methods:

  • matches: Check if the query is matched or not.
  • media: Serialized media query list.
  • addListener: Adding event to a media query.
  • removeListener: Removing event from a media query.

Example
The easy way to determine if a media query is matched:

(function () {
  function mediaQueryListener(mediaQueryList) {
    //do something with the object, or add events with jQuery for example.
  }

  if(window.matchMedia) {
    var widthMediaQuery = window.matchMedia("(min-width: 680px)");

    widthMediaQuery.addListener(mediaQueryListener);
  }
})();

Support
At this time, matchMedia is supported for this browsers:

  • Internet Explorer 10.
  • Firefox 6+
  • Google Chrome 9+
  • Safari 5.1+.
  • Firefox mobile
  • Google Chrome on Android.
  • Safari 5 on iOS.
  • Android stock browser.

Can I use window.matchMedia?