Detecting and reacting to media changes on Javascript

Published: by

On this post I'm going to briefly explain how to detect the user media with javascript and also how to handle media changes (like a screen resize).

In case you are not yet familiar with media and media queries you can check a brief explanation here.

On javascript you can access a matchMedia function available at window level. But before doing that it is important to check whether the user browser supports it or not. Overall the browsers offer support for matchMedia, as you can see on can I use website.

let isMobile = false
if (matchMedia) {
  const mediaQuery = window.matchMedia("(max-width: 1024px)")
  isMobile = mediaQuery.matches
}

The code above would check if the max-width of the user screen is equal or below 1024 pixels and set isMobile to true if so, otherwise would set it to false.

The code above is useful but it is still not able to detect a change on media, if the user is on a bigger screen and resizes it to a smaller size (< 1024px) our current javascript code wouldn't be aware of it, but that can be achieved:

let isMobile = false
if (matchMedia) {
  const mediaQuery = window.matchMedia("(max-width: 1024px)")
  isMobile = mediaQuery.matches
  mediaQuery.addEventListener(screenWidthChanged)
}

function screenWidthChanged(mediaQuery) {
  if (mediaQuery.matches) {
    // Code for a screen smaller than 1024px
  } else {
    // Code for a screen bigger than 1024px
  }
}

Now our improved code is capable of detecting the inital screen size when it gets called and also react to a screen resize triggered by the user.