How to use Media Queries in JavaScript with matchMedia
Original Source: https://www.sitepoint.com/javascript-media-queries/
When it was first introduced, responsive design was one of the most exciting web layout concepts since CSS replaced tables. The underlying technology uses media queries to determine the viewing device type, width, height, orientation, resolution, aspect ratio, and color depth to serve different stylesheets.
If you thought responsive design was reserved for CSS layouts only, you’ll be pleased to hear media queries can also be used in JavaScript, as this article will explain.
Media Queries in CSS
In the following example, cssbasic.css is served to all devices. But, if it’s a screen with a horizontal width of 500 pixels or greater, csswide.css is also sent:
[code language=”html”]
<link rel="stylesheet" media="all" href="cssbasic.css" />
<link rel="stylesheet" media="(min-width: 500px)" href="csswide.css" />
[/code]
The possibilities are endless and the technique has long been exploited by most websites out there on the Internet. Resizing the width of your browser triggers changes in the layout of the webpage.
With media queries nowadays it’s easy to adapt the design or resize elements in CSS. But what if you need to change the content or functionality? For example, on smaller screens you might want to use a shorter headline, fewer JavaScript libraries, or modify the actions of a widget.
It’s possible to analyze the viewport size in JavaScript but it’s a little messy:
Most browsers support window.innerWidth and window.innerHeight. (IE before version 10 in quirks mode required document.body.clientWidth and document.body.clientHeight.)
window.onresize
All the main browsers support document.documentElement.clientWidth and document.documentElement.clientHeight but it’s inconsistent. Either the window or document dimensions will be returned depending on the browser and mode.
Even if you successfully detect viewport dimension changes, you must calculate factors such as orientation and aspect ratios yourself. There’s no guarantee it’ll match your browser’s assumptions when it applies media query rules in CSS.
The post How to use Media Queries in JavaScript with matchMedia appeared first on SitePoint.
Leave a Reply
Want to join the discussion?Feel free to contribute!