Javascript examples for Browser Object Model:Window matchMedia
The window.matchMedia() method returns a MediaQueryList object representing the results of the specified CSS media query string.
The MediaQueryList object has two properties and two methods:
Property | Description |
---|---|
matches | check the results of a query. Returns true if the document matches the media query |
media | A String, representing the serialized media query list |
Method | Description |
---|---|
addListener(functionref) | Adds a new listener function, which is executed whenever the media query's evaluated result changes |
removeListener(functionref) | Removes a previously added listener function from the media query list. |
Parameter | Description |
---|---|
mediaQueryString | Required. A string representing the media query |
A MediaQueryList object representing the results of the specified CSS media query string.
The following code shows how to Find out if the screen/viewport is less than or greater than 700 pixels wide:
<!DOCTYPE html> <html> <body> <script> function myFunction(x) {// w w w .ja va 2 s.c o m if (x.matches) { // If media query matches 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) // Attach listener function on state changes </script> </body> </html>