Window matchMedia()Method
Definition and Usage
matchMedia() returns a new MediaQueryList object representing the parsed result of the specified media query string.
The value of the matchMedia() method can be any one of theCSS @media rulesfeatures, such asmin-height, min-width, orientationetc.
The MediaQueryList object has the following two properties:
- media: the content of the query statement.
- matches: used to detect the query result. If the document matches the media query list, the value is true; otherwise, it is false.
MediaQueryListThe object can also listen for events. By listening, when the query result changes, the specified callback function is called.
| Method | Description |
|---|---|
| addListener(functionref) | Adds a new listener function that executes when the result of the media query changes. |
| removeListener(functionref) | Removes a previously added listener from the media query list. If the specified listener is not in the list, no operation is performed. |
Syntax
window.matchMedia(mediaQueryString)
Parameter description:
- mediaQueryString: Required. A string representing the media query for which a new MediaQueryList object will be returned.
Return Value
Returns a MediaQueryList object.Browser Support
The numbers in the table indicate the first browser version that supports the method.
| Method | |||||
|---|---|---|---|---|---|
| matchMedia() | 9.0 | 10.0 | 6.0 | 5.1 | 12.1 |
Examples
Examples
Determine the screen (screen/viewport) window size:
Try it Yourself »
Examples
Determine the screen (screen/viewport) window size. When it is less than or equal to 700 pixels, change the background color to yellow; when it is greater than 700 pixels, change the background color to pink:
Try it Yourself »
Other Extensions
Window Object