Click the button to find out if the screen/viewport is less than or greater than 700 pixels wide.
<!DOCTYPE html> <html> <body> <button onclick="myFunction()">Test</button> <p id="demo"></p> <script> function myFunction() {//w w w . java 2 s . c om var x = document.getElementById("demo"); if (window.matchMedia("(max-width: 700px)").matches) { x.innerHTML = "The screen is less than, or equal to, 700 pixels wide."; } else { x.innerHTML = "The screen is at least 700 pixels wide."; } } </script> </body> </html>
The window.matchMedia()
method returns a MediaQueryList object representing the results of the specified CSS media query string.
The parameter of the matchMedia()
method can be any of the media features of the CSS @media rule.
For example, like min-height, min-width, orientation, etc.
The MediaQueryList object has two properties and two methods:
Property | Description |
---|---|
matches | Used to check the results of a query. Returns a boolean value: true if the document matches the media query list, otherwise false |
media | A String, representing the serialized media query list |
MediaQueryList object methods/event handlers:
Method | Description |
---|---|
addListener(functionref) | Adds a new listener function, executed whenever the media query's evaluated result changes |
removeListener(functionref) Removes a previously added listener function from the media query list.Does nothing if the specified listener is not already in the list |
matchMedia(mediaQueryString);
Parameter Values
Parameter | Description |
---|---|
mediaQueryString Required. A string representing the media query |