or()methodisdefinedbytheSelectorsAPIspecification.^6 ItacceptsanyCSSse-
lectorasitsargument,andreturnsthefirstitemthatmatches.It’sawaytoselect
elementsthatwillbemanipulatedwithJavaScript.
Next,we’veaddedwhat’sknownasaneventlistenerfortheclickeventusingad-
dEventListener.TheaddEventListenermethodispartoftheDocumentObject
Model.Itallowsustodefineafunctionthatwillbecalledwhenaparticularevent
occurs.Thisfunctionisknownasaneventhandlerorcallbackfunction.Inthis
casewe’relistening—orwaiting—foraclickeventonthebuttonelement.
Themagichappenswithintheclickeventhandler.We’reusingtheclass-
List.toggle()methodtoaddorremovethechangeclassfromthebodyelement
(document.body).WhentheclassListvaluechanges,itwilltriggertheanimation.
TheclassListpropertyisanewerpartoftheDocumentObjectModelAPI.It
providesahandfulofmethodsthatsimplifytheprocessofmanipulatingtheclass
namesofanelement.^7
Ifyou’dratherusejQuery,thesyntaxlookslikethis:
$('button').on('click', function() {
$('body').toggleClass('change');
});
jQueryusesa$()functiontoselectelements.ThisfunctionacceptsaCSSselector
stringasanargument,andreturnsalistofelementsthatmatch.Whenwecalla
methodonthislistofelements,it’sappliedtoeachiteminthelist.Here,it’sthe
onmethod.ItworkssimilarlytoaddEventListener,andalsoacceptstwoarguments.
Thefirstistheeventtolistenforandthesecondisthefunctiontoinvoke.
Withinoureventhandlerfunction,we’veusedthelibrary’stoggleClassmethod
toaddthechangeclasstothebodyelement.AswiththeplainJavaScriptexample,
thisiswhattriggersourtransition.
(^6) http://www.w3.org/TR/selectors-api2/
(^7) TheclassListpropertyisalsoknownasDOMTokenList.It’sdefinedintheDocumentObject
Modelspecification.[http://www.w3.org/TR/dom/]InternetExplorer 9 lackssupportforclassList,
however.IfyoustillneedtosupportIE9,usetheclassNameproperty,orapolyfill.
194 CSS Master