Window matchMedia() method
Definition and Usage
matchMedia() returns a new MediaQueryList object representing the result of parsing the specified media query string.
The value of the matchMedia() method can be any CSS @media rule feature, such as min-height, min-width, orientation , etc.
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 false.
MediaQueryList The object can also listen for events. By listening, the specified callback function is invoked when the query result changes.
| Method | Description |
|---|---|
| addListener(functionref) | Add a new listener function that executes when the media query result changes. |
| removeListener(functionref) | Remove a previously added listener from the media query list. If the specified listener is not in the list, no action is taken. |
Syntax
window.matchMedia(mediaQueryString)
Parameter Description:
- mediaQueryString: Required, a string representing the media query that will return a new MediaQueryList object.
Return Value
Returns a MediaQueryList object.
Browser support
The numbers in the table indicate the first browser version that supports this method.
| Method | |||||
|---|---|---|---|---|---|
| matchMedia() | 9.0 | 10.0 | 6.0 | 5.1 | 12.1 |
Example
Example
Determine the screen (screen/viewport) window size:
if
(
window
.
matchMedia
(
"
(max-width: 700px)
"
)
.
matches
)
{
/*
Window is less than or equal to 700 pixels
*/
}
else
{
/*
Window is greater than 700 pixels
*/
}
Try it »
Example
Determine the screen (screen/viewport) window size, changing the background color to yellow when it is less than or equal to 700 pixels and to pink when it is greater than 700 pixels:
function
myFunction
(
x
)
{
if
(
x
.
matches
)
{
//
Media query
document
.
body
.
style
.
backgroundColor
=
"
yellow
"
;
}
else
{
document
.
body
.
style
.
backgroundColor
=
"
pink
"
;
}
}
var
x
=
window
.
matchMedia
(
"
(max-width: 700px)
"
)
myFunction
(
x
)
//
The listener function called on execution
x
.
addListener
(
myFunction
)
//
Add a listener when the state changes
Try it »
Window Object