JavaScript and Media Queries

When developing a responsively designed web site, it is likely that you will come across a situation where you will want to selectively execute a JavaScript callback based on a media query comparison. For example, you may want to alter your menu layout for small-screen devices. Or you may wish to load in specific content only on large-screen devices. Luckily, these capabilities are currently available. In this article I will cover a couple methods and show you that this can be done without much trouble at all!

window.matchMedia()

window.matchMedia() is a very convenient, native JavaScript method that allows you to check for a match against a CSS media query condition. As MDN states, it “returns a new MediaQueryList object representing the parsed results of the specified media query string”.

In other words, by simply wrapping a media query in a matchMedia check you are able to execute conditional, view port specific JavaScript code contingent upon wether or not that check returns a match:

[code language=”javascript”]
if (window.matchMedia(“(min-width: 72em)”).matches) {
// Code executed only if view port is >= 72em
} else {
// Code executed if view port is < 72em
}
[/code]

The matchMedia() method is natively supported in Chrome, Firefox 9+, Safari 5.1+, iOS5+ and Android 3+. For browsers that do not support the method, an excellent polyfill created by Paul Irish, Nicholas Zakas and Scott Jehl is available on GitHub.

Enquire.js

Enquire.js is a lightweight JavaScript library that relies on the previously mentioned native window.matchMedia() API. In addition to the functionality provided with the native matchMedia() method, Enquire.js offers some additional capabilities for running media query matches. To list a few:

  • The ability to execute callbacks as media queries are both matched and unmatched, based on browser resize and orientation change events
  • Run one-time setup callbacks
  • Unregister a handler, or group of handlers, to perform any necessary cleanup
  • Support for multiple handlers per media query
  • Chain multiple media queries together to be registered with enquire

Since this library is based on window.matchMedia(), you will also need to utilize the aforementioned polyfill if you want to support older browsers. While I haven’t yet used Enquire.js in a production setting, I still think it would definitely be worth your while to give it a look!

References / Resources

Leave a Reply

Your email address will not be published. Required fields are marked *