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


mql = window.matchMedia(mediaQueryString)

where mediaQueryString is a string representing the media query for which to return a new MediaQueryList object.


This code lets you handle things differently when the window is very narrow.

if (window.matchMedia("(min-width: 400px)").matches) {
  /* The viewport is at least 400 pixels wide */
} else {
  /* The viewport is less than 400 pixels wide */

See Testing media queries programmatically for additional code examples.


Specification Status Comment
CSS Object Model (CSSOM) View Module
The definition of 'Window.matchMedia()' in that specification.
Working Draft Initial definition

Browser compatibility

Update compatibility data on GitHub
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidEdge MobileFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
matchMediaChrome Full support 9Edge Full support 12Firefox Full support 6IE Full support 10Opera Full support 12.1Safari Full support 5.1WebView Android ? Chrome Android ? Edge Mobile Full support YesFirefox Android Full support 6Opera Android Full support 12.1Safari iOS Full support 5Samsung Internet Android ?


Full support  
Full support
Compatibility unknown  
Compatibility unknown

See also