For people building web sites, Responsive Web Design has become a natural approach to making sure the content is available for as many users as possible. This is usually attended to via CSS media queries. However, there is a JavaScript alternative as well.
Introducing window.matchMedia
The way to approach media queries in JavaScript is through window.matchMedia. Basically, you just use the same approach as with CSS, but with a JavaScript call:
var widthQuery = window.matchMedia("(min-width: 600px)"); |
This query returns a MediaQueryList object, on which you can do a few things:
- matches
- Boolean whether the query matched or not.
- media
- Serialized media query list.
- addListener
- Adding event listener to a media query. Much preferred over polling values or similar.
- removeListener
- Removing event listener from a media query.
Therefore, the easy way to determine if a media query matched is using the matches property:
var widthMatch = window.matchMedia("(min-height: 500px)").matches; |
Adding listeners is very easy:
function getOrientationValue (mediaQueryList) {
console.log(mediaQueryList.matches);
}
portraitOrientationCheck = window.matchMedia("(orientation: portrait)");
portraitOrientationCheck.addListener(getOrientationValue); |
Demo and code
I’ve put together a window.matchMedia demo where you can see some queries in action. Try resizing the window and see the values change.
The complete JavaScript code for that demo, which is of course available on GitHub, is as follows:
Web browser support
At this time, window.matchMedia has been implemented in:
- Firefox 6+
- Google Chrome 9+
- Safari 5.1+. Note: doesn’t support
addListener. - Firefox mobile
- Google Chrome beta on Android. Note: doesn’t support
addListener. - Safari 5 on iOS. Note: doesn’t support
addListener. - Android stock browser. Note: doesn’t support
addListener.
It is also planned to be in Internet Explorer 10.
For older/unsupported web browsers, you can try the matchMedia() polyfill, although it doesn’t support addListener.
15 comments
Comments are now closed.
Comments are closed for this article.