Window matchMedia()

Example 1

Is the screen/viewport greater than 700 pixels wide:

if (window.matchMedia("(max-width: 700px)").matches) {
  // Viewport is less or equal to 700 pixels wide
} else {
  // Viewport is greater than 700 pixels wide
}
Try it Yourself »

Description

The matchMedia() method returns a MediaQueryList with the results from the query.


Media Queries

The media queries of the matchMedia() method can be any of the media features of the CSS @media rule, like min-height, min-width, orientation, etc.

Examples

matchMedia("(max-height: 480px)").matches);
matchMedia("(max-width: 640px)").matches);

Syntax

window.matchMedia(mediaQuery)

Parameters

Parameter Description
mediaQuery Required.
A string representing a media query.

Return Value

Type Description
An objectA MediaQueryList object with the results of the media query.


Examples Explained

The first example on this page runs a media query and compares it to the current window state.

To run responsive media query whenever the window state changes, add an event listener to the MediaQueryList object (See "More Examples" below):


More Examples

If the viewport is less or equal to 500 pixels wide, set background color to yellow, otherwise to pink:

// Create a match Function
function myFunction(x) {
  if (x.matches) {
    document.body.style.backgroundColor = "yellow";
  } else {
    document.body.style.backgroundColor = "pink";
  }
}

// Create a MediaQueryList object
const mmObj = window.matchMedia("(max-width: 500px)")

// Call the match function at run time
myFunction(mmObj);

// Add the match function as a listener for state changes
mmObj.addEventListener("change", function() {
  myFunction(mmObj);
});
Try it Yourself »

Browser Support

matchMedia() is supported in all modern browsers:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes 11


Copyright 1999-2023 by Refsnes Data. All Rights Reserved.