Easy Tutorial
❮ Met Canvas Createimagedata Jsref Obj Math ❯

Window matchMedia() Method

Window Object


Definition and Usage

The matchMedia() method returns a new MediaQueryList object representing the result of the specified media query string.

The matchMedia() method can be any feature of a CSS @media rule, such as min-height, min-width, orientation, etc.

The MediaQueryList object has the following properties:

The MediaQueryList object can also listen for events. By listening, a specified callback function is called when the query result changes.

Method Description
addListener(functionref) Adds a new listener function that executes when the result of the media query changes.
removeListener(functionref) Removes a previously added listener from the media query list. If the specified listener is not in the list, no action is taken.

Syntax

window.matchMedia(mediaQueryString)

Parameter Description:

Return Value


Browser Support

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

Method Chrome Edge Firefox Safari Opera
matchMedia() 9.0 10.0 6.0 5.1 12.1

Example

Determine the screen (screen/viewport) window size:

if (window.matchMedia("(max-width: 700px)").matches) {
    /* Window is less than or equal to 700 pixels */
} else {
    /* Window is greater than 700 pixels */
}

Example

Determine the screen (screen/viewport) window size and change the background color to yellow when it is less than or equal to 700 pixels, and to pink when it is greater than 700 pixels:

function myFunction(x) {
    if (x.matches) { // Media query
        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) // Add listener on state change

Window Object

❮ Met Canvas Createimagedata Jsref Obj Math ❯