Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Window matchMedia() method

Window matchMedia() method

Window Object Reference Window Object


Definition and Usage

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

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

The MediaQueryList object has the following two properties:

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

Method Description
addListener(functionref) Add a new listener function that executes when the media query result changes.
removeListener(functionref) Remove 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

Returns a MediaQueryList object.


Browser support

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

Method
matchMedia() 9.0 10.0 6.0 5.1 12.1

Example

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

*/

}

Try it »

Example

Determine the screen (screen/viewport) window size, changing 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

)

//

The listener function called on execution

x

.

addListener

(

myFunction

)

//

Add a listener when the state changes

Try it »


Window Object Reference Window Object