Window matchMedia()
Method
Definition and Usage
The matchMedia()
method returns a new MediaQueryList object representing the result of the specified media query string.
The matchMedia()
method can be any feature of a CSS @media rule, such as min-height, min-width, orientation, etc.
The MediaQueryList object has the following properties:
- media: The content of the query statement.
- matches: Used to detect the query result; it is true if the document matches the media query list, otherwise false.
The MediaQueryList object can also listen for events. By listening, a specified callback function is called when the query result changes.
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 action is taken. |
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
Browser Support
The numbers in the table specify the first browser version that supports the method.
Method | Chrome | Edge | Firefox | Safari | Opera |
---|---|---|---|---|---|
matchMedia() | 9.0 | 10.0 | 6.0 | 5.1 | 12.1 |
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 */
}
Example
Determine the screen (screen/viewport) window size and change 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) // Call listener function at run time
x.addListener(myFunction) // Add listener on state change