The window.matchMedia() method returns a MediaQueryList object representing the results of the specified CSS media query string.
The value of the matchMedia() method can be any of the media features of the CSS @media rule, 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 |
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. Does nothing if the specified listener is not already in the list |
window.matchMedia(mediaQueryString)
Parameter | Description |
---|---|
mediaQueryString | Required. A string representing the media query for which to return a new MediaQueryList object |
<button class="btn btn-primary" onclick="myFunction()">CLick it</button> <h2 id="demo"></h2> <script> function myFunction() { 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>
<script> function adjust_window(x) { if (x.matches) { // If media query matches document.body.style.backgroundColor = "green"; } else { document.body.style.backgroundColor = "lightblue"; } } var x = window.matchMedia("(max-width: 700px)") adjust_window(x) // Call listener function at run time x.addListener(adjust_window) // Attach listener function on state changes </script>
<!DOCTYPE html> <html> <head> <title> Window MatchMedia Method In Java Script</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> </head> <body> <div class="container"> <div class="text-center"> <h1>Window MatchMedia Method In Java Script</h1> </div> <br> <div class="well"> <button class="btn btn-primary" onclick="get_alert()">CLick it</button> <h2 id="demo"></h2> <script> function get_alert() { 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> </div> </body> </html>