THE WORLD'S LARGEST WEB DEVELOPER SITE

Window matchMedia() Method

❮ Window Object

Example

Find out if the screen/viewport is less than or greater than 700 pixels wide:

if (window.matchMedia("(max-width: 700px)").matches) {
    /* The viewport is less than, or equal to, 700 pixels wide */
} else {
    /* The viewport is greater than 700 pixels wide */
}
Try it Yourself »

Definition and Usage

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

The first example on this page only runs the specified CSS media query and compares it to the current window state once. To use window.matchMedia() in a responsive manner, to make your code react to a CSS media query whenever the window state changes, you can use its methods/event handlers (See "More Examples" below):

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

Browser Support

The numbers in the table specify the first browser version that fully supports the method.

Method
matchMedia() 9.0 10.0 6.0 5.1 12.1


Syntax

window.matchMedia(mediaQueryString)

Parameter Values

Parameter Description
mediaQueryString Required. A string representing the media query for which to return a new MediaQueryList object


Technical Details

Return Value: A MediaQueryList object representing the results of the specified CSS media query string.

More Examples

Example

If the viewport is less than, or equal to, 700 pixels wide, change the background color to yellow. If it is greater than 700, change it to pink

function myFunction(x) {
    if (x.matches) { // If media query matches
        document.body.style.backgroundColor = "yellow";
    } else {
        document.body.style.backgroundColor = "pink";
    }
}

var x = window.matchMedia("(min-width: 700px)")
myFunction(x) // Call listener function at run time
x.addListener(myFunction) // Attach listener function on state changes
Try it Yourself »

❮ Window Object