ThematchMedia()methodisapropertyofthewindowobject.Thatmeanswecan
refertoitusingwindow.matchMedia()orjustmatchMedia().Theformerisclearer,
sinceitindicatesthatthisisanativeJavaScriptmethod,butthelattersavesafew
keystrokes.I'malazytypist,soI'llusematchMedia()intheexamplesthatfollow.
WithmatchMedia(),wecantestwhetheraparticularmediaconditionismet.It
acceptsasingleargument,andthatargumentmustbeavalidmediaquery.
WhymightweuseamediaquerywithJavaScript,ratherthanCSS?Perhapsyou'd
liketodisplayasetofimagesinagridonlargerscreens,buttriggeraslideshow
onsmallscreens.Maybeyouwanttoswapthesrcvalueofavideoelementbased
onthescreensizeorresolution.ThesearecasesforusingmatchMedia().
Here'sasimpleexampleofmatchMediainaction.Thiscodecheckswhetherthe
viewportwidthisgreaterthanorequalto45em:
var isWideScreen = matchMedia("(min-width: 45em)");
console.log(isWideScreen.matches); // Logs true or false to console
UsingmatchMedia()createsaMediaQueryListobject.Here,thatobjectisstoredin
theisWideScreenvariable.EveryMediaQueryListobjectcontainstwoproperties:
■ media:returnsthemediaqueryargumentthatwaspassedtomatchMedia()
■ matches:returnstrueiftheconditionismetandfalseotherwise
Sincewewanttoknowwhetherit'struethatthebrowserwindowisatleast45em
wide,weneedtoexaminethematchesproperty.
ThereareafewcaseswhenMediaQueryList.matchesmightreturnfalse:
■ theconditionisn'tmetatthetimematchMedia()isinvoked
■ thesyntaxofthemediaqueryisinvalid
■ thefeaturequeryiswithoutbrowsersupport
Otherwise,itsvaluewillbetrue.
Here'sanotherexampleofusingmatchMedia.We'llupdatethesourceofavideo
elementbasedonthesizeofthecurrentviewportandresolution:
296 CSS Master