Window matchMedia() Method
- Previous Page location
- Next Page moveBy()
- Go to Parent Layer Window Object
Definition and Usage
matchMedia()
The method returns a MediaQueryList with the query results.
See also:
Media Query
The media query of the matchMedia() method can be any media feature of the CSS @media rule, such as min-height, min-width, orientation, etc.
Instance
matchMedia("(max-height: 480px)").matches);
matchMedia("(max-width: 640px)").matches);
Instance
Example 1
Is the screen/viewport wider than 700 pixels?
if (window.matchMedia("(max-width: 700px)").matches) { // Viewport width less than or equal to 700 pixels } // Viewport width greater than 700 pixels }
Example Explanation
This example runs the media query and compares it with the current window state.
To run responsive media queries when the window state changes, add an event listener to the MediaQueryList object (see the "More Examples" section below):
Example 2
If the viewport is less than or equal to 500 pixels wide, set the background color to yellow; otherwise, set it to pink:
// Create match function function myFunction(x) { if (x.matches) { document.body.style.backgroundColor = "yellow"; } document.body.style.backgroundColor = "pink"; } } // // Create MediaQueryList object const mmObj = window.matchMedia("(max-width: 700px)"); // Call match function at runtime: myFunction(mmObj); // Add match function as a listener for state changes: mmObj.addListener(myFunction);
syntax
window.matchMedia(mediaQuery)
parameter
parameter | Description |
---|---|
mediaQuery | Required. A string representing the media query. |
Return Value
Type | Description |
---|---|
Object | The MediaQueryList Object with media query results. |
Browser Support
All Browsers Support matchMedia()
:
Chrome | IE | Edge | Firefox | Safari | Opera |
---|---|---|---|---|---|
Chrome | IE | Edge | Firefox | Safari | Opera |
Support | 11 | Support | Support | Support | Support |
- Previous Page location
- Next Page moveBy()
- Go to Parent Layer Window Object