CSS Master

(Primo) #1
wecanrespondtochangesinourdocument'senvironmentwiththeaddListener()
method.TheaddListener()methodacceptsafunctionasitsargument.This
functionisalsoknownasacallbackfunction.

Let'saddaclassnamewhenourdocumententerslandscapeorientation.Thefirst
stepistocreateaMediaQueryListobjectusingmatchMediaandamediaquery:

var isLandscape = matchMedia("(orientation: landscape)");

Steptwoistodefineourcallbackfunction.OurMediaQueryListobjectwillbe
passedtothiscallbackfunctionatitssoleargument:

var toggleClass = function (mq) {
if (mq.matches) {
document.body.classList.add('widescreen');
} else {
document.body.classList.remove('widescreen');
}
}

Mediaqueryeventsarenotverysmart.They'refiredanytimethevalueofMedi-
aQueryList.matcheschanges,regardlessofwhethertheconditionistrue.This
meanswe'llneedtoexaminethevalueofMediaQueryList.matchesorMediaQueryL-
ist.mediaforourMediaQueryListobject.Inthiscase,ifthevalueofmq.matches
istrue,we'lladdaclassnametoourbodyelement.Otherwise,we'llremoveit.

Finally,let'saddthiseventlistenertoourMediaQueryListobjectwithaddListener:

isLandscape.addListener( toggleClass );

Toremovealistener,useremoveListenerasshown:

isLandscape.removeListener( toggleClass );

InearlyversionsoftheCSSOMViewspecification,addListenerandremoveListen-
erweresupposedtobeseparatemechanisms,removedfromtheDOMeventqueue.
ThishaschangedinLevel4.Eventually,we'llbeabletousethestandardaddEvent-
ListenerandremoveEventListenerDOMmethodstolistenforachangeevent.
Ourexamplesfrombeforecouldthenberewrittenlikeso:

298 CSS Master

Free download pdf