Window: matchMedia() method
BaselineWidely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
TheWindow
interface'smatchMedia()
methodreturns a newMediaQueryList
object that can then be used to determine ifthedocument
matches themedia query string,as well as to monitor the document to detect when it matches (or stops matching) thatmedia query.
Syntax
matchMedia(mediaQueryString)
Parameters
mediaQueryString
A string specifying the media query to parse into a
MediaQueryList
.Just like in CSS, anymedia feature must be wrapped in parentheses inside the expression. For example:
matchMedia("(width <= 600px)")
ormatchMedia("(orientation: landscape)")
work, whereasmatchMedia("width < 600px")
ormatchMedia("orientation: landscape")
do not. Keywords for media types (all
,print
,screen
) and logical operators (and
,or
,not
,only
) do not need to be wrapped in parentheses.
Return value
A newMediaQueryList
object for the media query. Use this object'sproperties and events to detect matches and to monitor for changes to those matches overtime.
Usage notes
You can use the returned media query to perform both instantaneous and event-drivenchecks to see if the document matches the media query.
To perform a one-time, instantaneous check to see if the document matches the mediaquery, look at the value of thematches
property, which will betrue
if the document meets the media query'srequirements.
If you need to be kept aware of whether or not the document matches the media query atall times, you can instead watch for thechange
event to be delivered to the object.There'sa good example of thisin the article onWindow.devicePixelRatio
.
Examples
This example runs the media query(width <= 600px)
and displays thevalue of the resultingMediaQueryList
'smatches
property in a<span>
; as a result, the output will say "true" if the viewport is lessthan or equal to 600 pixels wide, and will say "false" if the window is wider than that.
JavaScript
let mql = window.matchMedia("(width <= 600px)");document.querySelector(".mq-value").innerText = mql.matches;
The JavaScript code passes the media query to match intomatchMedia()
to compile it, then sets the<span>
'sinnerText
to the value of the results'matches
property, so that it indicates whether or not the document matches the media query at the moment the page was loaded.
HTML
<span></span>
A simple<span>
to receive the output.
.mq-value { font: 18px arial, sans-serif; font-weight: bold; color: #88f; padding: 0.4em; border: 1px solid #dde;}
Result
SeeTesting media queries programmatically for additional code examples.
Specifications
Specification |
---|
CSSOM View Module # dom-window-matchmedia |