David Baron's Weblog

window.matchMedia()

Friday, 2011-04-22, 23:20 -0700

As of the Friday, April 22 build on the Nightly channel, Firefox builds now have support for window.matchMedia(). This is basically the media queries equivalent to querySelector, matchesSelector, and friends. It is implemented as described in the current cssom-view draft: see the sections on window.matchMedia() and on the MediaQueryList interface (but beware the draft could change from its state as of today).

The window.matchMedia() method takes a media query as a string argument and returns a MediaQueryList object. The simplest way to use this object is just to look at its matches property, for example:

if (window.matchMedia("(min-width: 400px)").matches) {
  // The screen width is 400px or wider.
} else {
  // The screen width is less than 400px.
}

However, the object also allows you to add listeners that get notified when the state changes, so you can do:

function setup_for_width(mql) {
  if (mql.matches) {
    // The screen width is 400px or wider.  Set up or change things
    // appropriately.
  } else {
    // The screen width is less than 400px.  Set up or change things
    // appropriately.
  }
}

var width_mql = window.matchMedia("(min-width: 400px)");
// Add a listener for when the result changes
width_mql.addListener(setup_for_width);
// And share the same code to set things up with our current state.
setup_for_width(width_mql);

There are a few other things you can do (like remove listeners). For now, see the spec for details, though I would not be at all surprised if sheppy writes something better very soon.

If you notice any problems, file bugs in product Core, component Style System.

For details, see the the bug and the code.