Media Query in JavaScript

Shraddha Paghdar Oct 12, 2023
Media Query in JavaScript

Responsive design ensures the content looks good in all screen sizes.

CSS uses a media query to apply various styles based on browser properties, including width, height, or screen resolution.

CSS media queries apply custom styles, which gave rise to ​​responsive design.

Use the window.matchMedia() Method to Define the Conditions of Media Query in JavaScript

Media queries work similarly to CSS if we want to log a message to the console when the browser is 480 pixels wide.

const mediaQuery = window.matchMedia('( min-width: 480px )')

The matchMedia() method returns a new MediaQueryList object, which can then be used to determine if the document matches the media query string.

It Monitors the document and detects when it matches or breaks to match. We can then trigger logging to the console when this condition is met:

if (mediaQuery.matches) {
  console.log('Screen changed and media query matched!')
}

The media query list of the ReadOnly property of the matches interface is a Boolean value that returns true if the document is currently matching the list of media queries or false, if not.

When the match value changes, you can be notified by observing the change event fired in the MediaQueryList.

const mediaQuery = window.matchMedia('(min-width: 480px)');
function handleScreenChange(e) {
  if (e.matches) {
    console.log('Screen changed and media query matched!');
  }
}
mediaQuery.addListener(handleScreenChange);
handleScreenChange(mediaQuery);

Output:

"Screen changed, and media query matched!"

The only drawback of using this code is that this only fires once if the alert is dismissed.

If we change the screen width and try again without refreshing, it won’t fire again. We can use an event listener addListener that checks for updates to avoid this problem.

Shraddha Paghdar avatar Shraddha Paghdar avatar

Shraddha is a JavaScript nerd that utilises it for everything from experimenting to assisting individuals and businesses with day-to-day operations and business growth. She is a writer, chef, and computer programmer. As a senior MEAN/MERN stack developer and project manager with more than 4 years of experience in this sector, she now handles multiple projects. She has been producing technical writing for at least a year and a half. She enjoys coming up with fresh, innovative ideas.

LinkedIn