The window.matchMedia()
method in JavaScript allows you to check if the current document matches a specified media query. This method returns a MediaQueryList
object that represents the results of the media query. You can use this object to determine whether the current document matches the media query, and you can also register event listeners that will be called whenever the media query’s status changes.
Here is an example of how you can use the window.matchMedia()
method to check if the current document matches a specified media query:
// Check if the current document matches the "screen and (min-width: 600px)" media query
var mediaQuery = window.matchMedia("screen and (min-width: 600px)");
// Check the status of the media query
if (mediaQuery.matches) {
// The document matches the media query
// Do something...
} else {
// The document does not match the media query
// Do something else...
}
You can also use the window.matchMedia()
method to register event listeners that will be called whenever the media query’s status changes. This can be useful if you want to dynamically change the styles or behavior of your web page based on the current viewport size. Here is an example of how you can use the addListener()
method of the MediaQueryList
object to register an event listener for a media query:
// Check if the current document matches the "screen and (min-width: 600px)" media query
var mediaQuery = window.matchMedia("screen and (min-width: 600px)");
// Register an event listener for the media query
mediaQuery.addListener(function(event) {
if (event.matches) {
// The document now matches the media query
// Do something...
} else {
// The document no longer matches the media query
// Do something else...
}
});
It’s important to note that the window.matchMedia()
method is a part of the Window object, which represents the current browser window. This means that you must use it in the context of a web page that is running in a browser window. You cannot use it in a standalone JavaScript file or in a Node.js environment.
Leave a Reply