HTML & CSS
Article
By Craig Buckler

How to use Media Queries in JavaScript

By Craig Buckler

Media Queries for Responsive Web Design in JavaScript

This is the updated version of an article originally published on 12th October, 2011. Changes include: updated info, featured image, CodePen demo.

Responsive design is 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.

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:

<link rel="stylesheet" media="all" href="cssbasic.css" />
<link rel="stylesheet" media="(min-width: 500px)" href="csswide.css" />

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
  • But IE6, 7, 8 and 9 in quirks mode require 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.

--ADVERTISEMENT--

How to Write Media Queries with JavaScript Code

Fortunately, it’s now possible to respond to CSS3 media query state changes within JavaScript. The key API is window.matchMedia. This is passed a media query string identical to those used in CSS media queries:

const mq = window.matchMedia( "(min-width: 500px)" );

The matches property returns true or false depending on the query result, e.g.

if (mq.matches) {
  // window width is at least 500px
} else {
  // window width is less than 500px
}

You can also add an event listener which fires when a change is detected:

// media query event handler
if (matchMedia) {
  const mq = window.matchMedia("(min-width: 500px)");
  mq.addListener(WidthChange);
  WidthChange(mq);
}

// media query change
function WidthChange(mq) {
  if (mq.matches) {
    // window width is at least 500px
  } else {
    // window width is less than 500px
  }

}

You should also call the handler directly after defining the event — this will ensure your code can initialize itself during or after the page has loaded. Without it, WidthChange() would never be called if the user did not change their browser dimensions.

At the time of writing, matchMedia has excellent browser support across the board, therefore, there’s no reason why you could not use it in production.

Check how the text dynamically changes in the demo below from more than 500 pixels to less than 500 pixels as you resize your browser window. Alternatively, download the sample code:

See the Pen CSS Media Queries with JavaScript by SitePoint (@SitePoint) on CodePen.

Are you using CSS3 Media Queries? Can you foresee any uses for the matchMedia object?

The most important and interesting stories in tech. Straight to your inbox, daily. Get Versioning.
Login or Create Account to Comment
Login Create Account