Media Queries in JavaScript

Learn how to conditionally run JavaScript code depending on a media query.

David Mitjana Castro
JavaScript in Plain English

--

We all know CSS media queries, which allow us to apply different styles depending on a @media rule.

But did you know media queries aren’t only restricted to CSS? Sometimes it can be useful to run JavaScript code depending on a media query.

How? With the window API method matchMedia().

The matchMedia() method

In short, it’s a simple and fast way to write media queries in JavaScript. The concept is the same as in CSS: if the condition of the media query is matched, then run some code. We can pass any of the CSS @media rules (screen, orientation, min-width, etc.) as a string argument to the method, which returns a MediaQueryList object with two properties and two methods.

Properties:

  • matches : a boolean which is true if the media query is satisfied or false otherwise. This is the basic usage and more intuitive property that you will be using in most cases, and is very similar to how we write CSS media queries.
  • media: the media query itself.

Methods:

  • addListener() or addEventListener() : adds a callback which is called when the media query changes its state.
  • removeListener() or removeEventListener() : removes the specified callback previously defined in the addListener().

Examples

The following code snippet contains two examples with the properties and methods of the matchMedia() method.

Conclusions

In the second code block it can be argued that it would be more optimal to use the traditional window.addEventListener('resize', callbackFunction) and use window.innerWidth to obtain the current viewport width, but the presented approach using matchMedia() is intended to show how this method lets us detect media query changes in JavaScript, not to provide the best approach to that specific problem.

However, listening to resize events will call the callback function on every viewport resize, which would be less performant than using the matchMedia method that only calls the callback when the specified media query is matched.

In addition to this, using the presented method gives us a much broader spectrum of possibilities since it can not only perform traditional operations like listening to changes of the viewport width, but also detect changes on the well-known media queries.

--

--