Media Queries in JavaScript
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.
Get The Modern Web now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.