The benefit of media queries in CSS is obvious, so you shouldn’t be surprised that they have been adopted into JavaScript as well. This means you can run functions or load in more external scripts depending on device capabilities, leading to sympathetic and improved behavior as well as presentation.
The matchMedia() method is used to run the queries, which are provided in a string as an argument. Try running this in your developer console:
window.matchMedia('screen and (min-width: 800px)');
The result of this code is a MediaQueryList object, and how it appears in your console depends on the browser and tools you use; Figure 3-4 shows the result when I enter this query into Firebug.
What I want from this object is the value of the matches property, which will return true or false depending on the query logic. Using this value, you can easily build an if statement to perform actions depending on the result; in this example, if the viewport is at least 800px wide, the function foo() runs:
var mq = window.matchMedia('screen and (min-width: 800px)');
if (mq.matches) { foo(); }
else { // do something else }
In the file mq-matches.html, you can see a short script I’ve written based on this logic, which simply shows an alert that tells you whether your browser window is at least 800px wide; try resizing your browser window and refreshing the page to see different results.
Taking advantage of JavaScript’s dynamic nature, you can extend this with a listener that fires if the device’s state changes, for example, if the user resizes his or her browser window or changes the orientation of his or her device. I can extend my previous code snippet by adding a new function, widthWatch(), containing the original if-else logic, which is called whenever the viewport changes and fires the listener:
function widthWatch(mq) {
if (mq.matches) { foo(); }
else { // do something else }
}
var mq = window.matchMedia('screen and (min-width: 800px)');
mq.addListener(widthWatch);
widthWatch(mq);
In the example file mq-widthwatch.html, you can see the results of a script based on this; it returns the same results as in the previous example, but you won’t need to refresh the page to get a different result; just resize the window.