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 consoleUsingmatchMedia()createsaMediaQueryListobject.Here,thatobjectisstoredin
theisWideScreenvariable.EveryMediaQueryListobjectcontainstwoproperties:■ media:returnsthemediaqueryargumentthatwaspassedtomatchMedia()
■ matches:returnstrueiftheconditionismetandfalseotherwiseSincewewanttoknowwhetherit'struethatthebrowserwindowisatleast45em
wide,weneedtoexaminethematchesproperty.ThereareafewcaseswhenMediaQueryList.matchesmightreturnfalse:■ theconditionisn'tmetatthetimematchMedia()isinvoked
■ thesyntaxofthemediaqueryisinvalid
■ thefeaturequeryiswithoutbrowsersupportOtherwise,itsvaluewillbetrue.Here'sanotherexampleofusingmatchMedia.We'llupdatethesourceofavideo
elementbasedonthesizeofthecurrentviewportandresolution:296 CSS Master