English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Window matchMedia() Method

JavaScript Window Object

matchMedia()The method returns a new MediaQueryList object representing the parsed result of the specified media query string.

The value of the matchMedia() method can beCSS @media ruleAny media feature, such as min-height, min-width, orientation, etc.

Syntax:

window.matchMedia(mediaQueryString)
if (window.matchMedia("(min-width: 500px)").matches) {
   /* Viewport minimum is500 pixels wide */
}
   /* Viewport width less than500 pixels */
}
Test and See‹/›

Browser Compatibility

The numbers in the table specify the first browser version that fully supports the matchMedia() method:

Method
matchMedia()9612.15.110

Parameter Value

ParameterDescription
mediaQueryStringA string representing the media query for which a new MediaQueryList object is to be returned

Technical Details

Return Value:A MediaQueryList object representing the result of the specified CSS media query string

More Examples

If the viewport width is less than or equal to600 pixels, the background color will be coral. If greater than600, it will turn light green:

var size = window.matchMedia("(max-width: 600px)")
myFunc(size) // Call listener function at runtime
size.addListener(myFunc) // Attach listener function when the state changes
function myFunc(size) {
  if (size.matches) {
 document.body.style.backgroundColor = "coral";
  }
 document.body.style.backgroundColor = "lightgreen";
  }
}
Test and See‹/›

Related References

CSS Tutorial:CSS Media Queries

JavaScript Window Object