This is the 13th day of my participation in the August More Text Challenge

Media queries, first introduced in CSS3, form a core component of responsive Web design. Applications should be tailored to the limitations of each type of device (phone, tablet, laptop, desktop), and media queries provide an easy way to set the viewport size based on the size of the device on which the application is being viewed.

Media queries allow you to vary viewport sizes based on screen size, and can also help you with different style properties for different devices, including setup schemes, font styles, Settings and animations, borders and animations, and almost any other CSS property you might think of.

At first glance, some front-end developers overlook the fact that JavaScript also supports media queries. While not as popular as CSS media queries, JavaScript media queries offer flexibility and many advantages that can make them a better choice for some use cases.

The benefits of JavaScript media queries

The first thing we need to know is what the benefits of using JS media queries are.

JavaScript media queries have two main advantages:

  • Flexibility: You can programmatically incorporate media queries into JavaScript code so that they fire only at the start of a particular event or when certain conditions are met. Using a CSS3-only approach, changes to the media query description take effect for each screen sizing event.

  • Convenience: JavaScript media queries use the same syntax as CSS.

Consider this: If you wanted to dynamically change the properties of different screen sizes, what would you do?

You may be scratching your head, but it would be good to stick to this:

// The function we want to execute depending on the screen size
function foo() {
  if (window.innerWidth < 1024) { 
    /* TODO */}}// Set a listener
window.addEventListener('resize', foo)
Copy the code

In the code block above, we have an if statement based on window.innerWidth (the standard screen size for desktop display) of less than 1024. Presumably, this method should run whenever the application is running on a device smaller than a desktop computer.

Unfortunately, this approach is expensive because it triggers every time the user resizes, not just when the app is opened on their phone or tablet. That’s right – this works whenever the user manually resizes the screen on his desktop computer. Too many of these operations can eventually lead to application latency.

Thankfully, we have the perfect API to handle dynamic situations and responsive design: the matchMedia API.

MatchMedia is supported by almost all browsers, and here is the support given by Can I Use:

If you want to support lower versions of browsers, here’s a Polyfill to help.

How to use JavaScript media query

Instead of attaching a listener to the REsize event as in the example above, we can use the matchMedia API.

The matchMedia() method essentially attaches a listener to a media query, but does not respond to every change in window or screen size, significantly improving performance. If we take this approach, we are only responsible for developing the logic we want to perform for screen adjustments, and don’t have to worry about other conditions, validation, and code optimization.

To use this API, we call window.matchmedia () and pass in a media query string specifying the screen size to respond to.

// This media query targets viewports with a minimum width of 320px
const mQuery = window.matchMedia('(min-width: 320px)')
Copy the code

The matchMedia() method returns a new MediaQueryList object, which we named mQuery in the example above. This object stores information about media queries applied to specific documents, as well as methods that support event-driven and just-in-time matching. This allows us to trigger custom logic when the resizing event starts.

To perform the necessary resizing logic, we need to check window.matches, a Boolean property that returns true if the media query matches and false if it doesn’t. In our example, this property tells us whether there is an actual match to the specified condition (that is, the minimum screen width is 320px).

// Check whether the media query is matched
if (mQuery.matches) { 
  console.log('Media query match! ')}Copy the code

As you can see, it’s very simple to use. For now, there’s just one problem: Window.matches can only perform this check once. To promote responsive Web design, we want to constantly check for any changes that are happening. Thankfully, there’s another tool that works with Windows.matches to help us do this: the addListener() method.

addListener()methods

The matchMedia API provides the addListener() method and the corresponding RemovelListener() method. When addListener() is called, we pass in a callback function that runs when a change in the media query matching state is detected. This callback is the function we want to fire in the resize event:

// This media query targets viewports with a minimum width of 320px
const mQuery = window.matchMedia('(min-width: 320px)')
​
function handleMobilePhoneResize (e) {
  // Check whether the media query is true
  if (e.matches) {
    console.log('Media query match! ')
  }
}
​
mQuery.addListener(handleMobilePhoneResize)
Copy the code

This technique allows us to respond to media query changes and dynamically invoke other methods as needed. These dynamically invoked methods can then change various document properties, such as font styles, borders and spacing, animations, and so on.

For example, to add an animation to 😊, we can do this:

const reduceMotionQuery = matchMedia("(min-width: 320px)");
reduceMotionQuery.addListener(setblushAnimate);

function setblushAnimate() {
  if (reduceMotionQuery.matches) {
    document.body.style.setProperty("--toggle"."0");
    document.body.style.setProperty("--playState"."paused");
  } else {
    document.body.style.setProperty(""."1");
    document.body.style.setProperty("--playState"."running");
  }
}
setblushAnimate();
Copy the code

The effect is as follows:

See the effect

The last

You should now have a basic understanding of media queries in JavaScript and how they enable efficient, adaptive design. The matchMedia API helps you create media queries using JavaScript, and addListener() can build a responsive cross-platform experience by calling callback functions.

Periodically polling for document state changes is an inefficient and resource-intensive approach that ultimately leads to application delays. MatchMedia () allows you to observe specific documents, detect changes in media query criteria, and programmatically change document properties based on media query status.