Download as pdf or txt
Download as pdf or txt
You are on page 1of 137

11/15/2016

JavaScriptforSheridanStudents

2015SamSco,SheridanCollege,BramptonON.
Winter2015Version
Winter2014Version

http://profsamscott.com/javascript/

1/137

11/15/2016

JavaScriptforSheridanStudents

Contents
0.AboutThisBook
1.GengStartedwithJavaScript
2.ThedocumentObjectandtheDOM
3.FunconsandEvents
4.GraphicsontheHTML5Canvas
5.FunconsasValues
6.CustomObjects
7.ProgrammingChallenges
8.ServerIndependentWebApps
9.AdvancedDOMManipulaon
10.AJAX
11.ThejQueryLibrary
12.AJAXwithjQuery

http://profsamscott.com/javascript/

2/137

11/15/2016

JavaScriptforSheridanStudents

0.AboutThisBook
JavaScriptforSheridanStudentsisintendedtobeacompletecourseinJavaScriptprogrammingforweb
applicaondesign.Inthisbook,youwilllearnthebasicsoftheJavaScriptlanguageandhowtoembed
JavaScriptprogramsintoawebpage;youwilllearnhowtocreateclientsidewebapps;youwilllearnhowto
eecvelyusetheextensionsprovidedinthewidelyusedjQuerypackage,includingitsAJAXcapabilies;you
willlearnhowtousethenewHTML5canvastocreatedynamic,graphicalwebcontent;youwilllearnhowto
accessthenewwebstoragecapabiliesofHTML5;andyouwilllearnhowtoimplementobjectorienteddesign
inJavaScript.

0.1WhoShouldReadThisBook?
JavaScriptforSheridanStudentsisaimedatStudentsintheAppliedCompungprogramsatSheridanCollege
[hp://www.sheridancollege.ca],thoughitcouldalsobeusedeecvelybystudentsinothercontextsoreven
byexperiencedprogrammerswhoarenewtoJavaScript.
WhenSheridanstudentsrstencounterJavaScript,they
JavaConnection
havealreadycompletedarstprogrammingcourseinJava
andarstcourseinwebdesign,inwhichtheywereaskedto IfyouareaSheridanstudentorifyouhave
justcompletedanintroductorycoursein
writeHTMLandCSSbyhand(i.e.notusingaWYSIWYG
Java,JavaScriptforSheridanStudentswas
editorlikeDreamWeaver).Thesestudentsalreadyhavea
wrienjustforyou!
goodunderstandingofvariables,datatypes,ifstatements,
loops,methods,HTMLelements(tagsandaributes),and
CSSrules(properesandvalues).Theyhavedesigned
simplewebpagesandwriencomputerprogramsthataresplitupintomulplemethods(possiblyalsomulple
classes)toprocessuserinputandproducenewoutput.
Ifyouttheproleabove,thistextwillleverageyourpriorknowledgeofprogrammingtoskimoverstuyou
alreadyknowandfocusonthedierencesanduniquecapabiliesofJavaScript,jQuery,andHTML5.Itwillalso
leverageyourexisngwebdesignskillstogetyoucreangclientsidewebapplicaonsinJavaScriptmore
quickly.
DoItYourself
LookforDIY(DoItYourself)boxeslikethisthroughoutthistext.Theyareheretogiveyousomethingto
do,tokeepyouengagedandthinking,andtobreakupthemonotonyofreading.Buttheyrenotoponal!
Youshouldreadthemandtrytheacviesbeforemovingon.Thinkofitasanopportunitytoexperiment,
trynewthings,andtestoutwhatyouhavealreadylearned.

0.2WhatIsJavaScript?
http://profsamscott.com/javascript/

3/137

11/15/2016

JavaScriptforSheridanStudents

JavaScriptisafullyfunconalprogramminglanguagethatwasdesignedtobeembeddedinanHTMLpageto
createDynamicHTML(DHTML).ItwasrstshippedwiththenowdefunctNetscapebrowserin1995.DHTML
pagesmakeuseofJavaScriptstatementsandfuncons(similartoJavamethods)tochangetheirappearance
andcontentsbothastheyareloadingandaertheyareloaded.(StacHTMLpages,ontheotherhand,always
lookthesameanddonotchangeoncetheyareloaded.Stacpagesusedtobetheonlythingontheweb,but
theyarenowallbutexnct.)

JavaScriptwasstandardizedasECMAScriptacoupleofyearsaeritsinialrelease.Thename"JavaScript"isa
trademarkoftheOraclecorporaon,butotherimplementaonsoftheECMAScriptalsoexist(notably
MicrososJScriptusedinInternetExplorerandAdobesAconScriptusedinFlash).
AlmostallwebapplicaonsmakeuseofJavaScriptfordrop
downmenus,popupwindows,slideshows,image
Lookfortheseboxesthroughoutthetextto
magniersandotherdynamicelementsthatcanbe
getaquicksummaryofthesimilariesand
implementedontheclientsideoftheclientserver
dierencesbetweenJavaandJavaScript.
architecture.ManywebsitesalsomakeuseofJavaScript
withAJAXtoloadnewcontentfromtheserverandrefresh
partsofthepageaerloadme.ThisishowGoogle
[hp://www.google.com]makessuggesonsasyoutypeintothesearchbar,andhowFacebook
[hp://www.facebook.com]loadsnewcontentwhenyougettotheboomofyouracvityfeed.
JavaConnection

Byatleastonemeasure,JavaScriptmightbethemostfrequentlyusedprogramminglanguage:Ifyoucounted
upallthelinesofJavaScriptinthebrowsercachesofallthecomputersintheworld,thetotalwouldprobablybe
higherthanthenumberoflinesofsourcecodeinanyotherlanguage.

0.2.1PopularMisconceptionsAboutJavaScript
TherearetwowidelyheldmisconceponsaboutJavaScript.TherstisthatJavaandJavaScriptarethesame
language,ortwoversionsofthesamelanguage.Infact,JavaScriptisaverydierentprogramminglanguage
fromJava.ThesimilarityinnamesistheresultofamarkengdecisionmadebyNetscapeinthe1990s.Itstrue
thatthetwolanguagescanlooksimilaratrstglance.LikeJava,JavaScriptderivesmuchofitsbasicsyntaxfrom
theCprogramminglanguage.Butdontbefooledbysurfaceappearances.JavaScriptsvariables,arrays,
objects,andfunconsareimplementedverydierentlyfromtheircounterpartsinJava.
ThesecondmisconceponisthatJavaScriptissomehowalesspowerful,simpler,ormore"lightweight"
languagethanJava.Inthiscase,thereareseveralkernelsoftruth.ItistruethatJavaScriptisdesignedtorunina
restrictedenvironment(e.g.awebpage,aPDFdocument,theWindowsdesktop,etc.).Itisalsotruethat
historically,JavaScripthasbeenusedmostlyforverysimpletasks(e.g.imagerolloversanddropdownmenus).
AnditisalsotruethatJavaScriptrunsmoreslowlythanJava(itsinterpretedratherthancompiled),makingit
lesssuitedtohighperformanceapplicaons.Finally,itisalsotruethatJavaScriptprogrammersdonothaveeasy
accesstothesamekindofstandardpluginlibrariesthatJavaprogrammersenjoy.
ButJavaScriptisnot"lightweight"or"simpler"inthesenseofbeingeasiertolearn.Wringeecvecodein
JavaScriptcanbejustasdicultasanyotherlanguage,andadeepunderstandingofhowthelanguageworksis
asimportanttobeinganeecveJavaScriptprogrammerasitisforaprogrammerinanyotherlanguage.
JavaScriptisalsonot"lesspowerful"inthetheorecalsensethananyotherlanguage.JavaScriptisafully
developed,Turingcomplete,programminglanguage.Thismeansthatthereisnocomputaonalproblemthat
canbesolvedinJavathatcouldnotalsobesolvedinJavaScript.
http://profsamscott.com/javascript/

4/137

11/15/2016

JavaScriptforSheridanStudents

0.2.2TheFutureofJavaScript
WiththewidespreadadoponofHTML5,JavaScriptispoisedtobecomethelanguageofchoiceforwebbased,
hybrid,andpossiblyevenstandalonemobileapps,anditwillsoonreplaceAdobesFlashastheprimarywayto
producegraphicsintensivewebcontentlikegames,interacvediagramsandfancymenusystems.Withthe
developmentofNode.js,JavaScriptcannowalsobeusedtowritecodeontheserversideofawebapp.
AndJavaScriptisnotjustforwebappsanymore.JavaScriptinterpretersarealsoembeddedintotheMicroso
WindowsDesktop,AdobeAcrobat,OpenOce,andanumberofotherenvironmentstoallowprogrammersto
addappsandotherdynamicfunconalitytotheseproducts.
ItmaynotbelongbeforeasolidworkingknowledgeofJavaScriptisarequirementformanyprogrammingjobs.

0.3HowToUseThisBook
JavaScriptforSheridanStudentswasdesignedusingJavaScript,jQueryandCSS3MediaQueriestomakeit
lookgoodandbeusableonatablet,inanarrowdesktopbrowser,andontheprintedpage.Thisistomakeit
easierforyoutotrythingsoutonyourcomputerasyouread.ThebookalsomakesuseoftheHTML5App
Cache,whichmeansaeryouloaditfortherstmethemaintextwillalwaysbeavailable,evenifyourdevice
hasnoInternetconnecon.Bookmarkitonce,downloadtheexamplepackonce,andyouwillalwayshave
everythingyouneed.
SinceitisawebappwrieninHTML5,CSS3andJavaScript,thebookcanalsoserveasatestbedtotryout
JavaScriptstatementsasyoureadalong.
Youwillseelotsoflinksandhighlightedtermsinthebook.InmostcasesthesearelinkstoWikipediaentries,
w3Schoolspagesoronlineexamples.Whenyouprintthebook,thelinksappearinboldface.Ifthelinkpointsto
anythingotherthanWikipedia,w3Schoolsoranonlineexample,theURLwillappearbesideit.

0.3.1W3SchoolsandWikipedia
W3SchoolsisastandardreferencesiteforJavaScript,HTML,CSS,andotherwebtechnologies.Italsohasa"Try
itYourselfEditor"thatletsyoutweakexamplecodetoseetheresultsimmediately.Youshouldgettoknowthis
siteasagoodquickreference.
Wikipediaisacrowdsourcedencyclopedia.Forcomputerrelatedtopics,theentriesareusuallyofacceptable
quality,thankstoaverylargenumberofworkingcomputerscienstsandcomputerprogrammerswhopolice
thecontentandkeepituptodateandaccurate.YoushouldusetheWikipedialinkstobrushuponthe
meaningsoftermsyoumayhaveforgoenandtodigdeeperintotopicsthatinterestyou.
Butasgoodastheseresourcesare,theyhavesomelimitaons.Thetextinw3Schoolsisbriefanddoesnot
alwaysworkwellforstudentswithoutmuchpriorprogrammingexperience,andsomeofthetopicsinWikipedia
canbedicultforanovicetoread.Beginnerstudentsneeddetailedexplanaonsofbigideas,lotsofsignposts
alongtheway,workedexamplesandexercises.Sowewillfocusonthatstuhere.Youareencouragedtomove
backandforthbetweenthistext,w3schools,Wikipediaandothersourcestohelpbuildyourunderstanding.
DoItYourself
Ifyouhaveneverusedw3schoolsbefore,youshouldgettoknowit.Beforemovingon,payw3schoolsa
visitandfollowoneofthetrails(e.g.clickontheHTMLlinkandstartreading).Besuretotryoutsomeof
the"TryItYourself"acvies.
http://profsamscott.com/javascript/

5/137

11/15/2016

JavaScriptforSheridanStudents

0.3.2CriticalThinking
Allsourcesofinformaon(includingtheoneyou'rereadingnow)shouldbetreatedwithcauon.Ithink
w3SchoolsisagreatresourcetogetquickdetailsonHTML,CSSandJavaScript,butitisnotwithoutitscrics
(seethew3fools[hp://www.w3fools.com/]site).Ithasgapsandsomemesit'snotasuptodateasitshould
be.IalsothinkWikipediagenerallyhashighqualityentriesforcomputerrelatedtopics,butitiscrowdsourced
soonanygivendaytheinformaonmightbeinaccurateoroutofdateaswell.
Youshouldalwaysbeawareofthedrawbacksofanyonlinesourceanddevelopstrategiesforcrosschecking
informaonfrommulplesources.Ifyouthinkyouhavefoundanerrorinthistext,pleaseletmeknow
[mailto:sam.sco@sheridancollege.ca]soIcaninvesgate.

http://profsamscott.com/javascript/

6/137

11/15/2016

JavaScriptforSheridanStudents

1.GettingStartedwithJavaScript
BecauseJavaScriptandJavaarebothbasedonCsyntax,and
JavaConnection
becauseyouhavesomeexperienceinJava,youshouldhave
noproblemwithmanyofthenutsandboltsofthelanguage. Syntax.JavaScriptscoresyntaxisvery
similartoJava.Butdontbefooledby
Statements,comments,operators,comparisons,selecon
surfaceappearances.Somedeep
statements(ifandswitch),repeonstatements(for,
dierenceslurkbeneath.
while,do..while)andevencatchingandthrowing
exceponsallworkpreymuchexactlyhowyouwould
expectthemto.JavaScriptstringobjectsandthespecial
MathobjectalsocontainmostofthesamemethodsastheirJavacounterparts(e.g.charAt,Math.random,
etc.)
Thisisgreatnews.YoualreadyknowmostofthesyntaxofJavaScriptandyouhaven'tevendoneanythingyet!
ButbeforeyoucanleverageallthatexisngknowledgeandstartwringJavaScriptprograms,youneedto
understandtwocorefeaturesofJavaScriptthatmakeitverydierentfromJava:itssupportforimperave
programminganditsdynamicallytypedandweaklytypedapproachtovariables,valuesanddatatypes.
DoItYourself
Ifyouhavesomeprogrammingexperience,butnotwithaClikelanguage,orifyouneedtobrushupon
yoursyntax,w3schoolsisagreatplacetogoforarefresher.JustclickontheLearnJavaScriptlinkand
thenchoosethetopicsfromthelistonthele.Evenifyourefeelingcondent,youshouldprobablytake
aquicklookattheseconsonJSStringandJSMathbecausetherearesomeslightdierencesfromthe
JavaStringandMathclasses.

1.1ImperativeProgramming
JavaConnection
Statements.InJava,everystatementmust
bepartofaclassormethod.Thisisnot
trueinJavaScript.

Purelyimperaveprogramsconsistofalistofstatementsin
theordertheyaretobeexecuted.Thesestatementsdonot
needtobepartofaclass,object,method,funconorany
otherstructure.

Inhumanlanguages,imperavesentencesarecommands:
"Dothis.Nowdothat."Imperaveprogramsreadjustlike
thattothecomputer.Therearenopleasantries,youjustgetstraighttotheinstrucons.Thisisquitedierent
fromJava,whereyouhavetodenebothaclassandamainmethodbeforeyoucangettothecommands.

http://profsamscott.com/javascript/

7/137

11/15/2016

JavaScriptforSheridanStudents

1.1.1ImperativeProgramminginaBrowserConsole
TheeasiestwaytoexecuteJavaScriptstatementsisusingtheJavaScriptconsoleofyourfavoritebrowser(a.k.a.
GoogleChrome[hps://www.google.com/intl/en_ca/chrome/browser/]).InChrome,hitF12toopenthe
developertools,thenchoose"Console"fromthetabsthatappearattheboomofthepage.
Theconsolewillappearasanewpanelbeneaththewebpage,likethis.

(Whatsthatyousay?Chromeisntyourfavoritebrowser?Wellyouhavetwoopons.Youcaneithermake
Chromeyournewfavorite,oryoucansearchthroughthemenusonanyanotherbrowserfor"DeveloperTools",
"JavaScriptConsole"orsomethingsimilar.)
DoItYourself
Ifyou'rereadingthisonline,opentheJavaScriptconsolenow(F12inChrome).Ifyou'renotreadingthis
online,openanywebpageinChromeoranotherbrowser,thengotothedeveloperconsole.
NowyourereadytoexecuteyourrstJavaScriptstatement.Attheashingcursorbesidethe>,type:
window.alert("Hello,World!");
andhitenter.Seethepopupmessage?

WhatyouhavejustdoneintheDIYboxaboveisexecuteaJavaScriptfunconnamedalertthatispartofthe
builtinwindowobject.JavaScriptfunconsarealotlikeJavamethodsorCfunconsyoucallthembytyping
theirnamefollowedbyalistofargumentsinsideroundbrackets.Ifafunconbelongstoanobject,youtype
thenameoftheobjectrstfollowedbythe.(dot)operator.
Nomaerwhatbrowseryouareusing,youwillalwayshaveaccesstoawindowobjectcontainingvariablesand
funconspertainingtothecurrentlyacvepanelofthebrowser.Andbecauseyouarealways"inside"the
windowobjectwhenexecungJavaScript,youdontactuallyneedtotypethe"window."part.Sothiswould
haveworked,too:
alert("Hello,World!");

http://profsamscott.com/javascript/

8/137

11/15/2016

JavaScriptforSheridanStudents

JavaConnection
Semicolons.InJavaScript,youusuallydont
needasemicolonattheendofa
statement,butsomemesyoudo.Instead
oftryingtorememberwhichcaseiswhich,
itsbeertoalwaysincludeone.

JavaConnection
StringLiterals.InJava,doublequotesareforStringsandsinglequotesareforchars.JavaScript
doesnthaveachartype,soyoucanuseeithertypeofquotecharacterforastring.Thismeansyou
don'thavetouseescapecharacterstoputquotesinsideastring(e.g.insteadof"\"Murder,\",she
wrote",youcanusesinglequoteslikethis:'"Murder,",shewrote').

DoItYourself
HereareacouplemorewindowfunconstotryinaChromeconsolewindow.
prompt('Whatisyourname?');
confirm("You'reprogramminginJavaScript!");

Notethereturnvaluesofeachfunconthatappearintheconsolewindowwhenyoutrythestatementsinthe
aboveDIYbox.JustlikeJavaandotherlanguages,youcanusethereturnvalueofonefunconasanargument
toanother.
Beforewemoveon,afewmoreusefulps:
1.IfyoueverwanttorepeatacommandintheChromeconsole,youcanalwayshittheuparrowonyour
keyboardtocyclethroughrecentcommands,tweakthem,andtryagain
2.Ifyoueverwanttoenteramulplelinecommand,useshiftenter.
3.IfyouwanttocompleteacommandusingoneofChrome'spopupsuggesons,navigatetoitusingupand
downarrows,thencompletethecommandusingtherightarrow
4.Ifyouwanttocleartheconsolescreen,usectrlL(oryoucanusetheconsole.clear()funcon)
5.Ifyouwanttodetachtheconsoleanduseitinaseparatewindow,pressthewindowsicononthetopright
(besidetheXicon).Ifyouchangeyourmind,pressthesamebuonagaintoreaachit.
DoItYourself
InaChromeconsolewindow,trythesetwoseparatestatementsthatusethereturnvaluesfromthe
promptandconrmfuncons,thenmakeupsomeofyourown.
alert(prompt('Whatdoyouwanttosay?'));
if(confirm('OK?'))alert("You'reOK");elsealert("You'renotOK?");

http://profsamscott.com/javascript/

9/137

11/15/2016

JavaScriptforSheridanStudents

Theprompt,alertandconfirmfunconsarepreystraighorwardandarediscussedundertheheadingJS
PopupAlertonw3Schools.
TheChromeconsoleisagreattoolfortesngoutJavaScriptstatementsandexpressionstogetthesyntaxright
beforeincorporangthemintoawebpage.Itcanalsohelpyouremembermethodnamesbypoppingup
suggesonsasyoutype...
DoItYourself
Type"Math.r"intheChromeconsolewindowandlookatthesuggesonsthatpopup

anditcanevaluateJavaScriptexpressionsforyou.
DoItYourself
TrythefollowinginaChromeconsolewindow.(Makesureyougettheupperandlowercaserightinthese
examplesortheywon'twork.)
5+3*2
5<=3
Math.round(Math.PI*2)
Math.round(Math.PI*2)<Math.PI*Math.PI

1.1.2ImperativeProgramminginanHTML<script>Element
OfcoursetherealpointofJavaScriptistoembedaprogramintoawebpage.YoucanputJavaScriptstatements
anywhereyouwantinanHTMLdocument,aslongastheyareinsidea<script>elementwithatype
aributesetto"text/javascript",asintheexamplebelow.
<scripttype="text/javascript">
alert("Hello,world!");
</script>
Youcanputanynumberof<script>elementsanywhereinsidethe<body>or<head>elementsofanHTML
document.Thebrowserwillreadthepagefromtoptoboomasitloadsit.Whenitgetstoa<script>
element,itwillexecutethecommandsinsidebeforemovingon.Soifthe<script>elementappearsinsidethe
<head>,thepagewillbeblankunlthescripthasnishedexecung.Ifitappearsinthemiddleofthe<body>,
therstpartofthepagewillbedisplayed,thenthe<script>elementwillrun,thentherestofthepagewill
bedisplayed.

1.1.3ANoteonIDEs
YoucanwriteHTML,CSS,andJavaScriptinatexteditorandtestitinabrowser,buttherearemuchmore
programmerfriendlyenvironmentsoutthereforcodecreaon.Irecommendthatyouatleastusea
programmingeditorlikeNotePad++[hp://notepadplusplus.org/].Thisprogramwillusecolortohighlight
keywords,literals,andotherelements,andwillalsodosomesimplebracketmatchingforyou.
BeersllistouseafullydevelopedIntegratedDevelopmentEnvironment(IDE)likeNetBeans
[hps://netbeans.org/]orAptanaStudio[hp://www.aptana.com/](whichisbasedonEclipse
[hps://eclipse.org/]).Forwebprogramming,IlikeNetBeansthebest,especiallynowithassupportforHTML5
projectsandconnectstoChromeusingtheNetBeansConnectorPlugin
[hps://chrome.google.com/webstore/detail/netbeansconnector/hafdlehgocfcodbgjnpecfajgkeejnaa].Just
http://profsamscott.com/javascript/

10/137

11/15/2016

JavaScriptforSheridanStudents

downloadthelatestcopyofNetBeans,thenstartanHTML5Project,rightclickitintheprojectwindowand
createanHTMLdocument.Youllgetastarngtemplate,errorsandwarnings,aswellasshortcutsand
suggesons.YoucanalsocreateCSSandJavaScriptlesthisway,andyoucan"run"thelesinChrometotest
themonceyouhaveinstalledtheNetBeanspluginfromtheChromeWebStore
[hps://chrome.google.com/webstore/category/apps].
DoItYourself
CreateanewHTML5projectinNetBeans[hps://netbeans.org/](oryourfavoriteIDE)andinsidethat
projectcreateanewHTMLpage.YoushouldgetanHTML5templatebutjustincaseyoudon't,youcan
downloadtemplate.htmlfromtheexamplepackandusethatinstead.
Makesureyoucanrunyourtemplate(i.e.displayitinawebbrowser)thenaddthe<script>element
showninthepreviousseconsomewhereinthepageandrefreshittoseewhathappens.
Trymovingthe<script>elementtodierentposionsinthele.Whatdoyounoceaboutthe
behaviorofthepagewhenyoureloaditwiththescriptelementindierentposions?Whathappensif
youhavemulplecopiesofitinthele?Isthereanywhereintheleyoucantputthiselement?

1.1.4DebuggingOutput
Oncewegetpastthisopeningchapter,wewon'tusealertboxesverymuchtotalktotheuser.They'rerather
inelegantandobtrusive.Butyoumightsllwanttohaveawaytocreatedebuggingoutputtoletyouknowwhat
isgoingoninsideyourJavaScriptprograms.Forthis,youcanusetheconsole.logfuncon.It'sabitlike
System.out.println()inJava.Itsendsoutputtothebrowser'sconsolewherenobodybutusdevelopers
willseeit.
DoItYourself
GobacktotheNetBeans[hps://netbeans.org/]projectfromthelastDIYboxandchangethealert
funcontoconsole.log.Refreshthepagetoseethemessageendupinthebrowser'sconsolewindow.

1.2Dynamic(andWeak)Typing
AnotherimportantfeatureofJavaScriptthatsetsitapartfromJavaisthatitsvariablesaredynamicallytyped.
Anotherwaytosaythisisthatvalueshavexeddatatypesbutvariablesdonot.JavaScriptsupportsanumber
ofdatatypesincludingNumber,String,Boolean,ArrayandObject(youcanlooktheseupinw3schools
underJSDataTypes)butyoudonothavetodeclareavariablestypeinordertouseitandyoucanchangethe
typeofavariableastheprogramruns.
UnlikeinJavawhereyouhavetodeclareavariablebyspecifyingitstype,variabledeclaraoninJavaScriptis
donewiththegenerickeywordvar.

http://profsamscott.com/javascript/

11/137

11/15/2016

JavaScriptforSheridanStudents

DoItYourself
TrythestatementsbelowintheJavaScriptconsoleofyourbrowser.
varx=100;
alert(x);
x="I'mastringnow";
alert(x);
x=45.3;
alert(x);
x="$"+x;
alert(x);

(Here'sap:Toresettheconsoleandmakeitforgetallthevariablesyouhavedenedinthissession,justhit
therefreshbuononyourbrowser.)
TheexamplesintheDIYboxaboveshowthatnotonlycanx
changeitstypefromanumbertoastringandbackagain,
thealertfunconcanalsotakeanargumentofanytype.
Otherthanthefactthatvariablesaredynamicallytyped,
theyworkinpreymuchthewayyouareusedtofromJava.

JavaConnection
DataTypes.Javaisstacallytyped,but
JavaScriptisdynamicallytyped.This
seeminglysmalldierencehasripple
eectsthroughouttheenrelanguage.

DoItYourself
Here'salileloopforcounngto10.YoucantryitoutbycreangasimpleHTMLlewitha<script>
element.YoucouldalsotryititinyourJavaScriptconsoleusingshiftentertoseparatethelines,orif
you'reonlinerightnow,justcopyandpasteitintotheconsole.)
for(vari=1;i<=10;i++)
console.log(i);
Heresanotheronetotry.
varn=prompt("Enteranumber");
if(n<1000)
alert("thatwasasmallnumber");
else
alert("thatwasabignumber");
Notethatinthiscasethevariablencontainsastring,butJavaScriptsllallowsthecomparisonto
happen.ThisisbecauseJavaScriptpraccesnotonlydyamicbutalsoweaktyping.Moreonthisinthe
nextsecon.

Actually,youcanoenusevariableswithoutdeclaringthematall,butthisisconsideredverybadprogramming
pracce,forreasonswewilldiscusslater.Alwaysdeclareyourvariables!

http://profsamscott.com/javascript/

12/137

11/15/2016

JavaScriptforSheridanStudents

<exercisessection='1.2'>
1.Writeascriptonawebpagethatpresentstheuserwithanarithmecproblem(e.g.Whatis23
+4?)andasksfortheanswerusingaprompt.Thengivethemfeedbackusinganalertbox.
2.Extendthescriptsothatitgeneratestheintegersforthearithmecproblemrandomly.Keep
presenngthequesonunltheygetitright.Thengivethemasuccessmessageinanalertbox.
3.Extendthescriptsothatitaskstheuseriftheywouldlikeanotherquesonusingaconrmdialog
andgivesthemanotherquesoniftheypress"OK".Iftheypress"Cancel",thepageshouldnish
loadinganddisplayagoodbyemessage.

</exercises>
JavaConnection
RandomNumbers.Math.random()worksthesamewayinbothJavaandJavaScript.Butyoucantcast
toanintegerwith(int)inJavaScript.(Whynot?)YoucanuseparseInt()orMath.floor()instead.
LookuptheJavaScriptMathobjectonw3schoolsformoreinfo.

1.2.1WeakTypingandBooleanExpressions
InBooleanexpressions(i.e.theexpressionsthatevaluateto
trueorfalsetocontrolifstatementsandloops)
JavaScriptusesaggressiveimplicittypecasng(alsoknown
asweaktyping)tocompareanytwovaluesregardlessof
whetherornottheirtypesmatch.Typecasngistheactof
converngonedatatypetoanother.Implicittypecasngis
whenthecompilerorinterpreterdoestheconversion
automacallyforyou.

JavaConnection
ImplicitTypecasng."doublex=45"is
anexampleofimplicittypecasnginJava
(anintvalueisconvertedandthen
assignedtoadoublevariable).JavaScript
alsoperformsimplicittypecasng,but
doesitinmanymorecasesthanJavadoes.
BecauseofthiswesaythatJavaScriptis
weaklytypedwhileJavaisstronglytyped.

DoItYourself
ToseeJavaScriptsaggressiveimplicittypecasnginacon,trythefollowingintheChromeconsole:
varx="hi";
x==45.3
x>=45.3
x=="hi"
Thersttwocomparisonsabovearelegalbutfalse.Thelastoneistrue.

IfaStringcontainsarepresentaonofanumber,itcanbecomparedtointegersandoats

http://profsamscott.com/javascript/

13/137

11/15/2016

JavaScriptforSheridanStudents

DoItYourself
TrythefollowinginaJavaScriptconsole:
vary="50";
x=50;
y==x
Thiscomparisonistrue,eventhoughyisastringandxisanumber

BecauseofJavaScript'sweakapproachtotypes,thereisaspecialBooleanoperator===thatreturnstrueiftwo
valuesareequalandalsoofthesametypethisisknownasbeing"exactlyequal"or"idencal".Similarly,!==
isa"notexactlyequalto"operatorthatrespectsthetypesoftheoperands.SeeJSComparisonOperatorson
w3schoolsformoreinfo.
DoItYourself
TrythestatementsbelowusingthesamexandyvariablesfromthelastDIYbox.Trytopredicttheresult
beforeyouhitenter.
y===x
y==="50"
y!==x
y!=="50"
Explaintoyourselfwhatishappeningineachcase,andwhyeachstatementiseithertrueorfalse.

Becauseoftheconfusionthatimplicittypecasngcancause,itisoenconsideredbestpraccetouse===and
!==wheneverpossibleandtrytoavoidusing==and!=.
JavaConnection
BooleanOperators.JavaScriptaddstwo
newBooleanoperators,===and!==for
"isexactlyequalto"and"isnotexactly
equalto".

JavaConnection
StringComparison.InJavayouwrite
x.equals("hi")tondoutiftheString
xcontainstheword"hi".InJavaScriptyou
justusex==="hi".

1.2.2ExplicitCasting
SomemesyoureallywanttotreataStringvalueasaNumber.Forexample,thepromptfunconalwaysreturns
aString,whichworksneinmostcases,butsupposeweareaskingtheusertoenteranumberandthenwe
wanttoadd1toit.ThecodeintheDIYboxbelowwontdoit.
DoItYourself
Trythisina<script>elementoraChromeconsolewindow.Whatisgoingwrong?
vary=prompt("Enteranumber");
y=y+1;
alert(y);

http://profsamscott.com/javascript/

14/137

11/15/2016

JavaScriptforSheridanStudents

JavaConnection
ExplicitTypecasng.InJavathiscanoen
bedonewithacasngoperator.For
example(int)23.5convertsthedouble
23.5totheint23.Thereisnosuch
mechanisminJavaScript.Insteadyouuse
theparseIntfuncon.

TheexampleintheDIYboxabovedoesntdowhatwewant
becauseyisastring.SoJavaScripttreatsthe+operatoras
concatenaon(muchlikeJava).Inthiscase,weneedtouse
explicittypecasngtoforcethetypewewant.JavaScript
hasbuiltinglobalparseIntandparseFloatfunconsfor
thisverypurpose.

(Unlikealert,promptandconfirmwhichbelongtothe
windowobject,parseIntandparseFloatareglobal
funcons.Theydonotbelongtoanyobjectinthesystem.
Butthisdoesn'tusuallymakeadierenceinpracce.)
DoItYourself
Heresthexforthelastexample.Verifythatitworksandthatyouunderstandwhyitworksbefore
movingon.
vary=prompt("Enteranumber");
y=parseInt(y)+1;
alert(y);

ButwhatifparseIntorparseFloatfail(i.e.theusertypedsomethingthatcantbeinterpretedasa
number)?Inthatcase,theyreturnthespecialvalueNaN(NotaNumber)whichcanbedetectedwiththeglobal
BooleanfunconisNaN.Sotobefullyrobust,youcoulddothefollowing:
DoItYourself
Trythisoutina<script>elementoraJavaScriptconsole.Canyouexplainwhateachlineisdoing?
varn;
do{
n=prompt("Enteranumber");
}while(isNaN(n));
n=parseFloat(n)+1;
alert(n);

JavaScriptalwaystriestodothebestitcantoavoidcrashing.SoparseInt("50.5")willworkandreturn50.
SowillparseInt("50x6")(theparserjuststopsatthexandreturnswhatithassofar).Thiscanbeeithera
blessingoracursedependingonwhattheyouaretryingtodo.

<exercisessection='1.2.2'>
1.Loadwhatswrong.htmllefromtheexamplepack,runittoseewhatitdoes,thenviewthepage
sourceandreadtheinstruconsinthecommentheaderofthele.Explainexactlywheretheerror
orerrorshappen,andxthem.
2.Furtherxthecodefromqueson1sothatitrecoversgracefullywhentheusertypesabad
number.

</exercises>

http://profsamscott.com/javascript/

15/137

11/15/2016

JavaScriptforSheridanStudents

1.2.3DynamicTypingandArrays
Likemostlanguages,JavaScriptcontainssupportforarrays.Inmanycasesthecodeforprocessingarrayswill
lookveryfamiliar.ThingsareonlyslightlydierentinJavaScriptbecauseoftheconsequencesofthelanguage
beingdynamicallytyped.
DoItYourself
AsaJavaprogrammer,yououghttobeableleverageyourunderstandingofJavaarraysandyourgrowing
understandingofJavaScripttodescribetheeectofthisJavaScriptcode:
vara=[3,4,5];
for(vari=0;i<a.length;i++)
a[i]=a[i]*2;
Takeaminutetothinkaboutwhatthiscodedoes,thentypeorpasteitintoabrowserconsolewindowto
runit,andthentypeaandpressentertoexaminethecontentsofthearray.Didyougetitright?

TherstconsequenceofJavaScriptsdynamictypingisthat
youdonthavetodeclareatypeforanarray.Thefollowing
piecesofcodeshowtwodierentwaysofcreangageneric
emptyarray.
vara=[];
vara=newArray();
Youcanalsocreateanarraywithsomeinialcontents,like
this:
varinitializedArray=[43,"hello",2.5,
true];

JavaConnection
ArrayLiterals.InJava,arrayliteralsare
wrienwithcurlybracketsandcanonlybe
usedaspartofacombineddeclaraonand
assignment,likethis:int[]x=
{5,3,2};.Incontrast,JavaScriptarray
literalsarewrienwithsquarebracketsand
canbeusedanywhereyoucouldusean
array.Forexampletheexpression
[10,3,0][1]evaluatesto3.Canyou
gureoutwhy?

Theexpressioninsquarebracketsaboveiscalledanarray
literal.InJavaScript,youcanusearrayliteralsanywhereyoucoulduseanarray.
Nocethatthisarraycontainsvaluesofthreedierenttypes(Number,String,andBoolean).Thisbringsusto
thesecondconsequenceofdynamictyping:youcanmixvaluesofdierenttypesinasinglearray.Infact,you
canevenhavearraysstoredwithinotherarrays.
DoItYourself
Typeorpastethislineintoabrowserconsoleandhitenter.
vara=[6,[5,3,2],"JavaScript"];
Howmanyitemsdoesthearrayahaveinit?Typea.lengthtondout.
Whatdoeseachitemcontain?Typea[0],a[1],andsoontondout.Whatifyoutypea[1][1]?What
doyouexpecttobetheresult?Tryittoseeifyouwereright.

Youneverhavetodeclarethesizeofanarrayinadvancebecauseyoucanarbitrarilyextenditslengthaeryou
createit.

http://profsamscott.com/javascript/

16/137

11/15/2016

JavaScriptforSheridanStudents

DoItYourself
Typeorpastethefollowingintoabrowserconsole.
vara=[];
a[0]=23;
a[1]=45;
Nowtypeaandhitentertoseethecontentsofthearray.Thisisanexampleofextendingthelengthofan
iniallyemptyarray.Typea.lengthtoseethenewlength.

Itisalsopossibletocreateanarraywith"holes"init.
DoItYourself
CompletethepreviousDIYbox,andtheninthesameconsolewindow,typethefollowing:
a[9]=0;
Youjustcreatedanarraywith7"holesin"itfromindices2to8.Howlongisthearraynow?Type
a.lengthtondout,thentypeaandhitentertondoutwhatthecontentsofthearraylookslike.
The"holes"inthearrayhavebeenlledwiththespecialglobalpropertyundefined.
Soifyouareevernotsurewhetheranarrayindexhasbeengivenavalue,youcantestitinanif
statement.Trythis:
if(a[3]===undefined)alert("index3isundefined");

JavaConnection
Arrays.JavaScriptarraysarealotlikeJavaarrays,except:1.Youdontneedtospecifythetypeorsizeof
thearray;2.Youcanmixdatatypesinthesamearray;3.Youcanincreasethesizeofthearrayaerithas
beencreated;and4.Thearrayindicesyoullwithvaluesdonthavetobeconguous.

<exercisessection='1.2.3'>
1.Createapagethatpromptstheuserfor10numbersandthencomputestheaveragevalueofthe
numbersenteredandreportsinanalertboxhowmanyofthevaluestheyenteredwereabove
average.
2.CreateapagewithascriptthatdenesanarrayandputstheStringvalues"Hello","World",
and"!"intorandomarraylocaonsbetween1and10.Thenprompttheuserforthreeintegers
andchecktoseeiftheyhavefoundthearraylocaonswherethethreeStringvaluesarestored.
Givethemascoreoutof3dependingonhowmanytheyfoundandshowthemthevaluesthey
uncoveredusingalertboxes.

</exercises>

http://profsamscott.com/javascript/

17/137

11/15/2016

JavaScriptforSheridanStudents

2.ThedocumentObjectandtheDOM
Aerthepreviouschapter,youshouldbeabletowriteJavaScriptprogramsthatareintegratedwithawebpage,
communicatewiththeuser,andsolveproblems.Congratulaons!Yousllhavealongwaytogo.
Uptothispoint,yourinteraconswiththeuserhaveenrelymadeuseofpopupdialogs.Whilethisstyleof
communicaonissomemesusedinwebapps,mostinputtoaJavaScriptprogramusuallyconsistsofmouse
andkeyboardevents(i.e.movingthemouse,clicking,andtyping)andmostJavaScriptoutputconsistsof
modicaonstothewebpage(e.g.changingcolorsandstyles,revealingandhidingmenus,changingthe
contentsofanelement,loadinganddisplayingnewcontent,etc.).Wellstartwiththeoutputrstinthis
chapter,thenthenextchapterwillshowyouhowtorespondtokeyboardandmouseinput.Bytheendofthese
twochapters,youllhavethetoolsyouneedtowritemuchmoreprofessionalwebapps.

2.1TheDocumentObjectModel
EveryJavaScriptprogramrunninginawebbrowserhasaccesstoadocumentobject.Thisobjectholdsthe
browsersinternalrepresentaonoftheDocumentObjectModel(DOM),andcontainsalltheinformaonthe
browserconstructsusingtheHTMLtagsandaributes,CSSstylerules,images,andothercomponentsthat
makeupthesourcecodeofthepage.UnderstandingtheDOMiskeytobecominganeecveJavaScript
programmer.
Likeanybracketedstructure,anHTMLpagecanbeviewedasahierarchicalfamilytreeofelementscontaining
otherelements.WhenthebrowserreadsanHTMLsourcepageitconstructsanobjectforeachelement,linksit
totheelementsitcontains(the"children")andalsolinksittotheelementthatcontainsit(the"parent").
DoItYourself
Loadhelloworld.htmlfromtheexamplepack,andlookatthepagesource:
<!DOCTYPEhtml>
<html>
<head>
<title>HelloWorld</title>
</head>
<body>
<h1id='message'class='heading'>Hello,World!</h1>
<imgsrc='images/smiley.jpg'alt='smileimage'>
</body>
</html>

Intheexampleabove,thedocumentconsistsofa<!DOCTYPE>elementandan<html>element.The<html>
elementcontainsa<head>anda<body>.The<head>containsa<title>elementandthe<body>contains
http://profsamscott.com/javascript/

18/137

11/15/2016

JavaScriptforSheridanStudents

an<h1>elementandan<img>element.Thissetofrelaonshipscanbedisplayedinatreediagramlikethe
oneshownbelow.

Theitemsintheboxesarereferredtoasnodes.EachnodeisaJavaScriptobjectthathasbeenconstructedby
thebrowsertorepresentthecorrespondingHTMLelement.Eachnodeobjectcontainsinformaonaboutthe
aributes,CSSstyleandcontentsoftheelementitrepresents.
Anodecanhaveoneparentaboveit,anynumberofchildrendirectlybelowit,andanynumberofsiblings
(nodeswiththesameparent).Therootnodeisatthetopandtheleafnodesaretheonesattheboomwithno
children,whichmakesthisacurioussortofupsidedown"tree".WhenyouareusingJavaScriptinawebpage,
thewindowproperty,document,holdstherootnodeofthistree.Likeallproperesandfunconsbelonging
tothewindowobject,youcanaccessdocumentonitsownorbytypingwindow.document.
DoItYourself
Openhelloworld.htmlfromtheexamplepack.HitF12andinsteadoftheConsoletab,gototheElements
tab.ThisisarepresentaonofthebrowsersDOM.
Nowrightclickthe<img>element,select"addaribute",andgivethisimageastylearibute(e.g.
style="width:100px").Youshouldseethechangereectedonthepageimmediately.
Nowcheckthepagesource,andyouwillseethatithasnotchanged.Whynot?
NowgototheConsole,typedocument,andhitenter.ClicktheresponsetoopentheDOMandexploreit.
ThisdocumentobjectgivesyouaccesstothebrowsersDOMfromwithinaJavaScriptprogram.

ThereisalotmoretosayaboutthestructureoftheDOMthanthis,buttheinformaoninthisseconisgood
enoughtogetyoustarted.

http://profsamscott.com/javascript/

19/137

11/15/2016

JavaScriptforSheridanStudents

2.2WhatisaJavaScriptObject?(AnImportantAside)
ThelastseconintroducedthenoonofanObject,sowe
beersayafewwordsaboutthatbeforewemoveon.
JustlikeinJava,aJavaScriptobjectisapackageofvariables
(or"elds"or"properes")andcode(or"methods")stored
togetherunderasinglevariablename.Inyourexperience
withJavayouhaveprobablyusedobjectsbefore,andyou
mayevenhavecreatedyourownobjects.

JavaConnection
Objects.JavaScriptmakesextensiveuseof
Objects,andsupportsthecreaonof
customobjectsandanobjectoriented
styleofprogramming.ButJavaScriptalso
supportsotherprogrammingstyles(e.g.
imperave),andasyouwillseelater,
JavaScriptobjectsaredierentinmany
waysfromtheirJavacounterparts.Butfor
nowyoucantreatJavaScriptobjectsjust
likeJavaobjects.

Forexample,inJavaScripteveryStringobjecthasaeld
namedlengthandamethodnamedcharAt(justlikethe
JavaStringobject).ThecodeintheDIYboxbelowcreates
astringanddisplaysitslengthandrstcharacter.Notethe
useofthevariablename,s,withthedotoperatortoaccess
thevariablesandmethodsthatbelongtotheobjectreferencedbys.
DoItYourself

Trythisinaconsolewindowora<script>elementofawebpage.Predicttheresultofeachlinebefore
yourunit.
vars="JavaScriptisCool.";
alert(s.length);
alert(s.charAt(0));

JavaConnection
CharversusString.UnlikeJava,thereisno
chardatatypeinJavaScript.

Thesecondlineinthecodeaboveaccessesthelengtheld
associatedwiththeobjects.ThethirdlinecallsthecharAt
methodwiththeparameter0togettherstcharacterfrom
theobjects.ThecharAtmethodreturnsastringoflength
1.

OnethingthatisaliledierentaboutJavaScriptisthatyou
canuseeitherdotnotaonorsquarebracketnotaonto
accessanobjectsproperesandmethods.Forexample,
insteadofs.lengthands.charAt,youcanwrite
s["length"]ands["charAt"],asshownintheDIYbox
below.

JavaConnection
ObjectSyntax.Therearetwowaysof
accessinganobjectseldsandmethodsin
JavaScript.LikeJava,youcanwrite
objectName.fieldName.UnlikeJava,
youcanalsowrite
objectName["fieldname"].

Thissquarebracketobjectnotaonlooksandbehaves
exactlylikeadatastructurecalledanassociavearray(or
somemesa"map"ora"diconary").Indeed,thereisreallynodierencebetweenanobjectandanassociave
arrayinJavaScript,sobothstylesofreferencingareincludedfortheconvenienceoftheprogrammer.

http://profsamscott.com/javascript/

20/137

11/15/2016

JavaScriptforSheridanStudents

DoItYourself
Trythisinaconsolewindowora<script>elementofawebpage.
vars="JavaScriptisCool.";
alert(s["length"]);
alert(s["charAt"](0));
Thissquarebracketstyleofaccessinganobjectseldsandmethodsmightseemstrange,butithasits
uses.Forexample,trythefollowing(aertypingthelinesabove).Makesureyoutypesomethinglegallike
"length"whenprompted.
varfieldName=prompt("typeafieldname");
alert(s[fieldName]);

2.3RetrievingandManipulatingaDOMNode
TherearelotsofwaystoaccessanddigthroughtheDOMtreefromwithinaJavaScriptprogram,butbyfarthe
easiestwaytoretrieveanodeisbyusingitsidaribute.Todothis,usethegetElementByIdmethodofthe
documentobjecttoreachintotheDOMandgrabthenodeyouwant(notethelowercasedinthatmethod
name!).Onceyouhaveit,youcanaccessand/orchangethecontentsoftheelement,itsstyleinformaon,or
anyofitsaributes.
Anyelementyouretrieveusingdocument.getElementByIdwillbeanobjectoftypeElement(andalsoof
typeNode).JavaScriptElementobjectscontainanumberofelds,eachcontaininginformaonassociatedwith
thecorrespondingHTMLelement.TheseeldscanbeusedtomakechangestotheDOMlongaerapagehas
beenloaded.
HerearesomeofthemoreusefulElementelds...
innerHTML:

aStringrepresenngthecontentsofthenodeasHTML

style:

theCSSstyleinformaonassociatedwiththenode

className:

theHTMLclassaribute

plus

therewillbeoneeldforeveryaributespeciedinthecorrespondingtagintheoriginal
HTMLsourcecode(e.g.id,src,href,value,type,etc.)

http://profsamscott.com/javascript/

21/137

11/15/2016

JavaScriptforSheridanStudents

DoItYourself
Openhelloworld.htmlexamplefromtheexamplepack,gototheconsoleandtrythefollowing
commands,nongthereturnvaluesineachcase.
vare=document.getElementById("message");
e;
e.innerHTML;
e.style;
e.className;
Nowaddanidaributetothe<img>element,eitherbychangingthesourcecode,orbychangingthe
DOMthroughtheElementsview(seeapreviousDIYbox).
NowuseJavaScriptstatementssimilartotheonesabovetoretrievethesrcandaltaributesofthe
image.

AnalternavetothegetElementByIdmethodisquerySelector.YoucanusequerySelectorwithany
CSSselectoranditwillreturntherstmatchingelement(ornullifnoelementsmatch).
Forexample,document.querySelector("h1")returnstherst<h1>elementintheDOM,
document.querySelector("h1.main")returnstherst<h1>elementwithaclassofmain,andsoon.
Andofcourse,document.querySelector("#myId")isequivalentto
document.getElementById("myID").
DoItYourself
Openthebrowserconsoleforthispage(theoneyou'rereadingnow)andtrythefollowingtogettherst
DIYboxandtherstJavaConneconbox.
document.querySelector("div.DIY")
document.querySelector("div.JC")

ThequerySelectormethodcansomemesbeausefultooltohaveinyourtoolbox,buttokeepthings
simple,IwillconnuetojustusegetElementByIdintheexamplesthatfollow.

2.3.1ChanginganElement'sinnerHTML
AnElement'sinnerHTMLpropertycontainsaStringrepresentaonofthecontentofthecorrespondingDOM
node.Thecontentiseverythingthatappearsbetweentheopeningandclosingtagsthatdenedthatnodein
theoriginalHTMLle.ChangingthisstringisprobablytheeasiestwaytorewritepartoftheDOM.
TheDIYexamplebelowshowsyouhowtochangethetextcontentsofanelement.
(Becarefulwithcasehere.IfyoutypeinnerHtmlinsteadofinnerHTML,thecommandmayfailwithouteven
givingyouanerrormessage!)

http://profsamscott.com/javascript/

22/137

11/15/2016

JavaScriptforSheridanStudents

DoItYourself
LoadinnerHTMLExample1.htmlfromtheexamplepack,andletitdoitsthing.AeryoupressOK,you
willseethetextoftheheadingchange.
Therelevantcodeisshownbelow:
<h1id="heading">ASimpleExample</h1>
<p>Hereissometextinaparagraph.</p>
<scripttype="text/javascript">
alert("PressOKtoseemechangemyownheading.");
document.getElementById("heading").innerHTML="Done";
</script>
Seeifyoucanrewritethiscodesothatinsteadofjustrewringtheheading,italsorewritesthe<p>
element.

YoucanalsoplaceHTMLtagsintotheinnerHTMLeldofanode.Whenyoudothat,thebrowserwillreadthe
tags,createnodeobjectsforthecorrespondingHTMLelements,andaddthemtotheDOM,asdemonstratedin
theDIYboxbelow.IftheinnerHTMLoftheelementyourewritealreadycontainedotherHTMLelements,the
correspondingnodeswillbediscardedfromtheDOMandreplacedwithnewones.
DoItYourself
LoadtheleinnerHTMLExample2.htmlfromtheexamplepackintoabrowser,andletitdoitsthing.
AeryoupressOK,youwillseethedivchangetohavetwonewparagraphsaddedascontents.HitF12
andgotoElementstoverifythattwonewnodeshavebeenaddedtotheDOM.
Therelevantcodeisshownbelow:
<divid='target'>Hereissometextinadiv.</div>
<scripttype='text/javascript'>
alert("PressOKtoseemechangethecontentsofmydiv.");
document.getElementById("target").innerHTML=
"<p>Firstparagraph</p><p>Secondparagraph</p>";
</script>
RewritethecodesothatitaskstheuserforsomeHTMLandtheninsertswhatevertheusertypesintothe
<div>.

HereisadiagramoftherelevantpartoftheDOMbeforeandaerexecungthescriptintheDIYexample
above.

Note:AddingFieldstoObjects
UnlikeJava,JavaScriptallowsyoutocreateaneweldinanyobjectatanymesimplybyassigningsomething
toaneweldname.Thisisveryconvenient,butitalsomeansthatsomeerrorsarehardtocatch.Ifyoumisspell
http://profsamscott.com/javascript/

23/137

11/15/2016

JavaScriptforSheridanStudents

JavaConnection
BadFieldNames.InJava,ifyoumistypean
object'seldname,youwillgetasyntax
erroreveryme.InJavaScriptifyoutryto
readanonexistenteld,youwillgeta
runmeerrorintheconsole.Butifyoutry
toassigntoanonexistenteld,JavaScript
willcreateaneweldforyouwithoutany
errorsorwarnings.ThismakesJavaScript
objectsveryexible,butitalsomakes
someerrorsveryhardtond.

aeldorgetthecasewrongJavaScriptwillmodifythe
objectbyaddinganeweldwithoutwarningyouabout
whathashappened.
Forexampleifyoutypenode.innerHtml="new
content",theinnerHTMLeldofthenodeobjectwillnot
changebecauseyougotthecasewrongonitsname.Butyou
willnotgetanyerrororwarningmessageseithersince
JavaScriptjustaddsanewinnerHtmleldtothenode
object.

<exercisessection='2.3.1'>
1.FromtherstDIYboxabove:ModifythecodeforinnerHTMLExample1.htmlsothatitrewritesthe
<p>elementaswellasthe<h1>element.
2.FromthesecondDIYboxabove:
a.ModifyinnerHTMLExample2.htmlsothatitpromptstheuserforsometext,andthen
changesthecontentsofthe<div>tomatchwhattheytyped.
b.TestyourcodeandtryenteringHTMLatthepromptandinvesgatewhathappenstothe
DOM.
c.Whydoyouhavetocreatethescriptaerthe<div>element?Whathappensifyouplaceit
earlierinthele?
d.Modifythescriptagainsothatitaskstheusertoenteraposiveinteger.Thenalterthe
contentsofthe<div>elementtodisplaytheintegersfrom1uptothenumbertheuser
entered.Eachintegershouldbecontainedinaseparate<p>element.(Notethiswillrequire
somestringprocessingwithaloop.)
3.Getaddion.htmlfromtheexamplepack.Readthecommentheaderinthepagesourceand
followtheinstruconstocompletetheprogram.
4.Createanewpageusingtemplate.htmlfromtheexamplepack(orthedefaultNetBeans
[hps://netbeans.org/]template).Placea<script>elementaerthe<div>toputaJavaScript
program.Thisprogramshouldasktheuserhowmanyparagraphelementstheywant,thenask
themtotypeasentencetouseasthecontentofthoseparagraphs.Thenchangethecontentsof
the<div>elementaccordingtowhattheuserentered.Rightclickthepageandchoose"inspect
element"tomakesurethattheparagraphsgotcreatedcorrectly.

</exercises>

2.3.2ChanginganElement'sstyle
Changinganelement'sCSSinformaoncanbedonemosteasilybyaccessingthestyleeldofthe
correspondingDOMnode.ThisstyleobjectcontainsalltheinlineCSSinformaonfortheNode,whereeach
eldoftheobjectcorrespondstoaCSSproperty.

http://profsamscott.com/javascript/

24/137

11/15/2016

JavaScriptforSheridanStudents

DoItYourself
LoadinnerHTMLExample1.htmlfromtheexamplepack,andpressOKwhenprompted.NowhitF12to
opentheconsoleandtypethefollowing:
vare=document.getElementById("heading");
e.style.color="red";
NowtrychangingotherCSSstylesinthesameway.Addaborder,changethefont,posiontheheader
belowtheparagraph,etc.
NowgototheElementsviewandlookatthe<h1>element.Youwillseestyleinformaoninthe
elementsstylearibute.Notethatthepagesourcedoesnotcontainthisinformaon.

Inaddiontoassigningorchangingstyleinformaon,youcanalsoreadstyleinformaonfromtheeldsofthe
styleobject,butyoucannotreadanyCSSproperesthatweredenedaspartofastylesheetinthisway.
DoItYourself
LoadinnerHTMLExample2.htmlfromtheexamplepack,andpressOKwhenprompted.Notethatthe
<div>elementisredwithaborder.
NowhitF12toopentheconsoleandtypethefollowing:
vare=document.getElementById("target");
e.style.color;
e.style.border;
Whydoesoneoftheabovelinesgiveyouavaluebutnottheother?Viewtheoriginalpagesourceand
seeifyoucangureitout.

Theonlywrinkleinaccessingthestyleobjectaboveisthatyoucangetintoproblemswiththedotnotaonfor
hyphenatedstylepropereslikebackgroundcolor.TheproblemisthattheJavaScriptexpression
e.style.backgroundcolorlookslikewearesubtracngthevariablecolorfromtheeld
e.style.background.Thesoluonimplementedinmostbrowsersistoconverthyphenatedpropertynames
tocamelCasePropertyNames(e.g.borderradiustopleftbecomesborderRadiusTopLeft).
DoItYourself
LoadinnerHTMLExample1.htmlfromtheexamplepack,andpressOKwhenprompted.NowhitF12to
opentheconsoleandtypethefollowing:
vare=document.getElementById("heading");
e.style.backgroundColor="red";
Nowchangesomeotherhyphenatedproperes,likefontsize,borderradius,etc.

Note:UseofSquareBrackets
Don'tforgetthatyoucanaccessanobjects'eldsusingthedotnotaonorassociavearraynotaon(seethe
secononJavaScriptobjectsabove).ManyJavaScriptprogrammerschoosetousethisnotaonforstyle
properes.SointhemostrecentDIYboxabove,insteadofe.style.backgroundColormanyJavaScript
programmerswouldprefere.style["backgroundColor"].It'suptoyouwhichmethodyouusetoaccess
http://profsamscott.com/javascript/

25/137

11/15/2016

JavaScriptforSheridanStudents

thestyleobject'selds(oranyobject'seldsforthatmaer)butyouneedtoknowaboutthetwo
alternavesinordertoreadotherpeople'scodeeecvely.
DoItYourself
GobackandredoalltheotherDIYboxesinthissecon,changingthedotnotaontoassociavearray
notaonforallstyleproperes.Everyexampleshouldbehaveinexactlythesamewayasbefore.

<exercisessection='2.3.2'>
1.Createawebpagewithasingle"helloworld"paragraph.Createascriptonthepageaerthis
elementthatpromptstheuserforacolor,andthensetsthecolorofthe"helloworld"element
accordingtowhattheytyped.Whydoyouhavetocreatethescriptaerthe<p>element?What
happensifyouplaceitearlierinthele?
2.Modifythescriptfromqueson1sothattheusercanspecifyboththestylepropertytochange
andthevalue(notethatyouwillhavetousesquarebracketnotaontoaccessthestyleproperty
theuserchooses).
3.Gobacktotheaddion.htmlexercisefromtheprevioussecon.Changethelesothattheresult
eldchangestoGreeniftheusergetsyourquesonright,otherwiseitshouldbeRed.
4.Modifyaddion.htmlagainsothatiftheuserfailstoenteravalidnumber,the<h1>elementturns
intoasolidredboxwithathickblackborderaroundit.
5.Getthemoveme.htmllefromtheexamplepack.Whenyourunityouwillseeacircle(actuallya
<div>element)insideabox(another<div>element).Bothofthese<div>elementshavetheir
CSSpositionpropertysettoabsolute.Ifyouarenotfamiliarwithhowabsoluteposioning
works,youcanreadaboutitinthecommentsofthemoveme.htmlleorintheW3SchoolsCSS
Posioningpage.
a.Yourrsttaskistoadda<script>elementthatwillrepeatedlyuseaconfirmdialogto
asktheuseriftheywanttomovethebox.IftheyclickOK,movethecircletoarandom
posionwithintheboxandthenaskagain.iftheyclickCANCEL,exittheprogram.
b.Yoursecondtaskistochangetheprogramsoitusesapromptdialogtoasktheuserto
enterU,D,L,RorQ(forup,down,le,rightandquit)andthenmovethecircle20pixelsin
thedesireddirecon.
c.Finally,modifyyoursoluonsothattheusercannotmovethecircleoutofbounds.

</exercises>

2.3.3ChanginganElement'sclassName
Somemesyoumaywanttochangealargenumberofproperty/valuepairsatonce.Inthiscase,agoodopon
mightbetodenestylesfortwodierentclasses,andthenchangetheclassNameeldoftheelement.This
willautomacallyupdatethestyleoftheelementtomatchitsnewclass,eecvelychangingmanystylesat
once.

http://profsamscott.com/javascript/

26/137

11/15/2016

JavaScriptforSheridanStudents

DoItYourself
LoadclassNameChangeExample.htmlfromtheexamplepack.NowhitF12toopentheconsoleandtype
thefollowing:
document.getElementById("maindiv").className="classtwo"
Youshouldseeabigchange.Takealookatthesourcecodeforthisletoseehowthischangehappened.
Canyouuseasinglecommandtochangeitbacktothewayitwasoriginally?

(AdvancedProgrammingNote:Ifyouneedanobjecttohavemulpleclassesassociatedwithit,youcanusethe
classListapiforthatobject.Youwon'tndthisonw3schools,sohere'salinktotheMozillaDeveloper
NetworkClassList[hps://developer.mozilla.org/enUS/docs/Web/API/Element.classList]page.)

<exercisessection='2.3.3'>
1.Gobacktotheaddion.htmlexercisesfromthepreviousseconsandcreateCSSrulesfortwo
classesnamedcorrectandincorrect.Thecorrectclassshouldmakeanelementbig,
centeredinthemiddleofthescreen,withaborderandahappybackgroundcolor.Theincorrect
classshouldmakeanelementsmall,posionedinthelowerright,withsadcolors.Thenmodifythe
scripttochangetheclassoftheresultelementappropriatelydependingonwhethertheusergets
yourquesonrightorwrong.

</exercises>

2.3.4ChangingOtherAttributes
Youcanalsoaccess,changeoraddanyotheraributesofanelementbyaccessingtheeldsforthose
aributes.Forexample,ifyouwanttochangeanimage,youcanmodifyitssrcaributebyaccessingthesrc
eldofthecorrespondingnode.Orifyouwanttochangealink,youcanmodifythehrefaributeofthe
correspondingnode.
DoItYourself
Openthechromeconsoleforthispageandexecutethefollowingcommandtoretrievethenode
correspondingtothisDIYbox:
node=document.getElementById("testDIY");
Nowaddatitlearibute:
node.title="ReadMe!";
NowhoverthemouseoverthisDIYboxtoseetheeectofthisstatement.Thenrightclickandchoose
"InspectElement"toseetheaributeyouaddedtotheDOM.
ThislinkgoestoGoogle.Ithasanidof"testLink".Canyouentercommandsinthebrowserconsoleto
redirectthelinktofacebook[hp://www.facebook.com]instead?

http://profsamscott.com/javascript/

27/137

11/15/2016

JavaScriptforSheridanStudents

<exercisessection='2.3.4'>
1.Getthelemood.htmlfromtheexamplepackandfollowtheinstruconsinthecommentsatthe
top.Herearetheimagelesyouwillneed(rightclickandsavethemtoanappropriatefolder):

</exercises>

2.4RetrievingandManipulatingaListofNodes
Ifyouarecomfortablewithindexedstructuressuchasarrays,youcanuseseveralotherpowerfuldocument
methods,includingquerySelectorAll.ThismethodbehavesjustlikegetElementById,exceptthatinstead
ofpassingitanidaributevalue,youpassitaCSSSelectoranditreturnsaNodeListobject(anarraylike
structure)containingeveryelementthatmatchedtheselector.
DoItYourself
GototheSheridanCollegeWikipediapage,opentheJavaScriptconsoleofyourbrowser,andexecutethe
following:
document.querySelectorAll("p");
YoushouldgetaNodeListobjectreturnedthatcontainsallthe<p>elementsinthedocument.Togeta
parcularone,usesquarebracketslikethis:
document.querySelectorAll("p")[2];
Orlikethis:
varparagraphs=document.querySelectorAll("p");
paragraphs[2];
Nowtrytogetalltheelementswiththeclassname"body":
document.querySelectorAll("p.body");

Thesemethodscanbehandyifyouwanttomakeachangetoabunchofelementsatonce.Onceyouhave
theminaNodeListyoucanusealooptochangethemall.
DoItYourself
Ifyouarereadingonline,opentheJavaScriptconsole.OryoucouldgotoaWikipediapageandopenthe
consolethere.Executethefollowingcode:
vara=document.querySelectorAll("p");
for(vari=0;i<a.length;i++)
a[i].innerHTML="JavaScriptRules!";
Didthecodedowhatyouexpected?CanyougureouthowtoselectalltheDoItYourselfboxesonthis
pageandchangetheirbackgroundcolortored?

http://profsamscott.com/javascript/

28/137

11/15/2016

JavaScriptforSheridanStudents

<exercisessection='2.4'>
1.Gobacktoyoursoluontothemulpleparagraphsexercisefromsecon2.3.1andmodifyitso
thataertheparagraphshavebeencreated,theuserisaskedforaCSSpropertyandavalueintwo
separateprompts,andthenthegivenpropertyandvaluegetsetforalltheparagraphs.For
exampleiftheusertypes"color"attherstpromptand"red"atthesecond,alltheparagraphs
shouldturnred.Repeatthisunltheuserenters"quit"insteadofapropertyname.

Ifyoudon'tyethaveaworkingsoluonthethemulpleparagraphsexercise,youcanget
paragraphs.htmlfromtheexamplepackthenyoucanatleastcompletetheworkinthisqueson
foraxednumberofparagraphs.

</exercises>

http://profsamscott.com/javascript/

29/137

11/15/2016

JavaScriptforSheridanStudents

3.FunctionsandEvents
InthepreviouschapteryoulearnedhowtomanipulatetheDOMtoproducedierentkindsofoutputfroma
JavaScriptprogram.Butyouaresllverylimitedinthekindsofinputyoucangetfromtheuser.Thischapter
willbegintochangethat.

3.1TheBasics
Uptothispoint,youhaveonlybeenusingJavaScriptonyourwebpagesinanimperaveprogrammingstyle,
runningscriptswithina<script>elementasthepageisloading.Thisispreyliming.Usuallyyouwantto
makechangesorinteractwiththeuseraerthedocumentisloaded,notwhileitsloading.Todothis,youneed
todeclarefunconswhilethepageloadsandthenexecutethemlaterinresponsetospecicevents.

3.1.1DeclaringaFunction
JavaScriptfunconsarealotlikethemethods,procedures,
andfunconsfoundinmostotherlanguages.Here'san
exampleofaJavaScriptfuncondeclaraon.
functionhello(){
alert("Hello,world!");
}

JavaConnection
Methods.JavaScriptfunconsarevery
similartoJavamethodsalthough,aswe
shallsee,therearealsosomevery
importantdierences.

Theabovefunconhasnoparametersandnoreturnvalue.
NotethatthesyntaxisalmostidencaltoJavamethoddeclaraonexceptthatyouusethekeyword
function,andyoudonthavetospecifyareturntype.Youalsodontneedtospecifyanaccesslevel(public,
private,etc.)orwhetherthefunconisstacornotnoneofthesethingsapplyinJavaScript.
Funconscanbedenedanywhereonthepage,aslongastheyareinsidea<script>element,butitsgood
praccetodeneyourfunconsina<script>elementatthetopofthedocument,insidethe<head>
element.Itsevenbeerpraccetodeneyourfuncons(andtherestofyourcode)inaseparateleor
mulpleseparateleswitha.jsextension.Thenyoucanloadtheselesusingthesrcaributeofanempty
<script>element,likethis:
<scripttype="text/javascript"src="js/hello.js"></script>
Notethata<script>elementcanbeusedintwowayseitheryoucanputJavaScriptcodebetweenthe
openingandclosingtags,oryoucanleavetheelementemptyanduseasrcaributetoloadJavaScriptcode
fromanexternalle.Butyoucannotdobothinthesame<script>element.Ifyouwanttoloadsomecode
fromaleandputsomedirectlyonthepageyouwillneedtwo<script>elements.

http://profsamscott.com/javascript/

30/137

11/15/2016

JavaScriptforSheridanStudents

3.1.2RespondingtoanEvent
Nomaerwhereyoudeneafuncon,itwontexecuteunlessyoucallit.MostJavaScriptfunconcallsare
triggeredinresponsetobrowserevents.Aneventisanimportantmilestoneinthelifeofapage.Eventsare
triggeredwheneveranelementhasnishedloading,theuserhasresizedthebrowser,anelementhasbeen
clicked,themousehasenteredorlethepage,akeyhasbeenpressedandsoon.
AnyHTMLelementcanbethesourceofanevent.Bydefaultmosteventsareignored,butforanyparcular
eventthatmightoccurtoanyparcularelement,youcangivethebrowserablockofJavaScriptstatementsto
executewhentheeventoccurs.Thesestatementscanincludeacalltothefunconyoudened.
Heresanexample:
<ponclick="alert('Youclickedme!');">ClickMe</p>
JavaConnection
Events.InJavaGUIprogramming,you
denelistenerclasseswhichcontainevent
handlers(i.e.methods).InJavaScript,you
justdenethehandlers(i.e.funcons).

TheHTMLcodeabovecreatesaparagraphelementwiththe
text"ClickMe".Theonclickaributecontainsasingle
JavaScriptstatementthatshouldbeexecutedwhenaclick
eventhappens(i.e.whentheuserclicksontheparagraph).

NotethattheJavaScriptstatementhastobeenclosedin
quotaonmarks,likeanyaributevalue,andthatbecause
ofthis,thealertcommandhastousesinglequotesaround
thetextinordertobesyntaccallycorrect.Alternavely,sinceHTMLandJavaScriptbothtreatdoubleand
singlequotesinterchangeably,youcouldhavewrienthis:
<ponclick='alert("Youclickedme!");'>ClickMe</p>
YoucanputasmanyJavaScriptstatementsasyouwantintotheonclickaribute,aslongastheyreseparated
withsemicolons.Butifyouneedalotofcodethere,youshouldprobablydeneafunconandputacalltoit
intotheonclickaributeinstead.Theexamplebelowexecutesthehellofuncondenedintheprevious
seconwhentheheadingisclicked.
<h1onclick="hello();">ClickMe</h1>
OtherJavaScriptmouseeventsarelistedbelow.
ondblclick:

Triggeredwhenelementisdoubleclicked

onmousedown,
onmouseup:

Triggeredwhenamousebuonispressedorreleasedovertheelement

onmouseover,
onmouseout:

Triggeredwhenmouseismovedinto/outoftheboundingboxofanelement

onmousemove:

Triggeredeverymethemousemoves(evenonepixel)whileitisoverthebounding
boxofanelement.Watchout,thisgeneratesalotofevents!

http://profsamscott.com/javascript/

31/137

11/15/2016

JavaScriptforSheridanStudents

DoItYourself
Loadfuncons1.htmlandfuncons2.htmlfromtheexamplepacktoseetheaboveexamplesinacon.
Thetwopageshavethesamebehaviorbutdierinwherethehellofunconisdened.Onehasitina
<script>tag,whiletheotherhasthefunconloadedfromaseparatele.

<exercisessection='3.1.2'>
1.Editfuncons1.html(orfuncons2.html)andalteritsothatinsteadofpoppingupanalertwhen
theheadingisclicked,theuserisaskedfortheirnameandthenthemessage"Helloname"is
displayedinthe<p>element.Makeitsothateachmeanewnameisentered,anewmessage
appearswithouterasingtheoldone.
2.Trymakingtheelementrespondtoadierentevent,suchasonmouseoverorondblclick.

</exercises>

3.1.3ClickingonButtons
Clickingontextisallverywell,butweshouldreallybeclickingonbuons.Clickingonbuonscanbemore
intuivetousers,andthedefaultstyleofbuons(color,text,size)changesononmouseoversormouseclicks
tomakethemappearmoreacve.
Youcandeneabuonlikethis,wherethevalueaributeholdsthebuontext:
<inputtype="button"value="Pressme">
Tomakeitrespondtoclicks,justaddanonclickaribute,likethis:
<inputtype="button"value="Pressme"onclick="hello();">
DoItYourself
Loadfuncons3.htmlfromtheexamplepacktoseetheaboveexampleinacon.Canyouchangethe
codesothatthebuontextchangeswhenitisclicked?

<exercisessection='3.1.3'>
1.Createawebpagethataskstheuseratrueorfalsequesonandgivethemabuontoclickfor
eachopon.Displayasuccessorfailmessagesomewhereonthepageinresponsetotheirclick.

</exercises>

3.1.4ClickingonText
Anotheropontogivetheuserabeeronclickexperienceistousea<span>elementwiththeCSScursor
propertydened(andalsopossiblysome:hoverstyles).Thiswillstyletheclickablearealikealinkandmakeit
moreobviousthatitcanbeclicked.

http://profsamscott.com/javascript/

32/137

11/15/2016

JavaScriptforSheridanStudents

DoItYourself
Loadfuncons4.htmlfromtheexamplepackandclickwhereitsays"clickme".HereistherelevantHTML
code:
<h1id="heading">
Youcan
<spanclass="clickable"onclick="changeSize()">
clickhere
</span>
ifyouwant.
</h1>
TheclickableclasshasCSSstylerulesthatchangethecursorandaddotherhovereects.
SeetheW3SchoolsCSScursorPropertypageandtheW3SchoolsCSS:hoverSelectorpagesformore
info.

3.2Parameters,GlobalVariablesandReturnValues
JustlikeJavamethods,funconscanhaveparametersand
returnvalues.ButinJavaScript,thereisnoneedtodeclare
anytypesforanything.Heresanexample:
functionfoo(x,y,z){
returnx+y+z;
}
Thefunconabovetakesthreeparametersandreturnsthe
resultof"adding"themtogether.Whatgetsreturned
dependsonthetypeofwhatwaspassedin.

JavaConnection
ParametersandReturnValues.JavaScript
funconscanhaveparametersandreturn
values,justlikeJavamethods.Butbecause
thelanguageisweaklytyped,youdont
havetodeneparameterorreturntypes
aheadofme.Afunconcanalsobe
inconsistentaboutwhattypeitreturnsfor
dierentcalls,orevenwhetheritreturns
somethingornot.

Ifafunconnisheswithoutencouteringareturn
statement,itwillreturnthespecialJavaScriptvalue
undefinedbydefault.
DoItYourself
Openabrowserandgototheconsole.Enterthefoofunconabove(useshienterformulpleline
commandslikethis).Nowtrythefollowingcallstothefunconfoo.
foo(1,2,3)
foo(1,"2",3)
foo(1,2,"3")
Canyouexplainwhythefunconreturnsdierentresultsforeachcall?

3.2.1VariableScope
Variablescopereferstothepartsofaprogramthatcanseeagivenvariable.Ifavariablecanonlybeaccessed
withinagivecodeblock,thevariableislocaltothatcodeblock.Ifitcanbeaccessedanywhereintheprogramit
http://profsamscott.com/javascript/

33/137

11/15/2016

JavaScriptforSheridanStudents

JavaConnection
Scope.Javahasblocklevelscope,meaning
thatanyvariableislocaltothecodeblock
inwhichitwasdeclared.Ifyoudeclarea
variableinawhileloop,thatvariableis
localtothewhileloop.
JavaScripthasglobalandfunconlevel
scope,butnotblocklevelscope.This
meansthatifyoudeclareavariableina
whileloopinsideafuncon,thatvariable
cansllbeaccessedanywherewithinthe
funcon.

isglobal.
Variablesdeclaredinsidefunconsorlistedasparameters
arelocaltothefuncon.Thesevariablesarecreatedwhen
thefunconiscalledanddestroyedwhenitnishes.
Variablesdeclaredoutsideoffunconsarealwaysglobal,
whichmeanstheyareaccessibletoallfunconsonthe
page.
Ifafunconcontainsavariablenamethatisthesameasa
globalvariablename,referencestothatnamewithinthe
funconwillalwaysbetothelocalvariable.

JavaConnection
Hoisng.JavaScriptalsohasastrangeprocesscalledhoisng[hp://www.sitepoint.com/backto
basicsjavascripthoisng/]whichisunlikeanythinginJava.Inanutshell,itdoesn'tmaerwhereinthe
funconyoudeclareavariable,JavaScriptalwaysactsasifthedeclaraonwasatthetop(i.e.it"hoists"
thedeclaraontothetopofthefuncon).Thismeansthatyoucanusealocalvariableevenbefore
you'vedeclaredit.

DoItYourself
Loadfuncons5.htmlfromtheexamplepackintoabrowserandpressthebuonstoseewhattheydo.
Takealookatthecode.ThebuonsarealllinkedtoaJavaScriptfunconintheironclickaribute,but
theyeachpassadierentparametertothefuncon.Thefunconaccessesaglobalvariabletokeeptrack
ofthecurrentcount.

http://profsamscott.com/javascript/

34/137

11/15/2016

JavaScriptforSheridanStudents

DoItYourself
Hereisanexamplefromfuncons5.htmlshowingglobalandlocalvariables.

varcurrent=0;
functionadd(inc){
varnewVal=current+inc;
current=newVal;
alert(current);
}

currentisglobal
incislocal
newVallocal

Loadfuncons5.htmlfromtheexamplepackandpressabuon.Nowopenaconsolewindow(F12)and
typethefollowingexpressionsfollowedbyenter:
current
newVal
inc
Explaintheresultreturnedfromeachexpression.

3.2.2WatchOut!!!
Thereisabiggotchawithvariabledeclaraonwhichwehavebeenabletoignoreunlnow,butit'smeto
pointitout.TheissueconcernsthefactthatyoudontactuallyhavetodeclarevariablesatallinJavaScript.
Variableswillautomacallybedeclaredforyoutherstmeyouassignsomethingtothem.Butitisverybad
praccetonotdeclareavariablebecauseifyoudont,thevariablewillbecreatedwithglobalscope.
DoItYourself
Changethecodeforfuncons5.htmlsothatthetwooccurrencesofthekeywordvarareremoved.Now
loadthepageinabrowserandpressabuon.Thenopenaconsolewindow(F12)andtypethefollowing
expressionsfollowedbyenter(trytopredicttheresultineachcasebeforeyoudo):
current
newVal
inc
ExplainwhytheresultsaredierentfromtheresultsinthelastDIYbox.

Automacvariabledeclaraoncancauseconfusion,nottomenonhardtondbugs(seetheJavaconnecon
boxbelow).Butsomeoftheproblemsgoawayifyoumakeitstandardpraccetoalwaysdeclareallvariables
usingthevarkeyword.

http://profsamscott.com/javascript/

35/137

11/15/2016

JavaScriptforSheridanStudents

JavaConnection
UndeclaredVariables.Javarequiresthateveryvariablemustbedeclaredbeforeitisused.JavaScript,on
theotherhand,willautomacallydeclareanewglobalvariableforyouifyouforgettodeclareityourself.
Becauseofthis,somethingsthatwouldbesyntaxerrorsinJavaarelegalinJavaScript:
intmyvar=0;//Javavariabledeclaration.
myvsr=10;//Errorstopscompilation.
varmyvar=0;//JavaScriptvariabledeclaration
myvsr=10;//Createsnewglobalvariable.Noerror.

Comments.Asshownabove,youcanaddcommentstoJavaScriptinthesamewayasyouwouldinJava
(//...forsinglelinecomments,or/*...*/formullinecomments.)

<exercisessection='3.2.2'>
1.Openmessaging.htmlfromtheexamplepack.Readtheinstruconsinthecommentsthatappear
atthetopofthepagesourceandnishthewebappaccordingtotheseinstrucons.
2.Createapagewithasingle<div>elementwithaxedwidthandheightandaborderaroundit.
Includea<p>elementunderneathitwithanidsoyoucanuseitasoutput.Usethe
onmousemoveeventonthe<div>elementtocountthenumberofmestheeventistriggered
anddisplaythecountinthe<p>element.
3.OpencatchTheRabbit.htmlfromtheexamplepack.Readtheinstruconsinthecommentsthat
appearatthetopofthepagesourceandnishthewebappaccordingtotheseinstrucons.(Note
thatthiswebapphasanaccompanyingimageandCSSlewhichyoumustalsodownloadyoucan
gettotheselesbyclickingontheminthrough"pagesource"onmostbrowsers.)
4.Gobacktothemoveme.htmllefromthesamplepack.Inpreviousexercises,youusedprompt
dialoguestogettheusertomovetheballaroundinresponsetoU,D,LandR.Nowyoushouldadd
buonstothepageforup,down,leandrightandmovetheballinresponse.

</exercises>

3.3Application:DropdownMenus
Youseedropdownmenusallovertheweb,onsitesdesignedforbothdesktopandmobileviewing.Modern
desktopsitesoencontain"megamenus"thatarerichwithstructuredinformaonandlinks,asshownbelow:

http://profsamscott.com/javascript/

36/137

11/15/2016

JavaScriptforSheridanStudents

Thesemegamenussomemespopupwhenyouclickabuonortab,andsomemeswhenyoumouseovera
tab.Toseehowthisisdone,gotoasitewithamenulikethis(e.g.TheBostonGlobe
[hp://www.bostonglobe.com]orCTV[hp://www.ctv.ca]),rightclickthemenuonceitspoppedupand
"inspectelement".You'llndit'sjusta<div>element(orsimilar)posionedcleverly,andthenshownand
hiddenbyaJavaScriptfunconusingeithertheCSSvisibilityordisplayproperty.Somemesthe
JavaScriptfunconalsochangesthestyleofthebuontomatchthedropdownmenustyleandindicatewhich
menuisbeingdisplayed.
DoItYourself
TheledropDownMenu.htmlintheexamplepackshowsanexampleofdropdownmenusinacon,but
onasmallerpagewithsourcecodethatshouldbeeasiertoread.Notethatthe"catchtherabbit"menu
won'tactuallyplaythegameunlessyouincludeaworkingcatchTheRabbit.jsle(thesoluontoa
previousexercise).
Explorethisletoseehowthedesignworks.TakenoteoftheCSSstylingusedonthemenusandbuons
(inparcular,thecursorproperty).

http://profsamscott.com/javascript/

37/137

11/15/2016

JavaScriptforSheridanStudents

<exercisessection='3.3'>
1.ThelesideMenus.htmlintheexamplepackcontainssomestartercode.Whenyouviewthisle
youwillseewhatthepageissupposedtolooklikewhentheuserclicksmenu1.Seeifyoucanadd
JavaScriptandmakeotherchangessothatwhenthepagestarts,themenusarenothighlighted,
butmenu1popsupwhentheuserclicksthebuonandhidesitselfagainwhentheuserclicks
again.NowaddtheothertwomenustosideMenus.html.Thecontentofthesemenusisnot
important.
2.NowtrytogetthemenusinsideMenus.htmltorespondtomousingoverandmousingawayfrom
thebuonsand/ormenus.Thisisactuallyaliletrickiertogetrightthantherstversion.
3.TheledropdownMobileExercise.htmlintheexamplepack(withitscompanionCSSle)contains
somestartercodeforasimplemobilewebsite(viewitinanarrowbrowsertoseewhatitwould
looklikeonaphone).Addcodetothissitesothatwhenitisloaded,theparagraphsandthelistof
linksdonotappearatrst.Whentheuserclicksonaheading,itshouldopenthecorresponding
content.Asabonusseeifyoucangetittoclosetheotherparagraphsbeforeopeningthenewone.

</exercises>

3.4FormsandFunctions
Awebapp,whateverjobitisdesignedtodo,needstobe
abletohaveadialogwiththeuser.Inpreviouschaptersyou
learnedseveralsimplewaysofinteracngwiththeuseron
theclientsideusingJavaScriptpopups,HTMLbuons,and
eventslikeonclick.HTMLformsprovidearichersetof
toolsforgenguserinput.
YouwereintroducedtothebasicHTMLformelementsin
yourpreviouswebdesigncourses,butyoumayneeda
review.Trytheacviesbelow,andifyouneedanyhelp
brushinguponthisstu,readthew3SchoolsHTMLForms
secon.YoumightalsowanttolookattheFormsseconof
thew3schoolsHTMLEventspage.

http://profsamscott.com/javascript/

JavaConnection
GraphicalUserInterface(GUI).HTML
FormsprovideasetofGUIinput
componentssimlartoanyothersystemyou
mayhaveusedinJava.Forexample,many
javax.swinginputcomponents(check
boxes,radiobuons,dropdownlists,text
inputelements,etc.)havecounterpartsin
HTML/JavaScript.AndJavaAndroidapps
useXML,aMarkupLanguagesimilartolike
HTML,toconguretheirGUIinterfaces.

38/137

11/15/2016

JavaScriptforSheridanStudents

<exercisessection='3.4'>
1.CreateanHTMLpagetodisplaythe
"registraonform"shownatright.A
soluonisgiveninbasicForm.htmlfromthe
examplepack.
2.Createasimpleformthat(whenscripted
withJavaScript)wouldallowtheuserto
convertCanadiandollarstoanother
currencyofyourchoice.Trytomakegood
useofthenumbertypeand<output>
elementfromHTML5.
3.Createashoppingcartconrmaonpage,
accordingtothespecicaonsgivenbelow.(Inalaterexercise,youwilladdJavaScriptcodeto
implementthe"recalculate"buon.)
a.Present2itemsalongwiththeirprices,withtextinputelementstoshowthecurrent
quanes.
b.Allowuserstoenterapromoonalcodeinatextinputelement.
c.Allowuserstochoosestandarddelivery($4.99)orexpediteddelivery($19.99)
d.Allowuserstoseparatelyselectgiwrapping($9.99),insurance(10%ofthepurchaseprice
beforetaxanddiscounts),andrewardsmembership(free).
e.Presentthetax(13%)andtotalattheboom.
f.Givethem3buons:reset,recalculate,andsubmit

</exercises>

3.4.1RespondingtoFormEvents
JustlikeanyotherHTMLelement,aformelementcanbeconguredtoexecuteJavaScriptstatementsin
responsetovariousevents.
Hereisaparallistofeventsthatformelementscanrespondto.

http://profsamscott.com/javascript/

39/137

11/15/2016

JavaScriptforSheridanStudents

onclick:

Triggeredwhentheuserclickstheelement

onchange:

Triggeredwhenthevalueoftheelementchanges(e.g.whentheuserpressesenteror
tabsawayfromtheelement)

oninput:

Triggeredoneveryactofinput(e.g.everykeystroke)

onmouseover:

Triggeredwhenthemousepointermovesovertheelement

onmouseout:

Triggeredwhenthemousepointerleavestheelement

onfocus:

Triggeredwhentheuserclicksortabstoanelement.Whenanelementisselected,that
elementissaidtohavefocus.Typicallyonlyformelementsandhyperlinkscanhavethe
focus,andonlyoneelementatamecanhaveit.

onblur:

Triggeredwhentheelementlosesfocus.

Youcanprocessaformelementeventinmuchthesamewayasyouprocessanyotherevent,byincludingsome
JavaScriptcodeintheaributeforthatevent,asshownbelow.
<inputtype="radio"onclick="alert('clicked!');">
TheJavaScriptcodeinboldabovewillbeexecutedwhentheradiobuonisclicked.
Nocethatthestringpassedtothealertfunconiswrienwithsinglequotesinsteadofdoublequotes.Thisis
soitcanbeplacedwithinthedoublequotesrequiredbytheonclickaributewithoutcausingasyntaxerror.
Aside:TheSubmitEvent
Onenaleventyoumayneedtoknowaboutisonsubmit.Thiseventappliesto<form>elements,rather
individual<input>elements,anditistriggeredwheneveraformissubmied.Aformissubmiedeitherwhen
theuserpressesasubmitbuon(ifyouhaveone)orwhentheypressenterinsideatextinputelement.
Iftheform'spurposeistosenddatatoaserver,youcanusethiseventtodosomeJavaScriptprocessingto
makesurethedatatheyenteredisok,thenreturntrueifyouwanttoallowtheusertosubmittheform,or
falseifyouwanttopreventit.
Forclientsidewebapps,youusuallydon'twanttheformtobesubmiedanywhere,whichiswhyyoudon't
specifyanactionaributeonthe<form>element,andwhyyoudon'tusuallyhaveasubmitbuon.Butwith
noactionaribute,iftheformgetssubmiedsomehow,itwilltriggerapagereloadwhichwillresetthepage
andmessuptherunningofyourapp.Topreventthis,youcouldjustnotbotherwiththe<form>tags,oryou
couldaddreturnfalse;totheonsubmitevent:
<formonsubmit="returnfalse;">

3.4.2RetrievingFormElements
Inordertoproperlyrespondtomanyformevents,youneedtobeabletogettheformelementsfromtheDOM.
Youcandothisbyassigninganidaributetoeachoneandusingdocument.getElementById.Thisisthe
bestchoiceifyouhaveelectednottouse<form>tags(seeprevioussecon).Butthedocumentobjectalso
containsaformseldthatletsyouaccessformsandtheirelementsusingtheirnameaributes.Thisisthe
standardmethodofformaccessinJavaScript.
http://profsamscott.com/javascript/

40/137

11/15/2016

JavaScriptforSheridanStudents

DoItYourself
LoadbasicForm.htmlfromtheexamplepackintoChromeandtakealookatthecode.Nocethatthe
<form>elementhasthenameaributesettoform1.TrythefollowingintheChromeJavaScript
console:
document.forms
document.forms["form1"]
document.forms["form1"]["name"]
document.forms["form1"][0]
Makesureyouunderstandtheresultsbeforeyoumoveon.Whatisthedierencebetweentheresultof
therstandsecondexpressions?Whatisthedierencebetweenthethirdandfourthexpressions?
ThethirdandfourthexpressionsabovegetyouaparcularnodefromtheDOM(itsasifyouhadused
getElementById).Soyoucanmanipulateitlikethis:
document.forms["form1"]["name"].style.backgroundColor="red"
Orlikethis
varnode=document.forms["form1"]["name"];
node.style.backgroundColor="red";

JavaConnection
ObjectSyntax.Youcanaccesstheeldsof
aJavaScriptobjectusingdotnotaonjust
likeinJava,butitsoenconsideredbest
praccetouseassociavearraynotaon.

Recallthatwhenyouaccessanobjectselds,youcanuse
eitherthedotoperatororsquarebrackets(i.e.
object.fieldorobject["field"]).Itisconsidered
goodpraccebymanyJavaScriptprogrammerstousethe
squarebracket(associavearray)notaontoaccessnamed
elementsfromtheDOM.Thisisbecausesomemesthe
namescancontaincharactersthatwouldcauseproblems
whenusingthedotoperator.

Sotoaccessanamedinputelementfromanamedform,usethefollowingformula,whereformNameand
elementNamematchthenameaributesoftheformandelementrespecvely:
document.forms["formName"]["elementName"]
Toaccessaninputelementthatisnotpartofaform,justgiveitanidandretrieveitusing
document.getElementById.

http://profsamscott.com/javascript/

41/137

11/15/2016

JavaScriptforSheridanStudents

<exercisessection='3.4.2'>
1.Createasimpleformwith3textinputelements.Usetheonmouseoverandonmouseoutevents
totemporarilychangethebackgroundcolorofeachtextinputelementasthemouseglidesover
them.
2.Createatextinputelementwithalightgraybackground.Whentheuserclicksinthetextinput
elementtoentertext,thebackgroundshouldchangetowhite.Whentheyleavethetextinput
element,itshouldreverttolightgrayagain.
3.Addtoexercise2sothatwhentheuserchangesthetextinputelement,athankyoumessage
appearseitherinadialogboxorsomewhereintheHTMLdocument.
4.Addanight/daybuontobasicForm.html.Whenclickeditshouldtogglebetweentwodierent
colorschemesforthepageonedarkandonelight.Besuretochangeformcolorsaswellas.

</exercises>

3.4.3AccessingFormContents
Tocreateaclientsidewebapplicaon,youneedtobeabletoaccessandprocesstheuserinputthatisstored
intheform.Foralmostallinputelements(textboxes,numbers,dates,etc.)youcanaccessthevaluearibute
tondoutwhatcontenttheuserhasentered.Thisaributealwayscontainsastringrepresenngthedatathe
userentered.
DoItYourself
LoadbasicForm.htmlfromtheexamplepackintoChrome,typesomethingintothepasswordeld,then
openaJavascriptconsoleandtrythis:
document.forms["form1"]["password"].value
Congratulaons,youarenowaccessinguserinput.Youcanalsochangeformcontentslikethis:
document.forms["form1"]["name"].value="TypeHere"

Iftheformelementisoftyperadioorcheckbox,itsalilemorecomplicatedbecausewhatyougetback
fromdocument.forms["formID"]["elementName"]isanarrayofelements.Youhavetospecifytheindex
numberoftheparcularelementinthegroup.Therstradiobuoninthegroupwillbeindex0,then1,etc.
YoucanaccessthecheckedeldtogetaBooleanvalue(trueifthebuonischecked,falseotherwise).

http://profsamscott.com/javascript/

42/137

11/15/2016

JavaScriptforSheridanStudents

DoItYourself
LoadbasicForm.htmlfromtheexamplepackintoChrome.ThentrythisintheJavaScriptconsole:
document.forms["form1"]["interests"]
Youshouldgetanarrayofcheckboxesback.Nowtrythistogetthesecondcheckbox.
document.forms["form1"]["interests"][1]
Finally,trythis:
if(document.forms["form1"]["interests"][0].checked)
alert("Iknewyoulikedgardening!");
Whathappened?Probablynothing.Why?Whatdoyouhavetodotomakethealertboxpopup?

<exercisessection='3.4.3'>
1.ChangebasicForm.htmlsothatwhentheformisrstloaded,thetext"ChooseaUserName"
appearsinthetexteld.Whentheuserclicksinthetexteld,thistextshoulddisappear.When
theyleavethetexteld,iftheyhavetypedsomething,itshouldstay.Iftheyhavenottyped
anything,thetext"ChooseaUserName"shouldbeputbackinthebox.(Notethatthisisagood
exerciseforabeginningJavaScriptprogrammer,butifyoureallywanttoimplementthisbehavior
inatextbox,you'rebeerousingthenewHTML5placeholderaribute.)
2.ChangebasicForm.htmlsothatiftheusertriestouncheckthe"skiing"box,itpopsupa
conrmaondialogthatasks"areyousureyoudontlikeskiing?".IftheuserpressesOK,thebox
shouldstayunchecked.Iftheuserpresses"cancel"toboxshouldremainchecked.Notethatifthe
userunchecksthebox,thenrechecksit,noconrmaondialogshouldappear.
3.ChangebasicForm.htmltoadd"checkall"and"uncheckall"buonstotheinterestssecon.
4.Replacethe"checkall"and"uncheckall"buonsfromthelastexercisewithanew"all"checkbox.
Whenselected,thischeckboxshouldcheckoruncheckalltheotherboxes.Whenallinterestsare
manuallyselected,the"all"checkboxshouldautomacallycheckitself.Ifevenoneinterestis
deselected,the"all"checkboxshouldautomacallyuncheckitself.
5.OneofthemainusesforJavaScriptusedtobevalidangformsbeforetheyweresubmiedtothe
server(i.e.makingsurealleldswerelledin,checkingthatnumericeldscontainednumbers,
etc.)ThesedaysmostofthisvalidaoncanbedonebyusingthenewHTML5inputtypesand
aributes.ButthereissllaroleforJavaScript.Forexample,supposethattheuserof
basicForm.htmlisonlyallowedtocheckupto2interests.WriteaJavaScriptfuncontocheckthis
condionandcallitfromtheonsubmiteventofthe<form>element(onsubmit="return
yourFunction()").Thefunconshouldpopupanerroralertandreturnfalseifmorethan2
interestsarechecked.
6.Nowxtheformsothattheuserisalertedandpreventedfromcheckingmorethan2boxes.

</exercises>

3.4.4FormbasedClientsideWebApps
Whenyouharnessthepowerofforms,youcancreateclientsidewebappswithalmostthesameinput
capabiliesasanydesktopGUIapp.
http://profsamscott.com/javascript/

43/137

11/15/2016

JavaScriptforSheridanStudents

AnexampleofaverysimpleclientsidewebappisshownintheaddionQuiz.htmllefromtheexamplepack.
ThisprogramcontainstwoJavaScriptfuncons.Therstfunconcreatesandpresentsanewquesontothe
userandclearsoutanyoldanswersorfeedback,whilethesecondcheckstheusersanswerandgivesfeedback.
Eachofthesefunconsiscalledbyadierentbuonpress.
Nocetheuseofthe<span>elementswithuniqueids.Theyallowthevaluesforthetwooperandstobeset
inaJavaScriptfunconwithoutrewringtheenreparagraphelementthatcontainsthem.
Nocealsotheuseoftheonloadeventinthe<body>element.Thiseventistriggeredaerthe<body>is
nishedloading,andcallsthefuncontosettherstqueson.

http://profsamscott.com/javascript/

44/137

11/15/2016

JavaScriptforSheridanStudents

<exercisessection='3.4.4'>
1.Getthearithmec.htmllefromtheexamplepack.Thisleistheinterfaceforaverysimple
calculatorwithvefuncons.AddJavaScriptcode(aswellasanynecessaryHTMLtagsor
aributes)sothatwhentheuserpressesthe"DoIt"buon,theselectedarithmecisperformed
andtheresultisplacedinthereadonlytextboxtotherightoftheequalssign.
2.Modifyyoursoluonfromthelastquesonsothatanymetheusechangesanyoftheform
elements,theresultupdates.Youwillneedtousetheonchangeand/oroninputeventsforthis.
Nowthattheanswerisautomacallyrefreshing,youdon'tneedthe"DoIt"buonanymore,so
youcanremoveit.
3.GetthecurrencyconverterfromtheSecon3.4Exercisesworking.Whentheuserclicks"convert"
itshoulddisplayonthepagetheresultoftheconversion(youcanlookuptherateonlineorjust
makesomethingupifyoulike).
4.GettheshoppingcartfromtheSecon3.4Exercisesworking.Whentheuserclicks"reset",they
shouldbewarnedthattheformisabouttoclearandgetachancetostopit.Whentheuserclicks
"recalculate",afunconshouldbecalledthatchecksthequanesoftheproductsandthevarious
oponstheuserhaschosen,thendisplaysthenewtotalpricewithtax.DontforgettouseMath
methodstoroundtotwodecimalplaces.
5.Makeasimpleshoppinglistcreaonapp.It
shouldgivetheuseratextboxandabuonto
press.Whentheypressthebuon,itshould
addthetexttheyenteredtoa<table>
elementsomewhereonthepage.Itshouldbe
anumberedlistwithnumbersadded
automacally.Therstcolumnofthetable
shouldcontainitemnumbersandthesecond
columnshouldcontaintheitemstheuser
entered.Trytomakeitsothattheusercan
alsohitEntertocreateanewlistitem.
6.Nowmakethecurrencyconverterfrom
Exercise3beer:Useeldsets,styling,and
imagestoimprovethelookofthecurrencyconverter;Adddropdownliststoallowtheusertopick
the"from"and"to"currency,thenperformdierentcalculaonsdependingonwhattheychoose;
Maketheconverterrobustsothatiftheuserenteranonnumericvalueitrecoversgracefully,and
makesureitalwaysshowstwodigitsforthecentseld(e.g.itshows"01"insteadof"1").
7.MaketheshoppingcartfromExercise4beer:Useeldsets,labels,imagesand/ordropdown
menustoimprovethelookandfeeloftheshoppingcartconrmaonpage;Addatextareafor
shippinginstrucons;Makeitrobustsothatiftheyenternonnumericvaluesinnumbereldsit
recoversgracefully.

</exercises>

http://profsamscott.com/javascript/

45/137

11/15/2016

JavaScriptforSheridanStudents

4.GraphicsontheHTML5Canvas
HTML5bringswithitanumberofnewJavaScriptAPIsthatgreatlyincreasethecapabiliesofJavaScriptweb
apps.Forexampleitisnowpossibletoaccessauser'slocaon,storedatalocallyandrespondtodraganddrop
events.OneofthemostimportantnewJavaScriptAPIsisthenewdrawingAPIfortheHTML5<canvas>
element.ThisAPIallowsJavaScriptprogrammerstocreateinteracvegraphicsandgamesthatcanexecuteon
anybrowser(funconalitythatpreviouslyrequiredabulkypluginlikeFlash).
Thegoalofthischapteristogiveyoualltherawmaterialsyouwouldneedtoimplementasimple2Dgamesuch
asPong.Thechapterfocusesonthebasics,notthedetails.Forfulldetails,seethew3schoolsCanvas
Reference.

4.1CanvasBasics
Toaccessthe2DdrawingAPI,youneeda<canvas>elementsomewhereonyourHTMLpage.Thiselement
shouldhaveanidaributeaswellasheightandwidthaributestospecifyitssizeinpixels,likethis:
<canvasid='myCanvas'height='500'width='250'></canvas>
Notethat<canvas>isnotanemptyelement.Youdoneedaclosingtag.Thereisnoneedtoincludeany
contentbetweenthetags,thoughsomedevelopersputamessagetherewhichwilldisplayonolderbrowsers,
sayingsomethinglike,"Sorry,yourbrowserdoesnotsupporttheHTML5canvas."
Bydefaultacanvasjustappearsasablankspaceonyourpage.ButifyoustyleitwithCSStogiveitaborderand
backgroundcolor,youwillbeabletoseeit.
Therearetwostepstodrawingona<canvas>element.FirstyouhavetoretrievetheelementfromtheDOM:
varc=document.getElementById("testCanvas");
Onceyouhaveit,youcanchangeitsstyleandaributeslikeanyotherelement.Butifyouwanttodrawonit,
youneedtoretrieveadrawing"context".Thesimplestcontextavailableisthe"2d"context:
varctx=c.getContext("2d");
Theabovelineretrievesaspecial"drawingcontext"objectthatimplementsthe2DdrawingAPIforyourcanvas.

http://profsamscott.com/javascript/

46/137

11/15/2016

JavaScriptforSheridanStudents

DoItYourself
Here'sanexampleHTML5canvas,withawidthof400pixelsandaheightof100pixels.It'sCSSwidth
propertyhasbeensetto100%sothatitwillstretchtottheavailablespace.Italsohasaborderanda
backgroundcolorofwhitespeciedinCSS,andithasanidof"testCanvas"sowecaneasilyretrieveit
fromaJavaScriptprogram.

IntheJavaScriptconsoleofyourbrowser,trythefollowingcommands:
varc=document.getElementById("testCanvas");
varctx=c.getContext("2d");
ctx.fillStyle="red";
ctx.fillRect(125,25,150,50);
Thersttwolinesretrievethecanvasanddrawingcontexttovariablesnamedcandctxrespecvely.
Thethirdlinesetsadrawingcolor.ColorscanbespeciedusinganyCSScolorvalue.Thenallineplacesa
redrectangleinthemiddleofthecanvas.Thetoplecornerisatan(x,y)posionof(125,25),the
widthis150andtheheightis50pixels.
Followingtheaboveexample,entertwomorelinesintheJavaScriptconsoletocreateablackrectangle
thatllstheenrecanvas.
Drawtwooverlappingrectanglesindierentcolors,butwiththeiralphavaluessetsothatyoucanseethe
rstrectanglethroughthesecond.
Drawtheredrectangleagain,butuse(40,40)asits(x,y)locaon.Canyouexplaintheresult?

<exercisessection='4.1'>
1.SetupanHTMLpageforaponggame.Includeacanvaswithablackbackground,aheadingand
someinstruconalinformaon.

</exercises>

4.2DrawingCommands
Therearetwobasickindsofdrawingsupportedonthe2Ddrawingcontext(hereaerabbreviatedctx):
"stroke"drawsoutlinesand"ll"llsthemin.

http://profsamscott.com/javascript/

47/137

11/15/2016

JavaScriptforSheridanStudents

4.2.1RectanglesandText
Youhavealreadyseenthectx.fillRect()method,butthereisalsoactx.strokeRect()methodthat
usesthesameparameterstodrawtheoutlineofarectangleinsteadofllingitin.Thereisalsoa
ctx.clearRect()methodthatclearsarectangletotheCSSbackgroundcolor.
Whenyoudo"ll"drawing,thecanvasusesthecurrentcontentsofthectx.fillStyleeldtodecidehowto
dothedrawing.Thectx.fillStyleeldcanholdacolorstring(anylegalCSScolorvalueissupported)ora
specialobjectrepresenngagradientorapaern(formoreinformaonongradientsandpaernsseethe
w3SchoolsCanvasReference).Whenyoudo"stroke"drawing,thecanvasusesthecurrentcontentsof
ctx.strokeStyle,whichcantakethesamevaluesasctx.fillStyle.Anotherrelevanteldforstroke
drawingisctx.lineWidthwhichholdsanumberrepresenngthethicknessofthelinetodrawinpixels.
Ifyouwanttodrawtext,therearectx.fillText()andctx.strokeText()methods.Youcansetthefont
byassigningastringrepresenngaCSSfonttothectx.fonteld.
DoItYourself
Here'sanotherHTML5canvaswithawidthof400pixels,aheightof100pixelsandanidof
"testCanvas2".

IntheJavaScriptconsoleofyourbrowser,trythefollowing:
varc=document.getElementById("testCanvas2");
varctx=c.getContext("2d");
ctx.strokeStyle="#FF0000";
ctx.lineWidth=10;
ctx.strokeRect(125,25,150,50);
Nowaddsometexttothecanvas:
ctx.fillStyle="#0000FF"
ctx.font="22pxArial";
ctx.fillText("Hello,world!",135,55);
Nowtrythefollowingtoclearpartofthedrawing:
ctx.clearRect(0,0,200,50);

4.2.2WhereandWhentoDraw
Drawingcodeshouldbeplacedinafunconsothatitcanbecalledinresponsetoanevent.Thenyoucan,for
example,drawinresponsetoabuonclickorwhensomeonemousesoverthecanvas.
http://profsamscott.com/javascript/

48/137

11/15/2016

JavaScriptforSheridanStudents

Oen,though,youwillwanttodrawonthecanvasassoonasthepageloads.Youmightthinktheright
approachinthiscaseistonotuseafuncon,butsimplyincludethedrawingcommandsinsideascriptelement.
TheproblemisthatyourcodemightexecutebeforetheDOMiscompletelyconstructed.Ifthathappens,the
DOMnodeforthecanvasmightnotbeavailableatthemeyourcoderuns.
Thesoluonistoputthedrawingcodeinafunconandthencallitinresponsetotheonloadeventofthe
<body>element,likethis:
<bodyonload='draw()'>
Theonloadeventisredonce,justaerthebrowserhasnishedconstrucngtheDOM.Youshouldusethis
eventtoexecuteanykindofinializaoncode,includingcanvasdrawing.

<exercisessection='4.2.2'>
1.Connueyourponggamesetup.Usetherectangleandtextdrawingcommandstodrawthe
player'spaddles,anet,andascoreatthetopofthescreen.Putthedrawingcommandsinsidea
funconthatiscalledinresponsetotheonloadevent.
2.GetthecanvasTestBed.htmllefromtheexamplepack.Writeafunconthatcreatesan8x8
checkerboardpaerninthecanvaswhenthebuon1isclicked.

</exercises>

4.2.3Polygons
Ifyouwanttodrawapolygonotherthanarectangle,youhavetorsttraceapathonthecanvasandthen
eitherfill()orstroke()it.
Drawingapolygonhasvesteps:
1.Beginthepathwithctx.beginPath()
2.Movetothestarngposionwithctx.moveTo()
3.Traceoutthepathwithctx.lineTo()
4.Closethepathwithctx.closePath()(thisaddsalinethatgoesbacktoyourstarngposion)
5.Drawtheshapewitheitherctx.fill()orctx.stroke()

http://profsamscott.com/javascript/

49/137

11/15/2016

JavaScriptforSheridanStudents

DoItYourself
Here'sanotherHTML5canvas,withanidof"testCanvas3".

IntheJavaScriptconsoleofyourbrowser,trythefollowingcommandstodrawanorangetriangle:
varc=document.getElementById("testCanvas3");
varctx=c.getContext("2d");
ctx.fillStyle="rgb(255,128,0)";
ctx.beginPath();
ctx.moveTo(200,20);
ctx.lineTo(260,80);
ctx.lineTo(140,80);
ctx.closePath();
ctx.fill();
Thecontextsllremembersthepathevenaeryouhaveusedittodrawashape.Soifyouwanttoputan
outlinearoundyourtriangleyoucandosowithoutretracingthepath:
ctx.strokeStyle="rgba(0,128,255,0.5)";
ctx.lineWidth=10;
ctx.stroke();
Todrawanewshape,justbeginanewpath:
ctx.beginPath();
ctx.moveTo(140,20);
ctx.lineTo(260,20);
ctx.lineTo(200,80);
ctx.closePath();
ctx.fillStyle="black";
ctx.fill();

http://profsamscott.com/javascript/

50/137

11/15/2016

JavaScriptforSheridanStudents

<exercisessection='4.2.3'>
1.GetthecanvasTestBed.htmllefromtheexamplepack.Writeafunconthatdrawsasimpleline
drawingofahouseonthescreenwhenbuon2isclicked.
2.Extendthecodeyouwroteforqueson1sothateachmebuon2isclicked,anewhouse
appearstotherightofthelastonedrawn.(Hint:useaglobalvariabletokeeptrackofthestarng
xcoordinateofthenexthouse.)
3.InthecanvasTestBed.htmlle,writeajavascriptfuncontodrawastarinthetoplecornerof
thecanvas.Addanonclickeventtobuon3sothatwhenitisclicked,astarisdrawn.
4.Extendthecodeyouwroteforqueson3sothatwhenbuon3isclicked,astarisdrawnata
randomposioninarandomcolor.(Hint:GeneraterandomxandyvaluesusingMath.random()
andthenaddthesevaluestothecoordinatesyouuseinthedrawingfuncons.)

</exercises>

4.2.4CirclesandCurves
Thectxobjectalsocontainsmethodsfordrawingcirclesandarcs,tobeusedalongsidectx.beginPath(),
ctx.fill(),ctx.stroke()andtheotherpathdrawingmethods.
Youcanusethectx.arc()methodtodrawacircleorpartofa
circle.Youspecifythecenterofthecircle,itsradiusandthenthe
starngandendingangleforyourcurve.Theseanglesarespecied
inradians,whichisanalternavetousingdegrees(inthesameway
thatinchesareanalternavetocenmetres).Whenyouworkwith
radians,radians(that'stheGreekleerPi,where3.14)is
equivalentto180degrees.So/2is90degrees,/4is45degrees,
andsoon.YoucanusethebuiltinJavaScriptconstantMath.PIfor
this.
Atrightisaquickreferenceforcommonradianvaluestouseinarc
drawing.(Thepictureitselfisactuallya<canvas>elementandthe
diagramisdrawnusingJavaScript.)

http://profsamscott.com/javascript/

51/137

11/15/2016

JavaScriptforSheridanStudents

DoItYourself
Here'syetanotherHTML5canvaswithanidof"testCanvas4".

IntheJavaScriptconsoleofyourbrowser,trythefollowingcommandstodrawapinkcircle:
varc=document.getElementById("testCanvas4");
varctx=c.getContext("2d");
ctx.fillStyle="pink";
ctx.beginPath();
ctx.arc(200,50,45,0,Math.PI*2);
ctx.closePath();
ctx.fill();
Ifyouwanthalfacircle,youshoulddrawfrom/2to3/2.
ctx.strokeStyle="black";
ctx.beginPath();
ctx.arc(200,50,45,Math.PI/2,3*Math.PI/2);
ctx.closePath();
ctx.stroke();
Arcsarealwaysdrawnclockwisebydefault.Whatwouldyouneedtochangeinthe
abovecommandstodrawtheotherhalfofthecircle?
Canyouclearthecanvasandusethectx.arc()methodtodrawPacMan?

Therearealsocommandsavailabletodrawcurvesaspartofthepath(thatis,connuingfromwhereveryour
pathleo).Theyarectx.arcTo(),ctx.quadraticCurveTo()andctx.bezierCurveTo().Thereare
alsootheradvanceddrawingcommandsarealldiscussedinfullinthew3SchoolsCanvasReference.

http://profsamscott.com/javascript/

52/137

11/15/2016

JavaScriptforSheridanStudents

<exercisessection='4.2.4'>
1.ConnueyourPonggamesetupbyaddingaballtothescreen.
2.GetthecanvasTestBed.htmllefromtheexamplepack.Writeafunconthatdrawsasimpleline
drawingofacaronthescreenwhenbuon4isclicked.Havethecarappearunderthehousefrom
theprevioussecon'sexercises.
3.Extendtheanswertoqueson1sothateachmebuon4isclicked,anewcarappearstothe
rightofthelastonedrawn.(Hint:useaglobalvariabletokeeptrackofthestarngxcoordinateof
thenextcar.)
4.(CourtesyofAnnCadger)Writeafunconthatusesthecurvedrawingmethodstodrawaturtleon
thescreenwhenthemousemovesoverthecanvas(clickhereforturtleideas
[hps://www.google.ca/search?q=turtle+drawing]).

</exercises>

4.3CanvasInputEvents
Ifyourgoalistocreateagameorsomekindofinteracvedisplay,youneedtobeabletoreacttouserinputon
thecanvasfromakeyboardoramouse.(Youalsoneedtobeabletoproduceanimaons,butthatwillbe
coveredinChapter6).

4.3.1MouseInput
YouwereintroducedtoalltherelevantmouseeventaributesinChapter5.Asareminder,theyareonclick,
ondblclick,onmousedown,onmouseup,onmouseover,onmouseleaveandonmousemove.Buttotakefull
advantageoftheseeventsforacanvas,itisnotenoughtoknowthatthecanvaswasclickedorthatthemouseis
movingontopofthecanvas,wealsoneedtoknowwherethemouseis.Forthis,youcanusetheeventobject.
Wheneveraneventhappens,aneventobjectiscreatedthatcontainsinformaonabouttheevent.Thatevent
objectispassedtothecodeyouputinsidetheeventaribute(thisisdonethroughawrapperfunconthatis
createdtocontainthecodeyouwritethere).Youcanaccessthiseventobjectandpassitontothefunconyou
wrotetorespondtotheevent,likethis:
<canvasonclick='myFunction(event);'...></canvas>
Nowyoucangetinformaonoutofit.Forexample,event.targetwillbeareferencetotheelementthatwas
thetargetoftheevent,inthiscasethecanvas.
Findingoutwhereonthecanvasthemouseeventhappenedtakesalilebitofmath:
varx=event.pageXc.offsetLeft
vary=event.pageYc.offsetTop
ThepageXandpageYproperesgetyouthexandylocaonoftheexactpixelonthewebpagewheretheclick
happened,withx==0andy==0beingtheveryleandtopedgesofthepage.Butyouwanttoknowwhereon
thecanvastheclickhappened,withx==0andy==0beingtheleandtopedgesofthecanvas.Tondout,you
simplyhavetosubtracttheoffsetLeftandoffsetTopproperesofthecanvas(c),whichtellyouhow
manypixelsthecanvasisawayfromtheleandtopofthescreen.

http://profsamscott.com/javascript/

53/137

11/15/2016

JavaScriptforSheridanStudents

DoItYourself
LoadupcanvasTestBed2.htmlfromtheexamplepackandclickoneachcanvascanvas.Eachcanvascallsa
funconwhenclickedthatreportsthelocaonoftheclickusingtheequaonabove.Thelocaonis
reportedtothecanvasandalsointheconsoleusingconsole.log()
Butthesecondcanvaslocaonsarealloby30pixels.Thisisbecausethiscanvashasa30pixelborder
thatcountsaspartoftheclickableareaoftheelement.Sotogetthexandycalculaonrightforthis
canvas,thesizeoftheborderhastobesubtracted.
LoadcanvasTestBed2.htmlintonetbeans[hps://netbeans.org/]andxthewhereClickedfunconso
thatitusesthiscalculaonforthesecondcanvas(butnottherst):
varx=event.pageXc.offsetLeft30;
vary=event.pageXc.offsetLeft30;
Nowchangeonclicktoonmousemoveforoneofthecanvases.Thiscouldbethebeginningofa
painngapp...

Thereareafewothereventeldsthatmightalsobeusefulformouseinput:event.ctrlKey,event.altKey
andevent.shiftKeywilleachbetrueifthectrl,altorshiftkeys(respecvely)werehelddownwhen
themouseeventhappened.Otherwisetheywillbefalse.

http://profsamscott.com/javascript/

54/137

11/15/2016

JavaScriptforSheridanStudents

<exercisessection='4.3.1'>
1.ChangecanvasTestBed2.htmlsothatitcontainsonlyonecanvasandmodifythecodesothatit
drawsacirclewitha5pixelradiuswhenthemousemovesoverthecanvas.
2.Nowaddaglobalvariabletoindicatewhetherthepaintbrushisalargecircle,smallcircle,large
square,orsmallsquare.Havethefourbuonscallfunconstoswitchbetweenbrushes.Makesure
thesquarebrushesaredrawncenteredaroundthexandycoordinatesofthemouse.
3.AddanHTMLcolorelementtoallowtheusertochoosethedrawingcolor.Inthedrawingfuncon,
setthellStyleusingthevalueofthiselement.
4.Nowchangetheappsothatdrawingonlyhappensifthemousebuonispresseddown.Thisisa
liletrickierthanitsoundstogetworkingexactlyright.Itwillrequiretheuseofanotherglobal
variableandanumberofdierentevents.
5.InyourPonggame,getapaddlemovingundermousecontrol(xitsxlocaonandmakeitsy
locaonmatchtheycoordinateofthemouse).Thisisaliledierentfrompaintbecauseifyou
havebeenfollowingthedevelopmentofPongintheseexercises,thenyoualreadyhavethecanvas
redrawingevery16milliseconds.Soyounowneedaglobalvariablefortheylocaonofthepaddle,
thenintheonmousemoveevent,allyouneedtodoischangethisglobalvariablethedrawingwill
happenintheframedrawingmethod.
6.Inthepaintapp,changethingssothatiftheuserisholdingdownthectrlkey,draggingthe
mousewilleraseasquarearea(withclearRect).
7.Inthepaintapp,changethingssothatiftheuserisholdingdownthealtkeyitdoublesthesizeof
thebrushtheyarecurrentlyusing.
8.ImageMagnierProject.Usethemouseeventstoimplementanimagemagnierlikethisone
[hp://markrolich.github.io/Magnier.js/].Animagemagnierusesalargeandsmallversionof
animageanddisplaysthesmallversionbydefault.Thenwhentheusermousesovertheimage,it
revealsapreviouslyhiddenelementcontainingthelargeversionoftheimage,butshowingonly
thepartofitthatiscenteredaroundthecurrentmouselocaon.Thereareanumberofwaysto
accomplishthis,butonewayistousea<div>elementforthemagniedimageandsetits
backgroundimageCSSpropertytodisplaythelargeversionoftheimage.Thenadjustthe
backgroundpositionxandbackgroundpositionyproperesinresponsetomouse
movementsoverthetargetimagesothatthecorrectfeatureisshown.

</exercises>

4.3.2KeyboardInput
Therearetwokeyboardeventsthatareguaranteedtoworkonallbrowsers.Theonkeydowneventwillre
whenakeyispresseddown,andtheonkeyupeventwillrewhenthekeyislied.Intheorytheseevent
aributescanbeplacedonmostHTMLelements,butkeyboardeventswillonlyeverberedforelementsthat
havefocus.
Itispossibletogivefocustoa<canvas>element.Todothisyouneedtogivethe<canvas>atabindex=1
aributeandthencallthejavaScriptfocus()funconontheelementtogiveitthefocus.Butthisisalile
awkwardandifthereareotherfocusableelementsonthepage,theycouldsteakfocusaway.
Abeersoluonisoentoputtheonkeydownandonkeyupeventsonthe<body>element.Thisistheone
elementthatalwayshasfocus.
http://profsamscott.com/javascript/

55/137

11/15/2016

JavaScriptforSheridanStudents

Justlikewithmouseevents,youshouldpasstheeventobjecttothefunconyouarecalling:
<bodyonkeydown='foo(event);'>
Thenyoucanaccesstheintegercodeforthekeythatwaspressedasfollows:
functionfoo(event){alert(event.keyCode)}
Justlikewithmouseeventsyoucanalsouseevent.ctrlKey,event.altKeyandevent.shiftKeytond
outifanyofthesekeyswerehelddownwhentheeventhappened.
DoItYourself
LoadupcanvasTestBed3.htmlfromtheexamplepackandslowlypressandreleaseakeytoseethe
keyboardeventsinacon.
YoucanusethisliletestapptogureoutkeycodesoryoucangototheMozillaDeveloperNetwork
keyCodepage[hps://developer.mozilla.org/enUS/docs/Web/API/KeyboardEvent]forafulllistofkey
codes.

<exercisessection='4.3.2'>
1.WritecodeincanvasTestBed3.htmlorcreateyourownpagewithacanvasonit.Haveasquareor
circleinthemiddleofthescreenandrespondtothearrowkeysbymovingandredrawingthecircle
10pixelsup,down,le,orright.
2.Modifyyourcodefromthelastexercisesothattheshapebeginstomoveonepixelatamewhen
youpressdownanarrowkey,andstopswhenyouliitup.Thisrequiresaverydierent
architecture:treatitlikeananimaonwith60framespersecond.Whenakeyisdown,recordthat
factinaglobalvariable.Thenineachanimaonframe,ifakeyisdown,movetheshapeonepixel
intheappropriatedirecon.
3.GetthesecondpaddleinyourPonggamemovingunderkeyboardcontrol.Thisisaliletrickier
thanitsoundsbutonewaytodoitistohaveaglobalvariableforupandanotherfordown.When
theuserpressesdowntheupbuon,settheupvariabletotrue.Whentheyreleaseitsetitto
false.Dothesameforthedownbuon.Thenintheframedrawingfuncon(theonethatis
controllingtheball)movethepaddleupordowndependingonwhichofthesevariablesare
currentlytrue.
4.Inthepaintapp,makethebackspaceanddeletebuonsclearthescreen.(Itmightbeniceto
popupaconrmaondialogbeforeyoudothat.)

</exercises>

http://profsamscott.com/javascript/

56/137

11/15/2016

JavaScriptforSheridanStudents

5.FunctionsasValues
Upunlnow,youhavebeenaddingeventhandlerstoelementsbyplacingJavaScriptcodeintothe
correspondingHTMLaributes,likethis:
<inputtype="button"onclick="myFunction()">
ThisisnotconsideredbestpraccebymostJavaScriptprogrammersforatleastthreereasons.
1.ItspreadsyourJavaScriptcodethroughouttheHTMLle,makingthecodehardertomaintain.(i.e.It
wouldbemuchbeerifyoucouldaddallyoureventhandlercodeinasingleplace.)
2.Itviolatesthecleanseparaonbetweenthestructureoftheinterface(thejobofHTML),thestyleofthe
interface(thejobofCSS)andthefunconalityofyourapp(thejobofJavaScript).
3.Itcausesthebrowsertocreateanewanonymousfunconwiththecodeyouputintheaributeasits
contents.Thisisunnecessaryandwasteful.(theterm"anonymousfuncon"willbeexplainedina
moment.)
ItiswidelyconsideredbestpraccetoaddeventhandlersusingJavaScriptstatementsaerthedocumenthas
loaded.Buttobeabletodothat,youneedtounderstandhowJavaScriptfunconsworkinalilemoredepth.

5.1TheTruthAboutFunctions
ThetruthaboutJavaScriptfunconsisthattheyareactuallyvalues,justlikeStrings,Numbers,Booleans,and
Objects.Likeanyothervalue,funconscanbestoredinvariables,passedasparameterstootherfuncons,and
returnedfromfunconcalls.
ThetechnicaltermforthisisthatJavaScriptfunconsarerstclassfuncons.
Whenyouuseafuncondeclaraonlikethis:
functionfoo(a,b,c){
alert(a+b+c);
}
Whatyouarereallydoingiscreangavariablenamedfoo,andassigningafunconvaluetoit.
Thefollowingshowstheassignmentofafunconliteraltoavariable.ItislegalJavaScriptcode,andis
equivalenttothefuncondeclaraonabove:
varfoo=function(a,b,c){
alert(a+b+c);
};

http://profsamscott.com/javascript/

57/137

11/15/2016

JavaScriptforSheridanStudents

Theabovestatementcreatesavariablenamedfoo,and
assignstoitananonymousfunconwith3parameters.
(Notethatsincethestatementaboveisanassignment
statement,weputasemicolonattheendofit.)Thefuncon
beingassignediscalledananonymousfunconbecauseitis
createdwithoutbeinggivenaname.The"name"usedtocall
itcomesfromtheassignmentoftheanonymousfunconto
avariable.

JavaConnection
MethodsvsFuncons.InJava,methods
andvariablesarecompletelydierent
enes.(Queson:howwouldyou
describethisdierence?)InJavaScript,
funconnamesareactuallyvariable
names,andfunconsaredata.

Anonymousfunconsarealsoreferredtoas"funcon
literals"becausetheyarelikeNumber,StringorArrayliteralstheyarevaluesthatarehardcodedintothe
program.
Themaindierencebetweenthetwonotaonsisthatyoucanonlyusefuncondeclaraonincertaincontexts,
butyoucanusevariabledeclaraonandfunconliteralsinanycontext.Infact,thefuncondeclaraon
notaonisoenavoidedbyJavaScriptprogrammersonthegroundsthatitislimitedinuseandaddsnothingto
thelanguage.Theseprogrammersalwaysusethevariabledeclaraon/funconliteralnotaoninstead.
DoItYourself
Nomaerwhetheryouusefuncondeclaraonorvariabledeclaraonwithfunconliterals,ifyourefer
tofooinyourprogram,youarereferringtoavariable.Toseethis,trythefollowingintheJavaScript
consoleofyourbrowser:
functionfoo(){alert("hi");}fooisafunction
foo;
foo();
Queson:Whatisthedierencebetweenthelasttwolinesabove?
alert(foo);
alert(foo());
Queson:Whatisthedierencebetweentheabovetwolines?
Trythelinesbelowtoseethatyoucanswitchfoobackandforthbetweenafunconandotherdata
types.
foo=5;fooisnowanumber
alert(foo);
foo=function(){alert("hi");};fooisafunctionagain
alert(foo);
foo="hi";fooisnowastring
alert(foo);

Answers:Intheconsolewindow,fooreturnsthevalueofthevariable.It'safuncon.Butfoo()callsthe
funconsoyouwillseethepopup.Ontheotherhand,alert(foo)willdisplayapopupwhosecontentisthe
valueofthevariablefoo(ifit'safuncon,itwillshowyousomethingtothateect).Finally,alert(foo())
willrstcallthefoofuncon,displayingapopup.Thenitwillcreateanotherpopuptodisplaythereturnvalue
offoo.Sincethereisnothingexplicitlyreturned,itwillreturnthespecialvalueundefined.
http://profsamscott.com/javascript/

58/137

11/15/2016

JavaScriptforSheridanStudents

5.2BetterWaystoAddEventHandlers
Ifyouwanttoaddeventhandlerstoanelementaeritiscreated,youcandoitbyretrievingtheelementfrom
theDOMandassigningafunconliteraltotheaributefortheeventhandler.
DoItYourself
TrythefollowinginthejavaScriptconsoleforthistextbook.
document.getElementById("test1").onclick=function(event){
alert("hello!");
};
SincethisDIYboxhasanidoftest1,youshouldnowbeabletoclickitandseetheresult.
P.S.Don'tworryabouttheeventparameterabove.Itwillbeexplainedlater.

Oryoucancreatethefuncon(eitherthroughfuncondeclaraonorusingafunconliteral)rst,andthen
assignittotheeventhandler.
DoItYourself
TrythefollowingintheJavaScriptconsoleforthistextbook.
varclickHandler=functionclickHandler(event){
alert("goodbye!");
}
document.getElementById("test2").onclick=clickHandler;
Nowyoushouldbeabletoclickthisboxforamessage.

AnotheroponthatsomeprogrammerspreferistousetheaddEventListenermethodwhichtakestwo
parameters.Therstistheeventname(withoutthe"on"souse"click"insteadof"onclick")andthesecondis
thehandlerfuncon.

http://profsamscott.com/javascript/

59/137

11/15/2016

JavaScriptforSheridanStudents

DoItYourself
TrythisintheJavaScriptconsoleforthistextbook.Notethatyouwillhavetodeneclickhandlerrst.You
cangetitfromthelastDIYbox.
functionclickHandler(event){
alert("goodbye!");
}
document.getElementById("test3")
.addEventListener("click",clickHandler);
Ofcourseyoucanalsoaddahandlerusingafunconliteral.Trythis:
document.getElementById("test3")
.addEventListener("click",function(event){
alert("hello!");
});
Ifyouexecutebothcodesnippetsabove,thenwhenyouclickthisboxyoushouldgettwopopups,not
one.Thisillustratesonecrucialdierencebetweenassigningtoonclickandusing
addEventListener.Thelaerallowsyoutoaddmanyeventhandlersofthesametypetothesame
object.

JavaConnection
EventListeners.JavaandJavaScriptbothuseaddListenermethodstoregistereventhandlers.The
dierenceisthatinJavaaneventlistenerisanobject,whileinJavaScriptit'safuncon.

5.2.1TheeventObjectandthethisKeyword
Notethatthefunconsaboveallcontainaneventparameter.Anyeventhandlerisalwayspassedaspecial
eventobjectthatrepresentstheeventthatcausedthisfunconcall.Youcanuseittoaccessinformaonabout
theevent,suchaswhichelementtriggeredtheevent(event.target),whichmousebuonwaspressed
(event.button),thelocaonofthemouseonthepage(event.pageXandevent.pageY),etc.

http://profsamscott.com/javascript/

60/137

11/15/2016

JavaScriptforSheridanStudents

DoItYourself
HerearetwolastthingstotryintheJavaScriptconsoleforthistextbook.
document.getElementById("test4").onclick=function(event){
alert(event.pageX+","+event.pageY);
};
Nowwhenyouclickonthisbox,youwillgettoseetheexactXandYlocaonofyourclick,inpixels
relavetotoplecornerofthepage.IfyouchangepageXandpageYtoclientXandclientYyouget
thelocaonrelavetothetoplecornerofthebrowserwindow.
Theeventobjectcontainsanumberofusefulelds,butprobablythemostusefulisthetargeteld
whichreturnstheDOMnodethatwasthesubjectoftheevent.
Trythis:
document.getElementById("test4").onclick=function(event){
alert(event.target.innerHTML);
};
NowclickingthisboxshouldgetyoutheinnerHTMLoftheelementyouclickedon.

Butsomemesevent.targetwon'tgetyouexactlytheelementyouwanted.inthiscase,youshouldusethe
thiskeyword.
DoItYourself
InthelastexamplethecontentsofthealertwillvarydependingonwhereyouclickinsidetheDIYbox.
Thisisbecausethetargetisnotnecessarilythesameastheelementyouaddedthelistenerto.Canyou
gureoutbyinspecngtheDIYboxwhatthetargetactuallyrefersto?
Ifyouwanttomakesureyouaccesstheelementthatthelistenerwasaddedto,usethekeywordthis
insteadofevent.target.
Trythis:
document.getElementById("test4").onclick=function(event){
alert(this.innerHTML);
};
NowclickingtheDIYboxabovethisoneshouldgetyoutheinnerHTMLoftheenrebox,nomaer
whereyouclickonit.

FormoreinformaonontheEventobject,seethew3schools'DomEventspage.

http://profsamscott.com/javascript/

61/137

11/15/2016

JavaScriptforSheridanStudents

5.2.2Thewindow.onloadEvent
ItisalsoconsideredbestpracceinJavaScript,towriteallofyourcodeinsideawindowloadeventhandler,like
this:
window.addEventListener("load",function(){
//ALLYOURCODEGOESHERE
});
Whenyouputallyourcodeinsidetheloadevent,the
browserwillwaitunlthepageisreadybeforeexecungit.
Soyoucanputyourcodeintothe<head>ofyourdocument
withouthavingtoworryaboutwhethertheDOMisreadyat
thatpoint.Thisisabigadvantage.
Anotheradvantageisthatnowallvariablesyouuse
(includingfunconnames)becomelocaltotheanonymous
funconyouassigntotheloadevent.Thisisgoodtoo
becauseitminimizespotenalnameconictswithother
JavaScriptcodeorlibrariesyoumightbeusing.

JavaConnection
Funconswithinfuncons.One
consequenceofthefactthatfunconsin
JavaScriptarevaluesstoredinvariablesis
thatyoucandeclarefunconswithin
funcons.Thereisnowaytodoanything
likethisinJava.

NotethatbecausefuncondeclaraonsarejustvariabledeclaraonsinJavaScript,evenotherhelperfuncons
canbedenedinsidethewindowloadevent.

<exercisessection='5.2.2'>
1.LoadeventHandlerTest.htmlfromtheexamplepack.Comparehowthehandlershavebeenadded
totheelementswithidtest1andtest2.
a.Considerthepageasitisloadingintothebrowser.Atwhatpointinmeiseachhandler
added?
b.Trycommenngoutthewindow.onloadlineandthe};linethatgoeswithitandreload
thepage.Describehowthepageworks(ornot)nowandexplainwhy.
2.Addtwohandlerfunconstotheelementwithid="message"usingJavaScript(notHTML
aributes).Thesefunconsshouldrespondtotheonmouseoverandonmouseoutevents.When
themouseisinsidethemessagebox,oneoftheotherboxesshouldbepinkandtheothershould
bewhite.Whenthemouseisoutsidethemessagebox,theonethatwaswhiteshouldbecomelight
blueandtheonethatwaspinkshouldbecomewhite.Allyourcodeshouldbeinsideawindowload
eventhandler.
3.Gobacktotheotherexercisesfromthischapter(messages,catchtherabbit,etc.)andrefactor
themsothatallofyourcode(includingcodeinonclickorotherHTMLaributes)istuckedaway
insideawindowloadeventhandler.

</exercises>

5.3Functions,TimersandAnimation
Nowthatyouknowthetruthaboutfuncons,wecanalsotalkabouthowtousemerstocreateanimaon
eectsonacanvas
http://profsamscott.com/javascript/

62/137

11/15/2016

JavaScriptforSheridanStudents

Animaonreferstoanypictureinwhichelementsofthepictureseemtomoveorchangeoverme.Thebasic
techniqueinanyformofanimaonistopresentaseriesofanimaonframes(i.e.pictures)oneaeranother
veryquickly,witheachframeslightlydierentfromthelast.Forexample,anobjectmightmoveveryslightlyto
therightorgrowslightlyfromframetoframewhiletherestofthepictureremainsunchanged.Ifthisisdone
quicklyenough,theeyewillbefooledintoseeingsmoothmoon.
ToanimateanelementusingJavaScript,weneedthreethings:
1.Asetofvariablesthatspecifyimportantdetailsabouttheobjectbeinganimated(e.g.xandyposion,
color,size,etc.)
2.AfunconthatupdatesthesevariablesandthenmakeschangestotheCSSforthatobjectusingthenew
values.
3.Awaytotriggertheupdatefunconrepeatedly
(Ifyouwanttoanimatedrawingsonacanvas,useaverysimilarmethod,buttheupdatefunconwillneedto
clearandredrawtheenrecontentsofthecanvaseachmeitiscalledratherthanmakingchangestotheCSS.)

5.3.1JavaScriptTimers
We'llstartwithitem3fromthelistabove:Weneedawaytotriggerafunconrepeatedly.JavaScriptmersare
theanswertothatproblem.
JavaScriptfunconsarecalledinresponsetoevents(e.g.theuserpressesthemousebuonorthepageloads).
Ifyouwantafuncontobecalledrepeatedly,orjustoncebutatsomemeinthefuture,youhavetoschedule
amerevent.ThewindowobjectinJavaScriptcontainsasetTimeoutfuncontotriggeraneventsomeme
inthefuture,andasetIntervalfuncontotriggeraneventrepeatedlyatsetintervals.
Totriggeraneventrepeatedly,youcanusethefollowingcommand:
setInterval( functionName , interval );
Intheabove,functionNameisthenameofthefunconyouwanttocallwhenthemereventshappen,and
intervalisthenumberofmillisecondsbetweeneachevent.
Forexample,ifyouwanttocallafunconnamedtickeveryhalfasecond(500milliseconds),thecommand
wouldbe:
setInterval(tick,500);
Notethatyoumustnotusetick()withthebrackets.Thiswouldcallthetickfunconimmediately.Butwe
don'twanttocallitnow,wewanttopassitlikeaparametertothesetIntervalfunconsothatitcanbe
calledlater,whenthemereventhappens.
Tocallafunconjustonce,butatsomemeinthefuture,usethefollowingcommandtoscheduleasingle
merevent:
setTimeout( functionName , interval );
TheparametersarethesameassetInterval,butthefunconyouspecifywillonlybecalledonce,aer
intervalmilliseconds.

http://profsamscott.com/javascript/

63/137

11/15/2016

JavaScriptforSheridanStudents

DoItYourself
TrythefollowingintheJavaScriptconsoleofChrome:
functionhi(){alert("Hello");}
setTimeout(hi,5000);
Nowwaitvesecondsforyourmessagetoappear.
Trythesamethingonarepeangmer:
setInterval(hi,5000);
Nowyouwillgetapopupevery5seconds.Youcanreloadthepagetomakeitstop.

BothsetTimeoutandsetIntervalreturnanintegeridforthemeryouhavecreated.Ifyouwanttostopa
mer,youcandosowiththeclearTimeoutfuncon.Butyouhavetohavesavedtheidofthemerina
variable:
vartimerId=setInterval(myFunction,1000);
Withthisvariableyoucanstopthemeratanyme:
clearTimeout(timerId);
ThiswillalsoworkforsetTimeout.
DoItYourself
GobacktothepreviousDIYboxandexecutetherepeangpopupcommandagain,butthismestoreits
returnvalueinavariable:
vartimerId=setInterval(hi,5000);
Nowyoucanstopthepopupsbyclearingthemer:
clearTimeout(timerId);

http://profsamscott.com/javascript/

64/137

11/15/2016

JavaScriptforSheridanStudents

DoItYourself
LoadthemerExample.htmllefromtheexamplepackandrunit.Youshouldseetheword"ck"appear
every0.5seconds,andaerjustover5secondsyoushouldseetheword"***ALARM***"appear.You
canstoptheckingbypressingthe"stop"buon.
Examinethecodeforthislemakesureyoucananswerthesequesons:
1.Whichfunconsstopandstartthemers?
2.Whendoeseachofthesefunconsgetcalled?
3.Whatisthepurposeofthealarmandtickfuncons?
4.Howdoesthestopfunconknowwhichmertostop?
Nowaddcodetothelesothatthereisa"stopalarm"buonthat,whenpressed,willpreventthealarm
messagefrombeingdisplayed(ifithasn'talreadybeendisplayed).

5.3.2GettingThingsMoving
Recallthatweneededthreethingstogetananimaongoing:
1.Globalanimaonvariables,
2.AfuncontoupdatethosevariablesandchangeCSSproperes(ortoredrawthecanvasifyouareusing
one),and
3.Awaytotriggerthatfunconrepeatedly.
Wenowhavethelastpart:setIntervalcanbeusedtocallafunconeveryfewmilliseconds.Allweneed
nowissomeglobalvariablesandanupdateAnimationfuncon.
Theglobalvariablesshouldkeeptrackofposionandotherinformaonfortheobjectsthataremoving.
TheupdateAnimationfunconshouldtakethefollowingacons:
1.Updatetheanimaonvariables(e.g.x=x+1)
2.MaketherequiredchangeSize
a.IfyouareanimangHTMLelements,settherelevantCSSproperes(e.g.e.style.left=x+
"px").NotethattheCSSpropertypositionmustbesettoabsoluteorfixedforthistowork.
b.Ifyouareanimangapictureonacanvas,clearthecanvas(e.g.ctx.clearRect(0,0,
canvas.width,canvas.height))andthendrawthenewframe,usingtheanimaonvariables
(e.g.ctx.fillRect(x,100,50,50);).
Fortheappearnaceofsmoothmoon,thesetIntervalfunconshouldbeusedtotriggeracallto
drawFrameabout60mespersecond.Thatworksouttoanintervalof16milliseconds.

http://profsamscott.com/javascript/

65/137

11/15/2016

JavaScriptforSheridanStudents

DoItYourself
HTMLAnimaon: LoadthesampleAnimaon.htmllefromtheexamplepackandwatchitrun.
CanvasAnimaon: LoadthesampleCanvasAnimaon.htmllefromtheexamplepackandwatchitrun.
Whicheveroponyouchoseabove,makesureyoucananswerthefollowingquesons:
1.Whenandhowdoestheanimaonstart?
2.Whenandhowdoestheanimaonstop?
3.Forthecanvasanimaon,whatwouldhappenifyouskippedtheclearcanvasstep?

http://profsamscott.com/javascript/

66/137

11/15/2016

JavaScriptforSheridanStudents

<exercisessection='5.3.2'>
1.FetcheithersampleAnimaon.htmlorsampleCanvasAnimaon.htmlfromtheexamplepack.
a.Modifyitsothattheballmovesdownandtotheright.
b.Nowmodifyitsothattheballshrinksasitmoves.
c.Finally,modifyitsothattheballstartsoasblackandendsasred(Hint:deneared
variabletostartat0andgrowto255.Thensetthecolorusingrgb(___,0,0)withthe
valueofyourvariableintheblank.
2.ModifysampleAnimaon.htmlorsampleCanvasAnimaon.htmlfromtheexamplepacksothat
theballbouncesbackwhenithitstheedgeofthescreen.(Hint:insteadofx=x+1use
x=x+xSpeedwherexSpeedisiniallysettoaposivenumber.Thenwhentheballreachesthe
edgeofthescreen,mulplyxSpeedby1tostartmovingtheballintheoppositedirecon.
3.ModifysampleAnimaon.htmlorsampleCanvasAnimaon.htmlorupdatemoveme.htmlfrom
theexamplepacksothattheballmovesdiagonallyandbouncesoallfourwalls.(Hint:denean
xSpeedandaySpeed.)
4.Getyin.htmlfromtheexamplepackandaddcodetoittomakethe<h1>elementsyinfromthe
sideofthescreen.Startwiththemallmovingtogether,thenseeifyoucanextendittomakethem
yinatdierentmes.
5.Createyourownanimaonfromscratchwithatleasttwoelementsmovingorchangingatonce.
6.GobacktocatchTheRabbit.htmlfromtheexamplepack.Delete3oftherabbitsandcreateanew
versionofthegamewheretherabbitrunstoadierent(randomlyselected)locaononthescreen
whenyoumouseoverit.(Hints:Usewindow.innerWidthandwindow.innerHeighttogetthe
heightandwidthofthescreen.Forglobalvariables,usex,ytorepresenttherabbit'sposionand
targetX,targetYtorepresentwheretherabbitisgoing.EachcalltoupdateAnimaonshould
justmovexandyclosertothetargets.Whentheusermousesovertherabbit,setanewtarget.)
7.MoreCanvasExercises
a.NowgettheballmovinginthePonggameyouaredeveloping.
b.GetthecanvasTestBed.htmllefromtheexamplepack.Writeafunconthatcreatesan8x8
checkerboardpaerninthecanvaswhenthebuon1isclicked(ifyouhaven'talready
donethat).Nowmakethemodicaonsnecessarysothataerbuon1isclickedthe
checkerboardreversesevery250milliseconds.
c.Extendyoursoluontothepreviousexercisesothatwhenyoupressbuon1again,itstops
theanimaon.
d.TheGreengCardProject:

Createawebapptodisplaycustomgreengcardsforamobilephoneuser(withascreen
sizeof320pxby480px).

Whentheuserloadsthepage,theyshouldseeaheadingandaformthatletsthem
customizetheircard.Theformshouldletthementeradate,thenameoftheevent,the
nameoftherecipientandotherinformaonasyouseet.Thereshouldbea"makecard"
buonthat,whentheyhitit,hidestheformandrevealsacanvasshowingthe"front"ofthe
card,withasimplebutelegantdesignthatincorporatesthetexttheyentered.Thecard
http://profsamscott.com/javascript/

67/137

11/15/2016

JavaScriptforSheridanStudents

designshouldincludesometypeofanimatedelement(somethingmoving,changingcolor,
growingorshrinking,etc).

BONUS:Whentheuserclicksthecard,makeit"open"toshowthemadierentdesignon
theinside.

</exercises>

5.4Functions,ImagesandSound
Tomakeanicercanvasgame,youmightwanttoloadimagesfromaleandthendrawthemonthecanvas.To
makeabeeroverallexperiencefortheuser,youalsomightwanttoplaysoundsinresponsetocertainevents.

5.4.1TheBasics
Todrawanimage,youhavetocreateanImageobject,thenloadanimageleintoitandthendrawit.Creang
theimageobjectandloadingtheimageshouldbedoneonceandstoredinaglobalvariable.
varmyImage=newImage();
myImage.src="images/myImageFile.jpg";
Oncetheimageisloaded,youcandrawitonthecanvasinresponsetoanevent.
ctx.drawImage(myImage,x,y);
Toplayasound,youhavetocreateanAudioobject,thenloadanaudioleintoandthenplayit.Creangthe
Audioobjectandloadingtheaudioleshouldbedoneonceandstoredinaglobalvariable.
varmyAudio=newAudio("sounds/myAudioFile.mp3");
Oncetheaudioisloaded,youcanplayitanyme.Thisisdoneintwosteps.
myAudio.load();//resetsthesoundsoitcanbeplayedrepeatedly
myAudio.play();//playsthesound

5.4.2DealingwithLag
Thereisoneproblemlurkingintheaboveinstrucons.Whenyourappisonline,theHTMLpagewillloadrst
andthesoundsandimageswillonlybegintobedownloadedfromyoursitewhenyoucreatetheAudioand
Imageobjects.Whatifyoutrytodrawyourimagesorplayyoursoundsbeforetheyhaveloaded?
Todealwiththisproblemforimages,youcansetupanonloadeventlikethis:
myImage.onload=myImageReady;
WheremyImageReadyisthenameofafunconthatwillbecalledwhentheimageisloaded.Youcanuseitto
setaglobalagtolettherestoftheappknowtheimageisready
Thesoluonforaudioissimilarbutusesadierentevent:
myAudio.oncanplaythrough=myAudioReady;
Inthiscase,myAudioReadywillbecalledwhenthesoundcanbeplayedthroughfrombeginningtoend.
http://profsamscott.com/javascript/

68/137

11/15/2016

JavaScriptforSheridanStudents

DoItYourself
TryoutsoundAndVision.htmlfromtheexamplepacktoseeimagesandaudioinacon.

<exercisessection='5.4.2'>
1.FollowtheinstruconsabovetoputsoundsintoyourPonggameanduseimagesforthepaddles
andball.Forimagesyoucanlegallyuse,searchcreavecommons
[hp://search.creavecommons.org/].Forsoundeects,tryfreesound.org
[hp://freesound.org]orsoundjay.com[hp://soundjay.com].

</exercises>

5.5CreatingYourFirstCanvasGame
NowyouhaveeverythingyouneedtomakeasimplegameintheHTML5canvas.Here'salistofbasic
componentsyoucanadapttosuityourneeds:
1.Asetofglobalvariablestocontrolposion,speed,direconandotheraributesofthemovableobjects.
Youmayalsoneedvariablestocontrolthestateofthegame(gameon,paused,gameover,etc.)and
possiblythescore.
2.Asetoffunconsthatarecalledinresponsetokeyboardandmouseevents.Thesefunconshouldmake
changestotheglobalvariablesthatcontroltheplayerobjectsinthegame.
3.AcomputeFramefunconthatiscalledoncevery16milliseconds.Thisfunconcontainsthemaincode
forthegame.
TheprimaryjobofcomputeFrameistodrawthecurrentanimaonframe.Butbeforeitdoesthat,itshould
updatetheposionsofalltheobjectsbasedontherelevantvariables.Itshouldalsocheckforcollisions
betweenobjectsorbetweenobjectsandtheedgesofthescreenandmakechangesasaresult(reversespeeds
tosimulateabounce,increasethescore,markanalienas"dead",endthegame,etc.)
Hereareafewextrapstohelpyouout:
1.Anobject'sdireconandspeedcanberepresentedusingtwovariablesforxSpeedandySpeed.In
computeFrame,usex+=xSpeedandy+=ySpeedtomoveitonestep.
2.Youdon'thavetouseintegers.Ifyousetthexandyspeedsto0.5and0.25youwillgetanobjectthat
movesslowlytotheleandslightlydown.
3.Tomakeanobjectbounce,youcanreverseitsspeedwithxSpeed=xSpeed*1andySpeed=
ySpeed*1.Ifyoureverseboth,itwillbouncebackthewayitcame.Ifyoureverseonlythexspeedit
willseemtobounceoavercalsurface.Ifyoureversetheyspeeditwillseemtobounceoahorizontal
surface.
4.Gravitycanbesimulatedbyaddingasmallamount(e.g.0.01)totheySpeedofanobjectateverystep.
5.Collisionscanbedetectedbymeasuringhowclosetwoobjectsaretooneanother.Usetheirxandy
locaonstocomputethedistancebetweenthemusingthelengthofalinesegmentformula
[hp://www.freemathhelp.com/lengthlinesegment.html].Iftheyaretooclose,it'sacollision.
That'sit.Therestyouwillhavetoworkoutforyourself.Happygaming!
http://profsamscott.com/javascript/

69/137

11/15/2016

JavaScriptforSheridanStudents

<exercisessection='5.5'>
1.Finishthatponggame!
2.Foranextrachallenge,tryabrickbreakergamelikebreakoutorarkanoidaswell.

</exercises>

http://profsamscott.com/javascript/

70/137

11/15/2016

JavaScriptforSheridanStudents

6.CustomObjects
Throughoutthiscourse,youhavebeenusingobjectsinyourprograms(e.g.thedocumentobject)butyouhave
notbeenprogramminginanobjectorientedmanner.
Javascriptsupportsmanyprogrammingparadigms.Itsupportsimperaveprogrammingbylengyouplace
JavaScriptstatementsanywhereyouwantonapage.Thesestatementsareexecutedintheordertheyare
encountered(fromtoptoboom)whenthepageisrstloaded.Italsosupportsproceduralprogrammingby
lengyoudeclarefunconsthatcanbeexecutedoverandoveragainasnecessary.Anditsupportsfunconal
programmingthroughitssupportforrstclassfuncons.
Inthischapter,youwilllearnsomeofthewaysinwhichJavaScriptalsosupportsobjectorientedprogramming,
allowingyoutocreateyourownobjectswithwhateverinstancevariables(elds)ormethodsyouwish.
Onecaveatbeforewebegin:TheJavaScriptapproachtoobjectorientedprogrammingisquitedierentfrom
Javaandalmosteveryotherlanguage.Afulldiscussionisbeyondthescopeofthiscourse,butyoucanread
moreinIntroducontoObjectOrientedJavaScript[hps://developer.mozilla.org/en
US/docs/Web/JavaScript/Introducon_to_ObjectOriented_JavaScript]ontheMozillaDeveloperNetwork.

6.1SomeImportantFacts
JavaConnection
ClassesandObjects.JavaScriptletsyou
createobjectsbutdoesnotletyoudene
anyclasses.

InJava,ifyouwanttocreateanobject,youdeneaclassto
useasablueprintandthencreateobjectsusingit.In
JavaScriptthereisnosuchthingasaclass,andthereare
manydierentwaystocreateanewobject.We'lllookat
twosimplewaysinthenextsecon,butrstherearesome
importantremindersabouthowJavaScriptobjectswork.

6.1.1ObjectNotation
Asyouhavealreadyseen,inJavaScript,youcanaccessanobjectusingthedotoperatororbyusingassociave
arraybrackets.
Forexample:document.forms.["myForm"]isthesameasdocument.forms.myForm,and
document["getElementById"]("test1")isthesameasdocument.getElementById("test1")
Thiswillbetruefortheobjectsyoucreateaswell.

6.1.2FlexibleObjects
InJava,theclasscreatestheblueprintforanobjectanditcannotbemodiedatrunme.Youcannotaddor
removeinstancevariablesormethodsaercreanganobject.

http://profsamscott.com/javascript/

71/137

11/15/2016

JavaScriptforSheridanStudents

JavaScriptobjectsaremoreexible.Youcanaddaeldtoan
exisngobjectsimplybyassigningsomethingtoaneweld
name.Youcanalsoaddanewmethodsimplybyassigninga
funcontoaneweldname.

JavaConnection
FlexibleObjects.InJavaScript,the
structureofanobjectcanbechangedaer
itiscreated.InJava,youcan'tdothat.

TerminologyNote:AJavaScriptobjectisanassociavearray
linkingkeynamestovalues.Eachkeynameisaninstance
variableofthatobject.Asyoulearnedintheprevious
chapter,funconscanbeusedasvaluesaswell.WhenanObject'sinstancevariablecontainsafuncon,wecall
itamethod.Otherwise,wecallitaeld.
DoItYourself
InaJavaScriptconsole,trythefollowing:
document.myVariable=45;
document.myMethod=function(){alert("hi");}
Youhavejustaddedaneweldandanewmethodtothedocumentobject.Youcanaccessthemlike
this:
alert(document.myVariable);//accessthenewfield
document.myMethod();//callthenewmethod

Youcanalsodeleteaeldfromanobjectusingthedeleteoperator.Thisoperatorcanbeusedtoremoveany
variablefromthecurrentcontext.
DoItYourself
InthesameJavaScriptconsolefromthelastDoitYourselfbox,removethenewmethodandeldlikethis:
delete(document.myVariable);
delete(document.myMethod);
Nowyoushouldnotbeabletoaccessthiseldandmethodanymore.

6.1.3SilentErrors
NowyouareinaposiontounderstandsomeofJavaScriptsnotorioussilenterrors.
DoItYourself
InaJavaScriptconsoleforthistextbook,trythefollowing:
document.getElementById("test10").style.color="blue";
document.getElementById("test10").innerHtml="hi!";
Notethattherstlineworkedbuttheseconddidn't(thetextisbluenow,butthecontentshavenot
changed).
Whatwentwrong?Ifyou'renotsure,trythefollowingintheJavaScriptconsole:
document.getElementById("test10").innerHtml

http://profsamscott.com/javascript/

72/137

11/15/2016

JavaScriptforSheridanStudents

ThisisanexampleofaverycommonerrorinJavaScript:TheprogrammerwantstoputamessageintoaDOM
NodeandsheretrievedtheElementobjectcorrectlyusinggetElementByIdbutshegotthecasewrongon
theeldname.InsteadofinnerHTMLshetypedinnerHtml.Butratherthanthrowanerror,JavaScriptjust
addedaneweldtotheElementobject(calledinnerHtml)andassignedthestringvalue"hi"toit.
ThisisaprimeexampleofhowJavaScriptmakesatradeobetweenexibilityandeaseofdebugging.

6.2CreatingObjectsfromScratch
Withthepreliminariesoutoftheway,wecantalkaboutobjectcreaon.Therstwaytocreateanobjectisto
simplycreateanemptyObjectandthenaddeldsandmethodstoitonebyone.JavaScriptcontainsabuiltin
constructorfunconcalledObjectthatletsyoudojustthat.
DoItYourself
InaJavaScriptconsole,createanewobjectandassignittoavariablelikethis:
varperson=newObject();
Ifyouexamineperson(type"person"intheconsoleandopentheObjectthatisreturned)youwillsee
thatitsanobjectwithnocontents.Toaddelds,youcandothefollowing:
person.firstName="Joe";
person.lastName="Smith";
person.fullName=function(){
returnthis.firstName+""+this.lastName;
}

<exercisessection='6.2'>
1.TODOexercisesgohere!

</exercises>

6.3CreatingObjectsWithLiterals
Aliteralisavaluethatishardcodedintoaprogram.Wheneveryouuseanumberlike4or5.43,aquoted
sringlike"hello",aBooleanvalueliketrue,orabracketedarraylike[23,52,3]inaprogram,youare
usingaliteral.Likemostlanguages,JavaScriptsupportsNumber,String,Boolean,andArrayliterals.
Youalreadyknowthatunlikemanylanguages,JavaScriptsupportsfunconliteralssoitshouldcomeasnogreat
shockthat,alsounlikemanylanguages,JavaScriptsupportsObjectliteralstoo.
AnObjectliteralmustbeenclosedincurlybrackets.Insidethecurlybrackets,youputacommaseparatedlistof
keysandvalues(remember,inJavaScriptanObjectisjustanassociavearray).Theeldnamesmustbe
unquotedandthevaluescanbeproperlyformaedliterals(includingfunconandobjectliterals)ortheycan
bepreviouslydenedvariables.
SothisisanotherwayofcreanganobjectinJavaScript.

http://profsamscott.com/javascript/

73/137

11/15/2016

JavaScriptforSheridanStudents

DoItYourself
InaJavaScriptconsole,trythefollowing:
varx={name:"Joe",age:40,male:true};
vary={person:x,numPeople:1};
varz={person1:{name:"Jane",age:31},person2:{name:"Ruth",age:25}};
Nowtypex,y,andzandtakealookatthecontentsofeachobject.Isitwhatyouexpected?
Trytypingx.age,y.personandz.person1.Isthereturnvaluewhatyouexpected?

DoItYourself
Hereisanotherexample,thismeincludingamethodandwithsomenicerindenng.Pasteitintoa
JavaScriptconsole:
varcircle={
radius:10,
getArea:function(){
returnMath.PI*this.radius*this.radius;
}
};
Nowcallthecircleobject'sgetAreamethod.

<exercisessection='6.3'>
1.TODOexercisesgohere!

</exercises>

6.4CreatingObjectsWithConstructors
HereisthecodeforaCircleclassinJava(notJavaScript!)alongwithamainmethodthatcreatestwocirclesand
printstheirinformaontothescreen.Takeamomenttoreviewthiscodeandremindyourselfwhateachlineis
for.Thenumbersarenotpartofthecode,ofcourse,theyarejusttheresowecantalkaboutthedierences
betweenJavaScriptandJava.
publicclassCircle{1
publicdoubleradius;3
publicCircle(intradius){2
this.radius=radius;
}
publicdoublearea(){4
returnMath.PI*radius*radius;
}
publicstaticvoidmain(String[]args){5
http://profsamscott.com/javascript/

74/137

11/15/2016

JavaScriptforSheridanStudents

Circlec=newCircle(10);
Circlec2=newCircle(5);
System.out.println("Circle1Radius:"+c.radius);
System.out.println("Circle2Area:"+c2.area());
}
}

HereissomeequivalentcodeinJavaScript,againwithnumberstohelpthecomparisontoJava.
functionCircle(r){2
this.radius=r;3
this.area=function(){4
returnMath.PI*this.radius*this.radius;
}
}
c=newCircle(10);5
c2=newCircle(5);
alert("Circle1Radius:"+c.radius);
alert("Circle2Area:"+c2.area());
DoItYourself
YouwillndtheabovecodeintheexamplepackinthelesCircle.javaandCircle.html.Runboth
programstoverifythattheydomoreorlessthesamething.(NotethatCircle.htmlusesjQueryto
encapsulateeverythingproperlyandoutputstoa<p>elementratherthantoanalertbox,butotherthan
thatitisthesameasabove.)

6.4.1ClassesinJavaScript
http://profsamscott.com/javascript/

75/137

11/15/2016

JavaScriptforSheridanStudents

JavaConnection
Classes.Javausesclassestocreateobjects.
JavaScriptdoesnot.

InJava,objectcreaonandinheritancearebasedonclasses
(labeled1intheexamplesabove).Youdeneaclassasa
blueprintforanobjectandthenyoucancreatemulple
objectsofthattype.

JavaScriptdoesnotuseclassestodeneobjects.Thatiswhy
theJavaScriptexampleabovedoesnothavea1labelonitanywhere.

6.4.2ConstructorsinJavaScript
InJava,constructors(labeled2intheexamplesabove)arespecialmethodsdenedinsideaclass.Theirjobis
tocreateanobject,executesomeinializaoncode,andthenreturntheobjectcreated.
InJavaScript,anyfunconcanbeusedasaconstructor.In
theaboveexample,thefunconlabeled2isbeingusedas
aconstructor.Nocethatthefunconnameiscapitalized
thisistoindicateitsintendeduseasaconstructor,inmuch
thesamewaythatJavaprogrammerscapitalizethenamesof
classes.

JavaConnection
Constructors.Javaconstructorsarespecial
methodsinsideaclassdenion.Any
JavaScriptfunconcanbeusedasa
constructor.

6.4.3InstanceVariables(Fields)
InJava,instancevariables(labeled3intheexamplesabove)aredeclaredinthebodyoftheclass,outsideof
anymethod.
JavaConnection
InstanceVariables.Javainstancevariables
havetobedeclared.JavaScriptinstance
variablesarenotexplicitlydeclared.

InJavaScript,variablesdonothavetobedeclared.Ifyou
wanttocreateaninstancevariableinaconstructorfuncon,
youusethethiskeywordtoindicatethatthevariableisa
eldoftheobjectcreatedwhentheconstructorfunconis
called.

6.4.4InstanceMethods
InJava,instancemethods(labeled4intheexamplesabove)arealsodeclaredinthebodyoftheclass.These
methodscanaccesstheinstancevariablesoftheobject.
InJavaScript,instancemethodsareactuallyinstance
variablesthatcontainafuncon.(RecallthatinJavaScript,
funconsarevaluesthatcanbeassignedtovariables.)Any
funcondeclaredusingthethiskeyword,liketheone
labeled4,canaccesstheotherinstancevariablesofthe
objectusingthethiskeyword.

JavaConnection
InstanceMethods.Javamakesadisncon
betweenmethodsandvariables.JavaScript
supportsrstclassfunconssoitdoesnot
needtomakethatdisncon.

6.4.5CreatingandUsingObjects
InJava,youcreateobjectsbycallingtheirconstructorswiththenewkeyword,andyouaccesstheirpublicelds
andmethodswiththedotoperator(labeled5intheexamplesabove).Thevariablesthatstoreobjects
actuallystorereferencestothoseobjectsratherthantheobjectsthemselves.Thestatementstocreateand
accessobjectsmustbecontainedwithinamethodofsomekind.IntheJavaexampleabove,Ihavedeneda
mainmethodsothattheobjectswillbecreatedatrunme.
http://profsamscott.com/javascript/

76/137

11/15/2016

JavaScriptforSheridanStudents

JavaScriptworksjustlikeJavaforcreangandaccessingobjects.TheonlydierenceisthatsinceJavaScript
allowsimperaveprogramming,youdonthavetoputthestatementsthatcreateandaccesstheobjectsinside
amethod,thoughitisoengoodpraccetodoso.
DoItYourself
LoadCircle.htmlfromtheexamplepackintoabrowser,opentheJavaScriptconsole,createathirdcircle
ofradius52.3anddisplayitsarea.

6.4.6InformationHiding
InJava,youcancontrolaccesstoyourvariablesandmethodsusingkeywordslikeprivateandprotected.This
allowsyoutohidesomeofthedetailsoftheinternalworkingsofyourclass.
JavaConnection
InformaonHiding.InJavayoucanmark
variableswiththeprivatekeywordto
limitoutsideaccess.InJavaScriptany
variableyoudeclareinsideafuncon
(withoutthethiskeyword)isprivate.

InJavaScript,youcanalsohaveprivatevariablesinan
object.Youcandothisbydeclaringvariablesormethodsina
constructorfunconwithoutusingthethiskeyword.These
variablesandmethodsareprivateandcanbeaccessedonly
withintheobject.
Heresanexample,fromCircle2.htmlintheexamplepack
(seeCircle2.javafortheJavaequivalent).

functionCircle(r){
varradius=r;//PRIVATEVARIABLE.ONEPEROBJECTCREATED.
this.getRadius=function(){//GETTERMETHODFORPRIVATEVARIABLE.
returnradius;
};
this.area=function(){
returnMath.PI*radius*radius;
};
}
JavaScripthasanequivalenttoJavasprivateandpublic,butwhatabouttheothertwoaccesslevels,protected
andpackage?Theselevelsconcernaccessbysubclassesandclassesinthesamepackage.SinceJavaScript
doesnthaveclassesorpackages,thesetwoaccesslevelsarenotnecessary.

6.4.7Inheritance
JavaScriptdoesnotdeneobjectsusingclasses,whichmeansthatinheritancehastoworkinaverydierent
way.
InJava(andmostotherobjectorientedlanguagesinwideuse)youdeneaclasswhichcaninheriteldsand
methodsfromitssuperclasses.JavaScriptismuchmoreexible.Youcancreateobjectsusingaconstructor
funcon,andthentweakthemtoaddorremoveeldsasyouwish.
InJavaScript,anobjectisalsoassociatedwithaprototypethatcanbeusedtocreatesimilarobjects.Prototypes
canbeusedtoimplementaninheritancemechanismandthecorrectuseofprototypeswhencreangobjects
canleadtoamoreecientimplementaonofyourcode.

http://profsamscott.com/javascript/

77/137

11/15/2016

JavaScriptforSheridanStudents

Prototypesarewellbeyondthescopeofthistextbook,butit
ishelpfultoknowforfuturereferencethatyoucan
implementaformofinheritanceinJavaScriptandthatyou
canmakeobjectorientedimplementaonsmoreecient
usingprototypes.(InChromesJavaScriptconsole,whenyou
examineanobject,youwillnoceitsprototypeinformaon
storedinthe__proto__eld.)

http://profsamscott.com/javascript/

JavaConnection
Inheritance.Javausesclassbased
inheritance.JavaScriptusesprototype
chainingtoimplementinheritance.

78/137

11/15/2016

JavaScriptforSheridanStudents

7.ProgrammingChallenges
Atthispoint,youhaveallthetoolsyouneedtocreateafullyfunconing,clientsidewebapp.Herearesome
ideasforminiprojectsthatwillgiveyoualotofgreatpracce.Ineachcase,theinstruconsaredisplayedin
stepbystepstagessoyoucandoalloftheproject,orjustpartofit.

7.1DiceHistogram
Thiswebappcouldbeusedbyelementaryorsecondaryschoolstudentstoexploretheprobabiliesinvolvedin
rollingapairofdice.

1.Createawebappwithonebuon.Whentheuserpressesthebuon,itshould"roll"twodice(i.e.
generaterandomnumbersfrom1to6)anddisplaytheresultofeachdiethepage.(Hint:Use
Math.floor(Math.random()*6+1)tosimulateeachdie.)
2.Nowmodifyyourwebappsothatitalsodisplaysahistogramfortheuserliketheoneintheexample
above,showingthenumberofmeseachtotalfrom2to12hasbeenrolled.Youcanusethele
http://profsamscott.com/javascript/

79/137

11/15/2016

JavaScriptforSheridanStudents

images/six_sided_die.pngfromintheexamplepacktoshowthenumberofrollsgraphically.Youshould
alsoshowhowmanyrollstherehavebeenintotal.(Hint:Useatable,altertheinnerHTMLofthe
appropriate<td>elementforeachroll).
3.Adda"clear"buontoclearthehistogramcontents.
4.Add"roll10mes"and"roll50mes"buons.
5.Addanumberinputelementwithanotherbuonsothattheycanchoosehowmanymestoroll.

7.2TicTacToe
WhodoesntloveTicTacToe?Inthisprojectyouwilldevelopawebappthatcouldrunonadesktoporamobile
phone.
1.Createawebappthatshowsa3x3grid.Whentheuser
clicksonagridsquare,itshouldplaceanXinthat
square.Makethetotalgridwidthlessthan320pixelsso
itlooksgoodonamobilephone(also,seethep
below).
2.Alternateturns.TherstclickshouldshowanX,then
nextshouldshowanO,thenextanX,andsoon.Display
whoseturnitisinamessageunderthegrid.
3.Addcodetomakesurethegridsquareisemptybefore
youallowsomeonetoplaceanXorO.Popupanerror
messageiftheytrytoplaceapieceinanoccupiedspot.
4.Addaresetbuonthatclearsthegrid.
5.Addcodetodetectwhentheboardisfullandnofythe
playersofaegame.
6.Addcodetodetectawinanddisplayawinmessage.
(Youmightwanttouseanarrayforthis,thoughyou
dontneedone.Ifyouwanttouseanarray,check
Chapter7rst.)
Tip:Mobilephonebrowsersoendefaulttoareallywidescreenandzoomout.Iftheydothat,itwillmakeyour
TicTacToeapphardtouse,eventhoughitissizedforaphone.Tostopmobilebrowsersfromzoomingout,you
willneedtoincludethefollowingtaginthe<head>seconofyourHTML:
<metaname="viewport"content="width=devicewidth">

7.3ImageMagniier
Manyshoppingsitesletyourolloveranimagetoseeamagniedversionofthatimageappearbesideit.Inthe
websitepicturedhere,astheusermousesoverthemainimagethedetailappearsinawindowbesideit.A
smallbrightenedboxonthemainimagefollowsthecursortoshowwhatisbeingdisplayedinthedetailimage.

http://profsamscott.com/javascript/

80/137

11/15/2016

JavaScriptforSheridanStudents

Implemennganimagemagnierlikethisis
nottrivialbutthebasictrickistohavetwo
imagesonethatissmalltoserverasthe
mainimageandonethatisaverylarge
versionofthesmallerimage.Thislargeimage
canbesetasthebackgroundofa<div>or
similarelementusingCSSrulesandthen
changingtheposionofthatbackground(also
speciedinCSSproperes)canbechangedin
responsetomousemovementsoverthe
originalimage.The<div>elementwillact
likea"window"ontheimage,soifyou
posiontheimagewithinthewindowusing
topandlecoordinateswhicharenegave,onlythepartoftheimagethatwouldappearunderthe<div>
elementwillshowthroughthe"window".Gengthisrightmighttakesomemath!
Ifyoucangetthemovementanddisplayoftheimageright,therearealsolotsofotherdetailstoworryabout
includinghiding/showingthedetailimagewhentheusermousesinandoutanddecidingwhattodowhenthe
userapproachestheveryedgeoftheoriginalimage.
Theimagesshownaboveareavailableinthemarsrover.zipleintheexamplepack.

7.4Pong
MakeasimpleliveacongameusingtheHTML5Canvas.Seetheseconsonanimaon,gamecontrol,and
canvasdrawingforideasonhowtomakethiswork.
Ifyouwanttoprogramgames,it'sbestto
startwithrecreangsomethingrelavely
simple,likeyourownversionofpong.Other
seeminglysimplegameslikeFlappyBird,
SpaceInvadersorPacManaresurprisingly
challengingfornewprogrammers,but
denitelyworthashotifthissortof
programmingappealstoyou.
OfcoursetherearelotsofJavaScriptgames
alreadyonthewebwithcodethatyoucan
lookat,butmanyofthesegamesaremade
withframeworksoruseadvanced
programmingtechniques.ToseeaJavaScript
gamewithcodethatmightbeabitmore
understandable,takealookatTwiyBird
[hp://www
acad.sheridanc.on.ca/sta/scosam/twiybird/],thisauthor'sversionofFlappyBird.
ForsomesoundsandimagestohelpyoucreateagamelikePong,getthelepong.zipfromtheexamplepack.

http://profsamscott.com/javascript/

81/137

11/15/2016

JavaScriptforSheridanStudents

8.ServerIndependentWebApps
Younowhavealmosthaveallthetoolsyouneedtocreateatrueclientsidewebapp.Youcandenean
interfaceinHTMLandCSS,usingformelementsifrequired,andthenaddfunconalitytoitinJavaScript.But
thesewebappsareslldependentonaconnecontotheserver.Theyarenotindependentinthewaythat
standaloneappsare.
1.Webappsdonthaveanyleaccess.Thismeansyoucantopenaleontheclientmachineandstoredata
fortheusertoaccessthenextmetheyrunyourapp.TheonlyalternavebeforeHTML5wastostorethe
usersdataontheserverandretrieveitwhentheyreturn,makingtheappdependentonaconneconto
theserver.
2.Webappshavetobereloadedeachmethebrowserisrestarted.BeforeHTML5thismeantthatifthe
userlosestheirinternetconnecon,orifyourservergoesdown,theywillnotbeabletoloadandrunyour
app.
JavaConnection
FileAccess.Javaapplicaonshave
completeaccesstothemachinetheyare
runningon.Theycanreadandwritetoles
anddatabases.BecauseJavaScript
programsrunonwebpages,itwouldbe
toodangeroustogivethemthiskindof
accesstothelocalmachinesomeevil
personcouldembedJavaScriptintoaweb
pagetowipeouttheusersharddrive!

ButHTML5ischangingallthat.Thenewwebstoragesystem
inHTML5providesaneasywaytostoredataontheclients
machineeithertemporarilyorpermanently,andthenew
appcacheallowsauserto"reload"awebapptheyhave
visitedbeforeevenwhenthereisnoconnecontothe
server.Thesetwonewcapabiliesallowustocreatefully
funconalappsinawebbrowserthatareindependentof
theserver.

8.1WebStorage
Webdevelopersoenwanttheirsitestorememberusers,maintaintheirsengsbetweenpageloads,andeven
keeplocalcopiesofthedatatheuserenteredforthenextmetheyvisit.Inthepast,thiswasdonebyseng
HTTPCookiesontheusersharddrive.
Cookiesaresmallpiecesofdata(maximum4KB)thatarestoredontheclientmachinebythebrowser,linkedto
aparcularURL.TheyareaccessiblethroughJavaScriptandareautomacallysenttotheserveralongwith
everyHTTPrequest.Theyaretypicallyusedtostoreauniqueidenerforeachuserorsession,andthenthe
bulkofausersdataisstoredontheserversideusingthisuniqueidener.ThisishowsiteslikeFacebook
[hp://www.facebook.com]recognizeyouwhenyoureturn.
Asanalternavetocookiesandserversidedatabases,HTML5oerstwonewJavaScriptobjects:
localStorageforlongtermdatastorageandsessionStoragefortemporarydatastorage.Eachdomain
namegetsasinglelocalStorageobjectinthebrowseraswellasasessionStorageobjectforeachopen
http://profsamscott.com/javascript/

82/137

11/15/2016

JavaScriptforSheridanStudents

tab.Theseobjectscanstoreupto10MBofdata,andthisdataisstoredontheclient.Itisnotautomacallysent
totheserverthewaythatcookiesare.ThedatainsessionStorageisautomacallydeletedwhenthe
browsertabisclosed,butthedatainlocalStorageisonlyeverdeletedwhenaJavaScriptprogramdecidesto
deleteit,orwhentheuserclearstheirbrowserhistory.Otherwise,itspermanent.
DoItYourself
GotoasitelikeGoogleorFacebookinChrome.PressF12andgototheresourcestabtoseewhatthese
siteshaveputinyoursessionStorageandlocalStorageobjects.
NowgototheJavaScriptconsoleandtypethefollowingtoseethesameinformaon:
sessionStorage
localStorage

ThesessionStorageandlocalStorageobjectsworkjustlikeanyotherobject,exceptthattheycanonly
storestringdata.Eachitemofdataisstoredunderadened"key",andisaccessedthesamewayasanyother
object,withsquarebracketnotaonordotnotaon.
DoItYourself
OnthesamewebyouusedforthelastDIYbox,gototheJavaScriptconsoleandtypethefollowing:
localStorage["name"]="Bob";
localStorage.number=22342;
Nowtypethefollowingtoseewhatyouentered.
localStoragelocalStorage.name;
localStorage["number"];
Nocethattheresponsefromthelastlineisinquotes.Thismeansthatthenumberyouenteredwas
convertedtoastringbeforebeingstored.
NowrepeattheabovecommandswithsessionStorage.Thenrestartthebrowser,gobacktothepage
youwereonandcheckthelocalStorageandsessionStorageobjectstoseewhatdataremains.

Anaside:IntheDIYboxabove,youmightnocethatweare
addingeldscallednameandnumbertothe
localStorageobjectonthey.Thefactthatvariables
donthavetobedeclaredinJavaScript(eventhoughyou
shouldalwaysdeclarethem!)extendstoobjecteldsas
well.Youcanaddaeldtoanyobjectjustbyassigning
somethingtoit.Youcanevenaddneweldstothe
documentobjectifyouwant,asshownbelow.
document.newField=12;
BothwebstorageobjectsalsocontainaremoveItemthat
canbeusedtoremoveasingleeldandaclearmethod
thatcanbeusedtoremovealleldsatonce.

http://profsamscott.com/javascript/

JavaConnection
FlexibleObjects.InJava,onceanobjectis
created,youcantaddanyneweldsor
methods.InJavaScript,anyobjectcanbe
extendedwithneweldsandmethodsany
me.ThismakesJavaScriptveryexible,
butalsocreatessomedebugging
nightmares.Ifyoumisspellaeldnamein
Java,yougetasyntaxerror.Butdothe
sameinJavaScriptandyougetaneweld
addedtotheobject!

83/137

11/15/2016

JavaScriptforSheridanStudents

DoItYourself
GobacktothepagefromthelastDIYboxandopentheJavaScriptconsole.Typethefollowing:
localStorage.removeItem("name")
localStorage
NocethatthenameeldisnowgonefromthelocalStorageobject.Nowtrythis:
localStorage.clear()
localStorage
NowthelocalStorageobjectshouldbecompletelyempty.

8.1.1InitializingWebStorage
Supposeyouarecounnghowmanymesauservisitsyoursite.Ontheusersrstvisit,youwillhavetocreate
thecounteriteminlocalStorageandsetitto1.Onsubsequentvisits,youshouldnotrecreatethecounter.
Instead,youshouldaccessitandincrementit.Soyouneedawaytogureoutiftheuserhasbeenherebefore.
ThecodebelowaccomplishesthisbytakingadvantageofthefactJavaScripttreatsthespecialvalueundefined
thesameasfalseinaBooleanexpression,andeverythingelse(otherthan0andtheemptystring)astrue.
Soiftheuserhasnotbeenherebefore,theelseclausewillinializethecounter.Otherwise,thecounterwillbe
incremented.NocealsothemandatoryuseofparseInthere.WhatwouldhappenifparseIntwasleout?
if(localStorage.counter)
localStorage.counter=parseInt(localStorage.counter)+1;
else
localStorage.counter=1;
DoItYourself
LoadupwebStorageDemo.htmlfromtheexamplepacktoseetheabovecodeinacon.Hitreloada
coupleofmestoseethecountersmove.Thenopenthepageagaininanothertabtoseewhathappens
tothecounters.
ThiswebpageuseslocalStoragetocountthetotalnumberofvisitsandsessionStoragetocount
thenumberofreturnvisitsthissession.Ifyouopenthepageinanewtab,thesessioncountwillreset,
butevenifyouclosethebrowserandreopenit,thetotalcountwillberemembered.
Notetheuseoftheonloadeventinthe<body>element.Thismakessurethatthecount()funconwill
runonceoneachpageload,butnotunlaertheenre<body>isloaded.

8.1.2AdviceonSharingWebStorage
TheonedrawbacktolocalStorageisthatifyoursiteisonadomainthathasmulpleusersaccounts(like
mobile.sheridanc.on.ca),somebodyelseswebappcouldaccess,clear,andoverwriteyour
localStoragedata.Thereisnothingthatcanbedonetoavoidthisotherthanbuyingyourownprivate
domain,butfailingthat,itsagoodideatonameyourdatainsuchawaythatislikelytobeunique.
Forexample

http://profsamscott.com/javascript/

84/137

11/15/2016

JavaScriptforSheridanStudents

localStorage["App2938475SamScott_vehicle"]="Aveo";
islesslikelytobetamperedwiththan
localStorage["vehicle"]="Aveo";

<exercisessection='8.1.2'>
1.Writeasimplestandalonewebappwithtwopages.
Onpageone,havetheuserllinaformwiththeir
nameandthecolorshirttheyarewearing.Ifthey
havebeenherebefore,youshouldllintheirname
automacally.StoretheirnameinlocalStorage
andtheirshirtcolorinsessionStorage.Providea
linktopage2.Onpage2,youshouldgreettheuser
bynameandtellthemwhetheryouliketheirshirtor
not,basedonthecolortheyenteredlastme(e.g.
writeanifstatementthatonlysaysyouliketheir
shirtiftheysayitwasred).Providealinkbackto
page1.
2.Writeamobile"memopad"applicaon.This
applicaonshouldallowtheusertotypeintoatext
area.ThetextshouldbestoredinlocalStorage
anddisplayedwhentheyreturnforthemtoreador
modify.Makeitlookprofessional(likearealappyou
mightseeonamobilephone).
3.Asanaddedchallengetoqueson2,allow50pagesofmemostoragewithbuonsorotherform
elementstoallowthemtoipthroughthepages.

</exercises>

8.2TheAppCache
WithlocalStorageyoucancreateastandalonewebapplikethemobilememopadabove,butyouresll
dependentontheserverbecauseeachmetheuserwantstoloadyourapp,theyhavetosendanHTTP
requestanddownloaditagain.Itwouldbemuchbeeriftheappcouldbestoredlocallylikeanaveapp.And
thatsexactlywhattheHTML5appcachedoes.
Tousetheappcache,youneedtwothings:
1.Anappcache"manifest"le,and
2.2.Amanifestaributeonthe<html>tagofthesitesfrontpage.
Wellcovertheseinreverseorder.

http://profsamscott.com/javascript/

85/137

11/15/2016

JavaScriptforSheridanStudents

8.2.1ThemanifestAttribute
Themanifestaributeispartofthe<html>tag.Itspeciesthelocaonofamanifestle,likeso:
<htmlmanifest="myManifest.appcache">
(yourpagegoeshere)
</html>
Thenameofthemanifestledoesntreallymaer,butthe.appcacheleextensionisrecommendedto
ensurethattheservermarksitwiththeMIMEType"text/cachemanifest".Theusualrulesapplyfor
specifyingthelepath(sameastherulesforthehreforsrcaribute).Soyoucouldalsoputthe.appcache
leinitsownfolderaslongasyouspecifythepathtoit.(Intheaboveexample,themanifestleisinthesame
folderastheHTMLlethatreferencesit.)
ThepresenceofamanifestaributeinanHTMLlewillcausethemanifestletobeautomacallystored
locallytobeaccessedwhentheuserisoine.Thecontentsofthemanifestlespecifywhichotherlesshould
alsobestoredlocallyalongwiththemanifest.
Ifyourwebappusestheappcache,itwillonlybeloadedoneme.Futurevisitstothepagewillloadthe
remotemanifestleandcheckitagainstthelocallystoredcopy.Iftheymatch,noneofthecachedleswillbe
reloaded.Localcopieswillbeusedinstead.Sousingtheappcachealsosavesbandwidth.Butthemainpointis
thatifthereisnoconneconortheserverdoesnotrespond,theappwillsllloadusingcachedcopiesofallthe
les.

8.2.2TheManifestFile
Hereisthecontentofasimplecachemanifestle:
CACHEMANIFEST
#May29,2012,6:34pm
js/memo.js
css/memo.css
images/116_2.jpg
Therstlineisrequired.Thelinethatstartswitha#characterisjustacomment.Theremaininglinesspecify
whichlesonthesitearetobecached(alongwiththeHTMLlethatloadedthismanifest).Thesearelepaths
relavetothelocaonofthemanifestle.
YoucanalsoincludeaNETWORKsecon.Thisseconspecieslesthatmustbeloadedfreshfromtheserver
everyme.AndyoucanalsoincludeaFALLBACKseconthatspeciesaletobeloadedifapageisnot
accessible.Youcanreadmoreabouttheseoponsonthew3SchoolsHTML5ApplicaonCachepage.
DoItYourself
Youcanonlytesttheappcacheifyouhaveaccesstoawebservereitheraremotewebserverona
dierentmachine,oradevelopmentwebserverlikeWampServerorXAMPP
[hp://www.apachefriends.org/en/xamppwindows.html]runningonyourownmachine.
Ifyouhaveaserver,uploadthelesintheappCacheExperimentsfolderoftheexamplepackandtry
themout.Tryaccessingthemeachwhileonline,thenseveryournetworkconneconandtryagain.Tryto
gureoutwhyeachoneloadsordoesnotload.

http://profsamscott.com/javascript/

86/137

11/15/2016

JavaScriptforSheridanStudents

Important:Rememberthatreturninguserscheckthemanifestrstandifithasnotchanged,theywillloadlocal
copiesofthelesonly.Sowhenyouupdateyoursite,itiscrucialthatyouupdateyourmanifestleaswell,
evenifallthelenamesarethesame,youmustatleastchangeonecommentlineinthemanifestle.Ifyou
dontdothis,returninguserswillnotseetheupdatedsite.

<exercisessection='8.2.2'>
1.Updateyourtwopageappfromsecon9.1tousetheappcachesothatitsllloadsevenifthe
userisoline.
2.Updateyourmemopadappsoitworksolineaswell.

</exercises>

http://profsamscott.com/javascript/

87/137

11/15/2016

JavaScriptforSheridanStudents

9.AdvancedDOMManipulation
It'smetogetmoreseriousabouttheHTMLDOM.UpunlnowyouhavenavigatedtheDOMbyusing
methodslikegetElementByIdorquerySelectorAlltopulloutspecicelements.Youhavealsomade
changestotheDOMbyaccessinganode'sinnerHTMLproperty,orbychangingaributesandCSSstyle
properes.Thesetechniquescangetyoualongway,buttherewillbemeswhenyouwillwanttonavigateand
manipulatetheDOMinmoresophiscatedways.
Forexample,thistextbookusesJavaScripttobuildandinsertitsowncontentsseconaeritisloaded(check
thepagesourceandyouwillnotseeatableofcontentsthere).ThiscouldbedonebygengtheinnerHTMLof
the<body>andthenbuildingandinsernganewsubstringforthecontentssecon,butitwouldbetrickyto
reliablyndtherightplaceinthestringfortheinseron,andbuildingsuchalongHTMLstringwouldbetedious
andpronetoerror.It'seasiertodoitbycreangnewDOMnodesfromscratchandusingtheDOM
appendChildandinsertBeforemethods.You'lllearnhowtodothatinthischapter.
ThistextbookalsointelligentlyresizesimagesusingJavaScriptwhenthebrowserwidthchangessothatan
imageisalwayseitheritsoriginalsize,orjustbigenoughtotinsidethe<div>thatcontainsit.Thiswouldbe
verytrickytodousinginnerHTML.It'smucheasiertodowiththetechinquesoftreetraversalyouwilllearnin
thischapter.

9.1TheFullDOM
ConsidertheHTMLsourcebelow(domExample.htmlfromtheexamplepack).
<!DOCTYPEhtml>
<html>
<head>
<title>DOMExample</title>
<metahttpequiv="ContentType"content="text/html;charset=UTF8">
</head>
<body>
<divid="div1">ThisdivhasID"div1"</div>
<div>ThisdivhasnoID</div>
<div>ThisdivhasnoID</div>
</body>
</html>
FollowingtheanalysiswedevelopedinChapter4,weshouldexpecttheDOMforthisdocumenttolooklike
this:

http://profsamscott.com/javascript/

88/137

11/15/2016

JavaScriptforSheridanStudents

Here'saterminologyreminder.Inthepictureabove,thereare10nodes.Therootnodeis<document>.Ithas
twochildrenorchildnodes.Eachofthechildrensharethesameparent.Thelinefromparenttochildmeans
thatthechildiscontainedwithintheparent.Iftherearemanychildren,theyareusuallyshowninorderfrom
letoright.Nodesthatshareaparentaresiblings(thisisthegenderneutraltermfor"brother"or"sister").
Eachofthechildrenofthe<body>nodehastwosiblings.EachNodecontainsaeldforeveryaributeaswell
asstyleandclassNameelds.
Sofar,sogood.ButwewereoversimplifyinginChapter2.Infact,thebrowserwillcreateasurprisingly
complicatedDOMfromthissource,asshownbelow.

ThethingsinquotaonmarksareTextNodes.TheyareadierentkindofobjectfromaregularDOMNode.They
don'thaveaributes,style,classNameorinnerHTML.Rathertheyjusthaveaeldnameddatathatcontainsa
stringrepresenngthetext.Whenthebrowserreadsthedocument,aTextNodewillbecreatedforalmost
everysequenceofcharactersinthedocumentthatisnotenclosedwithin<and>anglebrackets,including
everystretchofwhitespacecharactersatthebeginningorendofaline.Theonlystretchesofwhitespacethat
don'tgetturnedintoTextNodesarethosethatarenotinsideorbetweenthe<head>and<body>tags.

<exercisessection='9.1'>
1.GobacktothehelloWorld.htmllefromtheexamplepackthatwelookedatinChapter2.Lookat
thesourceanduseittodrawthefullDOMtree,includingalltextnodes.

</exercises>

9.2TraversingtheDOM
http://profsamscott.com/javascript/

89/137

11/15/2016

JavaScriptforSheridanStudents

ADOMobjectinJavaScriptisacolleconofNodeobjectsthatarealllinkedtogetherintoatreestructurewith
thedocumentobjectattheroot.InordertoeecvelymanipulatetheDOM,youwillsomemeshaveto
understandthevariouswaystonavigatethisstructure,movingfromnodetonodebyfollowingthelinks.The
followingeldsandmethodswillhelpyouwithtreetraversal.

childNodes:

returnsanarrayofallchildnodesofthecurrentnode

firstChild:

returnstherstchildofthecurrentnode

lastChild:

returnsthelastchildofthecurrentnode

nextSibling:

returnsthesiblingtotherightofthecurrentnode

previousSibling:

returnsthesiblingtotheleofthecurrentnode

data:

ifthisisaTextNode,getsthetext

DoItYourself
LoadupdomExample.htmlfromtheexamplepack,openaJavaScriptconsole,andtrythefollowing.Try
topredicttheresultofeachbeforeyouhitenter:
document.childNodes
document.firstChild
document.lastChild
document.childNodes[0]
document.lastChild.childNodes
Canyouexplaintheresultineachcase?
Nowtrydocument.lastChild.childNodes[0].childNodesandexplaintheresult.
Nowforachallenge.FindasmanywaysasyoucantogettheTextNodefromthesecond<div>element.
RememberthattheTextNodeisaspecialchildnode,notanaributeoravalue(i.e.don'tuse
innerHTML).

http://profsamscott.com/javascript/

90/137

11/15/2016

JavaScriptforSheridanStudents

<exercisessection='9.2'>
1.LoaddomExample.htmlfromtheexamplepackintoabrowser.Usethedocumentobjectalong
withchildNodes,firstChild,lastChildandothereldsyoulearnedaboutintheprevious
secontoverifythatthedocumentdoesindeedhavethestructureshownabove.
2.CheckthestructureyoudrewforhelloWorld.htmlusingthesamemethod.
3.InthelastDIYboxyouwereaskedtondasmanywaysasyoucantogettheTextNodefromthe
second<div>element.HowmanywaysdoyouthinkthereareintotaltodothisusingtheDOM
navigaonmethodsgiveabove?Jusfyyouranswer.

</exercises>

9.3GettingaDOMNodefromanEvent
ThereisanotherwaytogetholdofanodefromtheDOMthatissomemesuseful.Wheneveryouregisteran
eventhandleronanelement(suchasaclickeventhandleronabuonoramouseovereventhandlerona
tableelement)youhavetheoponofusinganeventparameter.
DoItYourself
Trythefollowinginabrowserconsoleforthisbook.ItwillaachaneventhandlertothisDIYbox.
document.getElementById("test5").addEventListener("click",function(event)
{
alert(event.target.innerHTML);
});;
NowclickthisDIYboxtoseetheresult.Dependingonwhereyouclick,youmightgettheenre
innerHTMLforthisDIYboxinanalertwindow,oryoumightjustgetpartofit.Tryclickingindierent
places.Whatdotheresultstellyouabouttheevent.targetobject?

OneveryimportantpieceofinformaonintheeventobjectisthereferencetotheDOMnodethattriggered
it,knownasthe"target".ThisDOMnodeobjectisstoredintheevent.targeteld.Intheaboveexample,
theuserwillgetanalertwiththeinnerHTMLcontentsofthenodethattriggeredtheevent.
InaddiontoinnerHTML,youcouldalsouseanyotherDOMeldsormethodswithevent.target,suchas
event.target.parentNode.innerHTML,event.target.nextSibling.id,andsoon.
Thiscanbeextremelyusefulwhenyouareaddingeventstoapagewithlotsofsimilarelements.Intheabove
example,therecouldbe500dierent<div>elementsonthepage,andwithoutevent.target,youwould
needtowrite500dierenteventhandlers.
ForacompletereferenceontheDOMEventobjectandallitsassociatedeldsandmethods,gotothe
w3Schoolseventobjectreference.

http://profsamscott.com/javascript/

91/137

11/15/2016

JavaScriptforSheridanStudents

<exercisessection='9.3'>
1.TheledomExample2.htmlintheexamplepackshowsasimilarexampletotheoneabove.Add
some<div>elements,eachwithdierentidaributes,andthenmodifytheeventhandlerto
displaytheidaributeoftheelementthatwasclicked.
2.Nowput<inputtype="button"value="ID">besideeachofthe<div>elements,andadd
clickhandlerstoallthesebuonsthatdisplaytheidaributeofthe<div>besidethem(hint:the
<div>foreachbuonshouldbeitspreviousSibling).

</exercises>

9.4UsinginnerHTMLtoModifytheDOM
ThereisonereallyquickwaytomakemodicaonstotheDOM,andthatstoaltertheinnerHTMLofanode.
Youveprobablyalreadyusedthiseldtochangethetextofanelement,butitsactuallymuchmorepowerful
thanthat.WiththeinnerHTMLeldofanode,youcanquicklydeleteallitschildnodes,replacethemwithnew
onesnodes,orappendchildnodestotheendofitsexisnglistofchildnodes.

9.4.1DeleteAllChildNodes
IfyouassignanemptystringtotheinnerHTMLeldofanyDOMnode,youwilldeleteeverynodethatisa
childofthatnode.
DoItYourself
LoaddomExample.htmlfromtheexamplepackintoabrowserandtryoneoftheseintheJavaScript
console.
document.querySelector("body").innerHTML="";
document.lastChild.lastChild.innerHTML="";

Aertheaboveoperaon,theDOMtreelooksliketheonebelow.

http://profsamscott.com/javascript/

92/137

11/15/2016

JavaScriptforSheridanStudents

DoItYourself
YoucanverifytheaboveclaimintheelementstaboftheChromedevelopertools,orbyinspecngthe
documentobject.
Gotopagesource,andcomparethattowhatyouseeintheElementstabinChromesdevelopertools.
Canyouexplainthedierence?

9.4.2ReplaceAllChildNodesWithaTextNode
IfyouputsomeplaintextinthestringyouassigntoinnerHTML,youwillreplaceallthechildrenofthatnode
withasingleTextNode(orinsertanewTextNodeiftheelementhadnochildren).
DoItYourself
TrythefollowingondomExample.html.
document.querySelector("body").children[1].innerHTML="Hello";
Whatdoesthedocumenttreelooklikenow?Nowtrythesamethingwiththe<body>element.Now
whatdoesthetreelooklike?
ComparethepagesourceviewofthedocumenttotheviewofthedocumentintheElementstabofthe
developerconsoleinchrome.Canyouexplainthedierences?

9.4.3ReplaceAllChildNodesWithNewNodes
IntheexamplebelowtheTextNodechildoftheselected<div>elementwillbedeletedandreplacedwithtwo
<p>nodes,eachwiththeirownTextNodecontents.
DoItYourself
TrythefollowinginabrowserconsolefordomExample.htmlfromtheexamplepack.
document.getElementById("div1").innerHTML="<p>Para1</p><p>Para2</p>";
Whatdoesthetreelooklikenow?

ThisistrueDOMmanipulaonbecauseyouhaveremovedoneDOMelementandaddedtwonewonesinits
place.
Thenewtreelookslikethis:

http://profsamscott.com/javascript/

93/137

11/15/2016

JavaScriptforSheridanStudents

9.4.4AppendNewChildNodes
Finally,youcanalwaysappendnewDOMelementsbyusing+=insteadof=.
DoItYourself
TrythefollowinginabrowserconsolefordomExample.htmlfromtheexamplepack,andthendrawthe
resulngDOMtree.
document.lastChild.lastChild.firstChild.nextSibling.innerHTML+="<p>Here
isa<ahref='http://www.google.ca'>link</a></p>";

<exercisessection='9.4.4'>
1.AddabuontodomExample.html.Everymethebuonispressed,addanew<div>elementto
the<body>element,eachwithatextnode"NewDivX"whereXisthenumberofthenewnode,
counngupwardsfrom1.

</exercises>

9.5CreatingNewNodesFromScratch
ManipulangtheinnerHTMLeldisaverypowerfultechniqueforchangingtheHTMLDOMandisoeneasier
thanothermethods.Butitcangetcomplicatedinsomecases,anditisoeneasiertocreatethenewDOM
elementsyourselfratherthantryingtomanipulatetheinnerHTMLstring.
TocreateanewDOMNode,youcanusethedocument.createElementmethod,givingitthetagnameasa
stringparameter.Herearesomeexamples:

http://profsamscott.com/javascript/

94/137

11/15/2016

JavaScriptforSheridanStudents

d=document.createElement("div");

createsanew<div>node
e=document.createElement("a");

createsanew<a>node
e.href="http://www.google.ca";

setsthehrefaributeofthenew<a>node
e.innerHTML="ClickforGoogle."

addsatextnodetothenew<a>node
TheabovecodecreatestwonewDOMNodesandstorestheminvariablesnameddanderespecvely.The
<div>nodeindisempty,butwecanmaketheeelementitschildbyusingtheappendChildmethod.
d.appendChild(e);

addseasthelastchildofd
WhatwenowhaveisalilepieceofaDOM,depictedatright.Atthemomentitis
notincludedinthetree,butwecouldeasilyadditasthelastchildofthebodyofany
documentbyusingappendChildagain,likethis:
document.body.appendChild(d);
Notetheuseofthebodyeldabove.Thisisaspecialeldinthedocumentobject
thattakesyoustraighttothe<body>element.There'salsoaheadeld.

DoItYourself
TryoutthiscodeinaJavaScriptconsolefordomExample.htmlfromtheexamplepack.
vard=document.createElement("div");
vare=document.createElement("a");
e.href="http://www.google.ca";
e.innerHTML="ClickforGoogle.";
d.appendChild(e);
document.body.appendChild(d);
Checkthatthenew<div>isinsertedandthatthelinkworks.Thenusethesamecodetwicetoaddtwo
idencalnewelements.Whatifyouwantedtoadd100newidencalelements?Howcouldyoudoit?

Itisalsopossibletoinsertanewchildanywherewithinthelistofexisngchildnodes,usingtheinsertBefore
method.TheinsertBeforemethodrequiresthreethings:theparentNode,thenewNodetoinsert,andthe
exisngchildoftheparentyouwanttoinsertinfrontof,likethis:
parent.insertBefore(newNode,existingChild);

http://profsamscott.com/javascript/

95/137

11/15/2016

JavaScriptforSheridanStudents

DoItYourself
InaJavaScriptconsolefordomExample.htmlfromtheexamplepack,createthenewnodedasbefore:
vard=document.createElement("div");
vare=document.createElement("a");
e.href="http://www.google.ca";
e.innerHTML="ClickforGoogle.";
d.appendChild(e);
NowgettheseconddivandthebodyelementandstorethemasparentandexistingChild.
varparent=document.body;
varexistingChild=parent.childNodes[3];
Nowinsertthenewnodebeforethesecond<div>usinginsertBefore.
parent.insertBefore(d,existingChild);
Nowfollowtheaboveexampletocreateandinsertanodebetweenthesecondandthird<div>
elements.

<exercisessection='9.5'>
1.GobacktodomExample.htmlfromtheexamplepackandaddanotherbuon.Thisbuonshould
createaDOMfragmentliketheonedescribedabove(a<div>elementcontainingan<a>element
containingaTextNode)andappendittotheendofthe<body>eachmethebuonisclicked.
2.AddanotherbuontodomExample.html.Thisoneshouldaddafourelementcheckerboardtothe
documenteverymeitisclicked.Rememberyoucanusethestyleeldofthenewnodesto
specifystyleproperes,oryoucanusetheclassNameeldstoassignclasses.

</exercises>

9.6RemovingaSingleChildNode
Finally,itisalsopossibletoremoveparcularnodesfromtheDOMusingtheremoveChildmethod.Theonly
trickythingaboutremoveChildisthatyouhavetospecifyareferencetothechildtoremove,likethis:
document.getElementById("body").removeChild(x);
Intheabove,xhastobeavariablecontainingthechildtoremove.Forexample:
x=document.getElementById("body").childNodes[3];
document.getElementById("body").removeChild(x);
Onethingyouoenmightwanttodoisdeleteanelementthattheuserclicksormousesover.Ifyouhavethe
event.targetandyouwanttoremoveit,youcandoitlikethis:
event.target.parentNode.removeChild(event.target);

http://profsamscott.com/javascript/

96/137

11/15/2016

JavaScriptforSheridanStudents

<exercisessection='9.6'>
1.Again,gobacktodomExample.htmlfromtheexamplepackandaddamouseoverhandlerthat
deletesa<div>whenthat<div>ismousedover.
2.Seeifyoucancombinetheabovewiththebuonfromthepreviousexercisethatadds<div>
elements.Whenthisisnished,youshouldbeabletoaddnew<div>elementsbyclickingthe
buon,andthenremovethembymousingoverthem.

</exercises>

http://profsamscott.com/javascript/

97/137

11/15/2016

JavaScriptforSheridanStudents

10.AJAX
ThetextinthischaptermirrorsthetextinChapter12.Inthischapter,youlearntouseAJAXwithrawJavaScript.InChapter12,you
learntouseAJAXwiththejQuerylibraryandyoualsolearnalilebitabouthowtoworkwithXMLdata.

EvenifyoudontknowwhatAJAXis,youhaveexperienceditseects.WhenyoustarttypingintotheGoogle
[hp://www.google.com]searchbox,itdoesnttakelongbeforeyoustartgengsomesuggesonsabout
whattosearchfor.WhenyouviewyourlistoffriendsonFacebook[hp://www.facebook.com],itstartsyou
withasmalllist,andwhenyouscrolldown,itloadssomemoreforyouautomacally(oenwithoutyoueven
nocing).BothoftheseareexamplesofAJAXinacon.
BeforeAJAX,ifyouwantedtogetsomemorecontentfortheuser,youhadtogetthebrowsertoloadand
displayawholenewpage.WithAJAX,youcanlaunchanHTTPrequestfromJavaScript.Thenwhentheresponse
datacomesbackfromtheserver,youcanuseJavaScriptcodetoincorporatethisdataintothepagewithout
reloadingit.

10.1TheBasicIdea
ThetermAJAXwascoinedbyawebdevelopernamedJesseJamesGarre
[hp://www.adapvepath.com/ideas/ajaxnewapproachwebapplicaons]in2005.AJAXisatermforanew
wayofthinkingaboutandmakinguseofacolleconofalreadyexisngtechnologies.It'snotanewlanguageor
libraryorplugin.AJAXstandsforAsynchronousJavaScriptandXML.Letsbreakthisphrasedown.
JavaScript:Youalreadyknowwhatthisis.
Asynchronous:Asynchronousprocessesareprocessesthathappenoutsideoftheregularowoftheprogram.
InAsynchronousprogramming,youmakesomekindofrequestthatwilltakemetocomplete,andthen
connueonwithothertasks.Inmanycasesyoualsospecifyacallbackfuncontobetriggeredwhenthe
asynchronoustaskisnished.YousawsomethingabitlikethiswhenyouusedthesetTimeoutfunconin
Chapter5.Thisfunconstartsamerandthenallowstheapp/pagetoconnuerunningandrespondingtothe
userwhileitwaitsforthemertogoo,atwhichpointthefunconyouspeciedgetscalled.Ifthemertask
wasnotasynchronous,everythingwouldbeatastandsllunlthemeouteventhappened.
XML:Youmayhaveencounteredthisbefore.XMLstandsforeXtensibleMarkupLanguage.Itsagenericmarkup
languageforrepresenngstructureddata.ItlooksalotlikeHTML,butitcanbeusedtorepresentanykindof
data(sportsscores,theweather,ashoppinglist,etc.).XMLisonepossibleformatforthedatathatcomesfrom
theserverinresponsetoanAJAXrequest.Butyoucangetyourdatafromtheserverinanyformatyouwant.It
canbeXML,HTML,JSON(JavaScriptObjectNotaon)orevenjustplaintext.Nomaerwhatkindofdata
youregeng,mostdeveloperswouldsaythatifyouregengitasynchronouslybylaunchingarequestfroma
JavaScriptprogram,youreusingAJAX.

http://profsamscott.com/javascript/

98/137

11/15/2016

JavaScriptforSheridanStudents

10.2ANewWebAppArchitecture
Upunlnow,wehavebeenassumingawebapparchitecturethatlookslikethis.

Inthisarchitecture,anHTTPrequestislaunchedbytheusereitherbytypingaURL,clickingalink,orsubming
aform.(HTTPRequestsarealsogeneratedbythebrowsertoautomacallytoloadimages,CSSles,JavaScript
lesandotherresources.ButImignoringthatminorcomplicaoninthestoryImtellinghere.)Therequest
goestotheserverwherealeisretrievedand/orascriptisruntogeneratetheHTTPResponse.Whenthe
responsearrives,thebrowserinterpretstheHTMLandCSSinthedocumenttodisplaythepage,andexecutes
theJavaScriptcommandsinthepage.ThenitconnuestorunJavaScriptinresponsetouserinteraconsand
otherevents,refreshingthepageviewwhensomethingchanges.Itdoesntgobacktotheserveragainunless
theuserclicksalink,typesinaURL,orsubmitsaform.
ButwithAJAX,thelifecyclelooksabitdierent:

AnAJAXrequestisanHTTPRequestjustlikeanyother,andcanhaveGETandPOSTparametersassociatedwith
itjustlikeanyother.AttheserveritistreatedinexactlythesamewayasanyotherHTTPrequest.Theonly
dierenceiswhereitcamefrom:itwaslaunchedbyaJavaScriptfuncon.SinceHTTPRequestscantakemeto
completetheyaredoneasynchronouslyandtheprogrammerregisteralistener(a.k.a.callbackfuncon)todeal
withtheresponsewhenitcomes.(Whatwouldhappeniftherequestswerenotasynchronous?)
TheHTTPResponsefromtheserverisalsothesameasanyother.Theonlydierenceisthatwhentheresponse
arrivesattheclient,itdoesnottriggerapagereload.Instead,thecontentoftheresponseispassedtothe
listenerasaparameter.
http://profsamscott.com/javascript/

99/137

11/15/2016

JavaScriptforSheridanStudents

10.3HowAJAXWorks
AJAXqueriesarelaunchedusingtheXMLHpRequestAPIthatisbuiltintoallmodernbrowsers.Tolaunchan
AJAXrequest,youcreateanewXMLHttpRequestobjectandbuildupyourrequestoverseverallinesofcode,
addingheaders,GETandPOSTparametersandregisteringalistenerfuncontobecalledwhentheresponse
arrives.Thenyoulaunchtherequestandthepageconnuesoperangwhiletherequestisinprogress.

10.3.1ADataSource
YoucantdomuchinAJAXwithoutaccesstoadatasourceonaserversomewhere.Therearemanyexcellent
sourcesofdataonthewebthatarefreetouseinyourAJAXprograms.ForexampleYahoosYQL
[hp://developer.yahoo.com/yql/](YahooQueryLanguage[hp://developer.yahoo.com/yql/])canbeused
toretrieveinformaonaboutgeographiclocaons,weather,music,maps,andanumberofotherdomains.But
fornow,youneedaneasiertousesourceofinformaon.
DoItYourself
Intheexamplepack,youwillndaserversfoldercontainingtwoPHPscripts:a"meserver"named
servers/meServer.phpanda"LoremIpsumserver"namedservers/loremIpsumServer.php.
Loadthetwoserverlesbyclickingonthelinksabove(don'ttrytoopenthemonyourownmachine).
ThenreadovertheAPIstheydisplayandtrythemout.YoucanexperimentwiththeGETparametersby
typingthemintoaURL.Forexample,ifyouwantedtosetthepstartparameterto2andplengthto1,
youcoulddoitlikethis:
servers/loremIpsumServer.php?pstart=2&plength=1
AndifyouwanttotestPOSTparameterswiththeLoremIpsumserver,youcanusethe
servers/loremIpsumPostTest.htmllewhichusesa<form>elementwithitsmethodaributesetto
"post"tosendrequeststotheLorumIpsumserver.
Ifyou'veforgoenwhatallthismeans,youmayneedtorevieww3schoolsorasimilarsourcetorefresh
yourmemoryaboutGETandPOSTandPHPFormHandling.

10.3.2AJAXGETRequests
TosendanAJAXGETrequest,youneedtoexecuteaJavaScriptstatementtoperformeachofthefollowing
steps:
1.CreateanXMLHttpRequestObject:Thisistheobjectyouwillusetosendtherequest.
2.OpentheConnecon:YouwillhavetospecifyaURLwhichincludestheGETparametersforyourrequest.
TheURLcanbeabsoluteoritcanberelavetoyourcurrentlocaon.
3.RegisteranEventListener:Theeventlistenerfunconwillbecalledwheneverthestatusoftherequest
changes.
4.SendtheRequest:Thenalstepsendstherequest.Thenthepageconnuestofunconwhilewaingfor
theresponse.

http://profsamscott.com/javascript/

100/137

11/15/2016

JavaScriptforSheridanStudents

DoItYourself
LoadajaxTime2.htmlfromtheexamplepackintoadesktopbrowser.Ignorethecontentsofthepagefor
now.JustopentheJavaScriptconsoleandlaunchyourrstAJAXrequestbyexecungthecodebelowfor
thefourstepsoutlinedabove:
//step1
varxmlhttp=newXMLHttpRequest();
//step2
xmlhttp.open("GET","servers/timeServer.php?request=time",true);
//step3
xmlhttp.addEventListener("readystatechange",function(){
if(xmlhttp.readyState===4&&xmlhttp.status===200)
alert(xmlhttp.responseText);
})
//step4
xmlhttp.send();
Theaboveshouldpopupthecurrentmeforyouinanalertbox.

Instep2,therearethreeparameters.Therstspeciesthetypeofrequest("GET").ThesecondistheURL
whichincludestheGETparameters.Thethirdisabooleanthatissettotruetomakesurethisisan
asynchronousconnecon.
Instep3,youareregisteringalistenerforaspecialeventcalledthereadystatechangeevent.Thelisteneris
thecallbackfunconanditmakesuseofthexmlhpobjectcreatedearliertogureoutwhetheritshouldtake
aconornot.ThereadystatechangeeventwillhappenmulplemesthroughoutthelifeoftheHTTP
request,andwilltriggerthelistenerfunconeachmewithadierentreadyState.Butformostpurposes
onlystate4("ResponseReady")isuseful.Whenstate4isdetected,thenextthingtocheckistheHTTPstatus
thatwasreturned.Status200means"OK",404means"PageNotFound",etc.Usually,youjustcheckforstate
200.
DoItYourself
PastethecommandsfromthelastDIYboxintothe<Script>elementofanewwebpageandaddthe
followinglinetothecallbackfuncontotraceeverycalltothelistener:
console.log(xmlhttp.readyState+""+xmlhttp.status);
YouwillalsohavetoreplacetheURLwiththeabsoluteaddressofthemeserver
(http://javascript.sheridanc.on.ca/examples/servers/timeServer.php/)
Nowloadthepageandchecktheconsoletoseethecalltrace
NowtryagainbutchangetheURLtoinvalidateittoviewthecallsofcallstothelistenerfuncon.

http://profsamscott.com/javascript/

101/137

11/15/2016

JavaScriptforSheridanStudents

DoItYourself
TryouttheforminterfaceprovidedontheajaxTime2.htmlpage.Doyouthinkyoucouldwritethecode
forthispagenow,givenwhatyouknowaboutAJAXandjQuery?

10.3.3AJAXPOSTRequests
ForAJAXrequests,thedisnconbetweenGETandPOSTmayseemlessimportantsincetheparametersyou
sendwillneverbevisibleinthebrowser.However,youshouldsllusePOSTrequestsinthefollowingcases:
1.SendingLargeAmountsofdata(GEThasa1KBlimit).
2.SendingRequeststoUpdateaDatabase(GETrequestsmightaccesscachedcopiesofthepage,inwhich
casethedatabaseupdatewillnotgothrough).
TheprocessforsendingPOSTdataisverysimilartotheprocessforGETdata,butyoumustsetaspecialheader
ontherequesttospecifythatthereareparametersinthebodyofthemessage,andyouspecifytheparameters
whenyoucallthesendmethodratherthanintheURL.
DoItYourself
Pastethecommandsbelowintothe<Script>elementofanewwebpage.Theboldfacedpartsshow
thestuchangedforaPOSTrequest.
varxmlhttp=newXMLHttpRequest();
xmlhttp.open("POST","servers/timeServer.php",true);
xmlhttp.setRequestHeader("Contenttype","application/xwwwform
urlencoded");
xmlhttp.addEventListener("readystatechange",function(){
if(xmlhttp.readyState===4&&xmlhttp.status===200)
alert(xmlhttp.responseText);
})
xmlhttp.send("request=time&timezone=Canada/Pacific");
Theaboveshouldpopupthecurrentmeforyouinanalertbox.
Nowtrychangingsomeoftheparameterstogetthedayormonth,oruseadierentmezone.
Nowtrychangingthelistenerfunconsoitputsthetextsomewhereonthescreen(maybeinthe
innerHTMLofan<h1>element,orinthevalueaributeofan<input>element).

http://profsamscott.com/javascript/

102/137

11/15/2016

JavaScriptforSheridanStudents

10.3.4AJAXOnaWebPage
TheJavaScriptcodebelowisfromtheajaxTime2.htmlexample.Takeamomenttoreaditoverandtryto
understandit.
window.addEventListener("load",function(){
functionlaunchAjax(){
varaddress="servers/timeServer.php";
vartimezone=document.querySelector("input[name=timezone]").value;
varrequest=document.querySelector("select[name=type]").value;
vardelay=document.querySelector("input[name=delay]").value;
varURL=address+"?timezone="+timezone+"&request="+request+
"&delay="+delay;
varxmlhttp=newXMLHttpRequest();
xmlhttp.open("GET",URL,true);
xmlhttp.addEventListener("readystatechange",function(){
if(xmlhttp.readyState===4&&xmlhttp.status===200){
document.getElementById("result").innerHTML=
xmlhttp.responseText;
}
});
xmlhttp.send();
}document.getElementById("ajaxButton").addEventListener("click",
launchAjax);
});
Therstthingtonoteisthatallthecodeisinsidethewindowobject'sreadyeventhandler.Thisisjust
followingthebestpraccesthatwereintroducedinchapter5.
ThesecondthingtonoceisthatthelaunchAjaxfunconcontainscallstotheXMLHttpRequestobjectthat
shouldlookveryfamiliarfromtheprevioussecon.Theonlydierenceisthatonemoreparameterisset
(delay)andthevaluesforeachparameterarecomingfromtheformelements.Also,thelistenerfunconis
placingthedataintotheinnerHTMLoftheelementwithanidof"result".
Thesyntax$("[attribute=value]")isusedtoselectalltheelementswithaparcularaributevalue.In
thiscaseitsbeingusedtoretrievenamedformelements.Theprogrammercouldjustaseasilygivethemid
aributesandusedocument.getElementById.
AerthedenionoflaunchAjax,thefunconisaddedasaclickeventhandlerontotheelementwithan
idof"ajaxBuon".
Nowyouhavetwodatasources(servers/loremIpsumServer.phpandservers/meServer.php)andaworked
example(ajaxTime.html).Itsmetobuildsomethingofyourown.

http://profsamscott.com/javascript/

103/137

11/15/2016

JavaScriptforSheridanStudents

<exercisessection='10.3.4'>
1.Taketheleservers/loremIpsumPostTest.htmlfromtheexamplepackandchangeitsothat
insteadoflaunchingabrandnewPOSTrequestandreloadingthepage,itinsteadlaunchesanAJAX
queryanddisplaystheresultbelowtheform.
2.Intheexercisesfolder,lookatthelendLorem.html.YouhavetheHTMLandCSShereforagame.
YoujusthavetollintheJavaScript.ThisgamewillpulloutarandompieceofLoremIpsumtext
fromtheserver,usinganAJAXquery.Thenitwillallowtheusertoguesswherethetextcamefrom,
usingmoreAJAXqueriestocheckwhethertheywererightornot.Seethecommentsinthe
ndLorem.htmllefordetailedinstrucons.
3.Intheexamplepackyouwillndmore.htmlanditsassociatedles.AddthenecessaryJavaScript
codesothatthispageallowstheusertoloadoneparagraphatamefrom
servers/loremIpsumServer.php.Whentheyrstload,theyshouldseetherstparagraph,retrieved
withAJAX.Thenwhenevertheyhitthe"more"buon,theyshouldgetthenextparagraphin
sequence.

</exercises>

10.3.5WhatToDoWhileYouWait
Becausenetworkscanbeslow,AJAXrequestscansomemestakeafewsecondstocomplete.Ifthingsdon't
happeninstantly,itcancausetheusertostartpressingbuonsoverandoveragain,orbehavinginother
destrucvewayswhichcouldenduplaunchingmoreandmoreAJAXrequests.Thisisaproblemyouhaveto
thinkaboutwheneveryouuseAJAX.
DoItYourself
LoadupajaxTime2.htmlfromtheexamplepack,setthedelayontheformto15seconds,andsetthe
requestto"me",thenhitthe"AJAX!"Buon.Thiswillsendarequesttotheservers/meServer.php
pagewhichinstructsthephpscriptstopausefor15secondsbeforecompleng.Sothissimulatesadelay
overaslownetwork.
Whileyourewaingforyourrstrequest,setthedelaybackto0andtrysomedierentrequests
(anythingotherthan"me").Aer15seconds,theoriginalrequestwillgetitsresponseandthiswill
disruptwhatyouarecurrentlydoing.

TheusualsoluontothisproblemistocontroltheusersomehowwhileyouarewaingfortheAJAXrequestto
complete.Forexample,iftheuserclickssomethingtoloadmorecontent,youcoulddothefollowing:
1.Intheclickhandler,disablethebuontheuserjustclicked,andperhapsgivethemsomevisualindicaon
thatwearewaingforsomethingtoload.
2.InthelistenerfunconthatrespondstotheAJAXrequest,reenablethebuon.
ThiswillensurethatonlyoneAJAXrequestisdealtwithatame.
AnotherapproachmightbetohaveaglobalvariablewithanamelikewaitingForAJAX:
1.InializewaitingForAJAXtofalse.
2.Intheclickhandler,checkifwaitingForAJAXistrue.Ifitis,givetheuseranerrormessageorsimply
ignoretherequest.Ifit'sfalse,launchtheAJAXqueryandsetwaitingForAJAXtotrue.
http://profsamscott.com/javascript/

104/137

11/15/2016

JavaScriptforSheridanStudents

3.Inthelistenerfuncon,setwaitingForAJAXbacktotofalseoncethereadystateis4.
Youcouldalsoconsiderplacingananimatedgifonthepagelikeintheexamplebelow.

Load
<exercisessection='10.3.5'>
1.Followuponexercise1fromthepreviousseconbyaddingmorecodetothe
servers/loremIpsumPostTest.htmlpagesothatthesubmitbuonisdisabledunltheAJAX
requesthascompleted.Thentestitbysengthedelayparameter.
2.AddcodetotheajaxTime.htmlpagesothattheuserhastowaitunlthepreviousrequesthas
completedbeforeanewonewillbelaunched.Thismedon'tdisablethebuoninsteadseta
globalbooleanvariableandiftheuserhitsthebuonagainbeforetheAJAXrequestiscompleted
givethemanerrormessageinanalertbox.
3.Repeattheabove,butthismeusetheothersuggestedstrategyforwhattodowhileyouwait.
4.Alteryoursoluontothemore.htmlexercisefromtheprevioussecon.SetuptheAJAXrequests
toincludeashortdelayandmakesureyoudisabletheuserwhiletheywaitfortheirnext
paragraph.
5.Wouldn'titbeniceifyoucouldjustcallafunconlikethisandhaveittakecareofallthemessy
detailsforyou:sendAjax(type,url,parameters,callback_function);Youshould
writeone!Thenputitinitsown.jsle,addittooneofyourpagesandtryitout.Makesuretotest
bothGETandPOST.

</exercises>

http://profsamscott.com/javascript/

105/137

11/15/2016

JavaScriptforSheridanStudents

11.ThejQueryLibrary
Nowyou'reabletowritesomepowerful,standalonewebappsusingforms,eventsandtheHTMLDOM.But
thereareeasierwaystoprogramwebappsthanplainJavaScript.ThischapterisaboutjQuery,apublicdomain
JavaScriptlibrarythathascaughtonlikewildreandischangingthewayJavaScriptcodeiswrien.JQuery
[hp://jquery.com/]providesapowerfulsetofmethodsforDOMmanipulaonandeventhandlingthatsolve
manyofthecrossbrowsercompabilityissuesthatarisewhenusingplainJavaScript.TousejQueryeecvely,
youneedtonallyunderstandJavaScriptfunconsalilebeer,sothischapterwillcoverthataswell.
ThischapterwillgiveyouthebasictoolsyouneedtousejQuery,butIwillleavealotofthedetailsforyouto
exploreyourself.ThejQueryAPIisthedenivesourceofinformaonaboutjQuery,andtheocialLearn
jQuery[hp://learn.jquery.com/]sitehassomenicetutorials.Therearealsosomeusefultutorialsinthe
w3SchoolsLearnjQuerysecon.
ThejQuerylibraryispubliclyavailablefordownload,butifyouareusingNetBeans[hps://netbeans.org/]
version7.3orlater,itisalsoavailableautomacallyasanaddinlibraryforprojectsoftypeHTML5.

11.1SelectorsandEffects
ThejQuerylibraryextendsthepowerofCSSselectorsinJavaScript.RecallthataCSSselectoristherst
componentofaCSSrulethepartthatspecieswhichelementstheruleappliesto.Forexample,theCSSrule
belowusestheselector"p,#myDiv,span.movie"tospecifythatitappliessimultaneouslytoallelements
oftype<p>,theuniqueelementwithitsidaributesettomyDiv,andany<span>elementwithaclass
aributethatincludesmovie.
p,#myDiv,span.movie{
color:red;width:100%;
}
InplainoldJavaScript,ifyouwantedtodomakesamechangestoadiversecolleconofelementslikethis(e.g.
supposeyouwantedtoturnthemallgreen)youwouldneedtowriteoneexpressionorasetofexpressionsto
getthecolleconofelements,andthenyouwouldneedtowritealooptoapplythechangestothecollecon.
ButnowyoucanusejQueryselectorstodoitallinoneline,likethis:
$("p,#myDiv,span.movie").dosomething();

http://profsamscott.com/javascript/

106/137

11/15/2016

JavaScriptforSheridanStudents

DoItYourself
Here'sasimpleexamplethatyoucanuseonthisbookifyouareviewingitonline.
OpentheJavaScriptconsoleandtypethefollowingtoturnalltheheadersgreen.
$("h1,h2,h3").css("color","green");
NotethatenteringjQuerycommandsintheconsolewillonlyworkifthecurrentpageincludesalinkto
thejQuery[hp://jquery.com/]library.SincethisbookmakesuseofjQuery,itcanbeusedasajQuery
testbed.
AlltheDIYboxesinthisbookare<div>elementswiththeclassname"DIY".Basedontheabove
example,seeifyoucanturnthebackgroundsofallDIYboxesinthedocumentpink.
Youcanalwaysreverseanychangesbyhing"reload".

11.1.1ThejQuerySandbox
Inwhatfollows,wewillusethejQuery[hp://jquery.com/]"sandBox"alot.It'sjustapagewiththejQuery
libraryloadedsothatyoucantryoutcommandsintheJavaScriptconsole.Themainpageis
jQuerySandbox/index.htmlfromtheexamplepack.WhenyouexplorethejQuerySandboxfolderandles,you
willnocethatthejQuerylibraryisincludedinthejsfolder,andthattheindex.htmlleloadsthejQuery
libraryusingthefollowingline:
<scripttype="text/javascript"src="js/jquery1.10.0.js"></script>
ThislinecausesallthecodeinthejQuerylibrarytobeincludedinthesandboxpage.IfyouwanttousejQuery
inyourownpages,youhavetodotwothings:
1.Downloadthelibraryandputitsomewhereinyourproject;and
2.Linktoitina<script>elementasabove.
JavaConnection
ImporngLibraries.InJava,youoenhave
toimportclassesthatareextensionstothe
baselanguage.jQueryisabitlikethat.It
alsohastobeexplicitlyincludedinyour
program.

Atthemeofwring,version1.10.0wasthelatestversion
ofjQuery,butthatmighthavechangedbynow.Thelatest
versionisalwaysfreelyavailableatthejQuerywebsite
[hp://jquery.com/],whereyoucanalsochoosethe
"minimized"versionofthelibrarytosavebandwidth(it'sthe
sameastheregularlibrary,butwithwhitespaceandother
unnecessarycharactersremoved,variablenamesshortened
andsoon).

DoItYourself
Tousethesandbox,loadjQuerySandbox/index.htmlfromtheexamplepackintoabrowserandopenthe
JavaScriptconsole.Becausetheindex.htmlleloadsthejQuerylibrary,youcanplaywithjQuery
[hp://jquery.com/]commandsinthiswindow.
You'llnocetherearesomeinstruconsforacviesonthepage.Youcantrythemnowifyouwant,but
youmightdobeertowaitforabitmoreinformaon.

http://profsamscott.com/javascript/

107/137

11/15/2016

JavaScriptforSheridanStudents

11.1.2ThejQuery($)Function
EverythingyouwilldowiththejQuerylibrarywillbebasedonthenewjQueryfuncon.Therearetwowaysto
writethisfuncon,shownbelow:
1.jQuery(selector)or
2.$(selector)
Fromnowon,Iwilljustuse$version.
TheselectorpartofthesyntaxworksjustlikeaCSSselector,withafewextensionsuniquetojQueryselectors.
ThejQueryfunconwillreturnanobjectoftypejQuerythatlooksandbehavesverymuchlikeanarrayof
DOMelements.
Beforemovingon,youmayneedtoreviewthew3SchoolsCSSselectorreferenceandyoushouldalsotakea
lookatthejQueryAPIselectorreferenceaswell.NotethatsomeCSSselectorsarenotavailableinjQuery(e.g.
:hover)andsomejQueryselectorsarenew(e.g.:not()).Whywould:hovermakesenseforCSSbutnotfor
jQuery?
DoItYourself
OpentheJavaScriptconsoleforthistextbookandtrythiscommand:
$("h1")
ThejQueryobjectthatisreturnedtoyoushouldlooksomethinglikethis:
[<h1>Contents</h1>,<h1>1.GettingStarted</h1>...]
Iftherearemorethan100elementsinthearray,thingsmightlookaliledierent.Forinstanceifyou
type:
$("a")
you'llgetsomethinglikethisinstead:
>st.fn.st.init[432]
Whichmeanstherewere432objectsreturned.Ifyouopentheresultbyclickingonthearrow,youwillbe
abletoseethecontents,arrangedintogroupsof100.

http://profsamscott.com/javascript/

108/137

11/15/2016

JavaScriptforSheridanStudents

DoItYourself
TrythefollowinginaJavaScriptconsoleforthejQuerySandbox/index.htmlpageandmakesurethe
resultsarecorrect.RememberthatinChromeyoucanmouseovertheresulngobjectstoseethe
correspondingDOMelementshighlightedontheoriginalpage.
1.Getall<td>elementswiththeclassaributesetto"odd"
2.Getall<h1>elements
3.Getall<span>elements
4.Gettheelementwiththeidsetto"instrucons"aswellasevery<tr>element.
5.ExecutethejQuerycommand$("*").WhatelementsareintheresulngjQueryobject
[hp://learn.jquery.com/usingjquerycore/jqueryobject/]?
6.ExecutethejQuerycommand$(document)withnoquotaonmarksinsidethebrackets.What
elementisintheresulngjQuery[hp://jquery.com/]object?

Theobjectreturnedfromthe$funconcanbetreatedalotlikeanyanarray.Forexample,thiscommandwill
changetheborderstyleofthecheckerboard:
$("#checkerboard")[0].style["borderStyle"]="dashed";
Theabovestatementisequivalenttothefollowing:
document.getElementById("checkerboard").style["borderStyle"]="dashed";
Similarly,youcouldputanXintoeveryevencheckerboardsquareofjQuerySandbox/index.htmlwiththe
following:
varsquares=$("td.even");
for(vari=0;i<squares.length;i++)
squares[i].innerHTML="X";
Butwait!AlthoughinsomerarecasesyoumightwanttodoarrayprocessingonthejQueryobject
[hp://learn.jquery.com/usingjquerycore/jqueryobject/],inmostcasesthereisafareasierway.Readon...

11.1.3ChainingMethods:innerHTML,stylesandattributes
Sonowyou'vemasteredselectors,andyoucanprocessthejQueryobjectasifitwereanarray.Butwhere
jQueryreallygetsitspowerisinthechainingofotherjQuerymethodsontotheendofthe$funcon.Foursuch
methodsarehtml,css,valandattr.Whenchainedattheendofthe$funconusingthedotoperator,
thesefunconscanbeusedtosettheinnerHTML,styleproperes,valueaributes(forformelements)and
otheraributesofanenresetofselectedelementsallatonce.

http://profsamscott.com/javascript/

109/137

11/15/2016

JavaScriptforSheridanStudents

DoItYourself
HerearesomeexamplestotryintheJavaScriptconsoleofjQuerySandbox/index.html:
$("#instructions").html("Nomoreinstructions!");
$("td.odd").css("backgroundColor","blue");
$("a").attr("href","http://www.facebook.com");
$("input:text").val("Anewvalue");
Verifythechangesmadetothepageineachcase.NotethatthelastonemakesuseofaspecialjQuery
selectorinput:textwhichselectsallinputelementsoftypetext.Therearealsoselectorsfor:button,
:checkboxandsoon.
Youcanalsouseeachofthesemethodswithonelessparameter,andtheywillreturntheinnerHTML,
styleproperty,oraributeoftherstelementinthematchingset.Trythefollowing:
$("#instructions").html();
$("td.odd").css("backgroundColor");
$("a").attr("href");
$("input:text").val();
Verifythattheresultsmakesenseineachcase.

Andmethodchainingdoesntstopatjustonemethod!EachchainedjQuerymethodreturnsacopyofthe
originaljQueryobject.Thismeansmethodscanbechainedoneaeranotherasmanymesasyouwant.
DoItYourself
TrythefollowingcommandinjQuerySandbox/index.html,buttrytopredicttheresultbeforeyoupress
enter.
$("#instructions").css("backgroundColor","red").css("color","rgba(255,255,2
55,0.5)").html("Hello,World!");
Thereisnolimittohowmanymethodsyoucanchaintogetherinthisway.

Youcanalsochangetheclass(es)anelementbelongstowiththeaddClassandremoveClassmethods,and
youcanndoutifitbelongstoaparcularclasswiththehasClassmethod.Moreinformaononthese
methodscanbefoundinthew3schoolsjQueryseconcalledjQueryCSSClasses.
ThejQuerymethodsmenonedaboveallhavecounterpartsinordinaryJavaScript(style,innerHTML,
className,etc.).ButinmanycasesthejQueryversionsaremorepowerful.

http://profsamscott.com/javascript/

110/137

11/15/2016

JavaScriptforSheridanStudents

DoItYourself
Forexample,trytheJavaScriptstatementbelowinjQuerySandbox/index.html.
document.getElementById("instructions").style["color"]
Itreturnsanemptystringbecausethecolorpropertyofthiselementisnotexplicitlysetinthestyle
aributeoftheelement.
NowtrytheequivalentjQuerystatement.
$("#instructions").css("color")
ThiscommandsearchesthehierarchyofCSSstylesandreturnsthecorrectcolor"rgb(0,0,0)"whichit
retrievesfromthedefaultbrowserstyle.

<exercisessection='11.1.3'>
1.TrythefollowingonjQuerySandbox/index.htmlusingtheJavaScriptconsoleofyourbrowser.Note
thatyoucanalwaysreloadthepagetogetitbacktoitsinialstatebetweencommands.
a.Usethe.css()methodtochangethecheckerboardborderstyletodashed.
b.Usethehtml()methodtoputan"X"ineveryevencheckerboardsquare.
c.UsetheaddClass()andremoveClass()methodstochangetheoddsquarestoeven.
d.Usethehtml()methodtochangeeverylinkonthepagetoread"thisisalink".
e.Changethecontentsandcolorofall<td>elementsinoneline.
f.Changetheclassofeventooddandoddtoevenintwolines.Canyoudoitinoneline?
2.ThefollowingrequirechangestothejQuerySandbox/index.htmlleofthesandbox.Makesure
youalsohavetheCSSandJavaScriptles.Youcanviewthesourceofthepageandopentheextra
lesfromthere,oryoucangeteverythingintheexamplepack.
a.Putabuononthesandboxpagethat,whenclicked,togglesthecheckerboardfromwhite
andredsquarestobrownandblacksquares,andbackagain.
b.Putasecondbuononthesandboxpagethatpromptstheuserfortwonumbers,then
movestheinstruconspaneltothosecoordinates.
3.GetthebasicForm.htmllefromtheexamplepackandmakethefollowingchanges:
a.LoadthejQuerylibraryina<script>element.
b.UsingjQuery[hp://jquery.com/],addanonsubmiteventhandlertotheform,andcheck
tomakesuretheusernameandpasswordeldsarelledin,thatthepasswordisatleast8
characterslongandcontainsleersandnumbers,andthatatleasttwointerestsare
selected.Ifnot,returnfalseandissueanalerttellingtheuserwhatwentwrong.
c.Adda"llin"buonthatautollstheformwithvaluesofyourchoosing.UsejQueryforall
processing.

</exercises>

http://profsamscott.com/javascript/

111/137

11/15/2016

JavaScriptforSheridanStudents

11.1.4EffectsandAnimations
ThejQuerylibraryalsocontainsmethodstomakevariouseectsandanimaonseasy.Thesemethodscanbe
chainedaerthe$funconjustliketheonesdiscussedintheprevioussecon.
DoItYourself
Here'sanexampletotryinjQuerySandbox/index.html:
$("#instructions").fadeOut();
Theabovewillfadeouttheinstruconpanel,andthenremoveitbysengitsdisplaypropertyto"none".
Notethattobeatitsmosteecve,thefadeOut()methodshouldonlybeappliedtoelementswith
absoluteposioning.Trythefollowingtoseewhathappensotherwise:
$("#td.odd").fadeOut();

Iwillleaveittoyoutoexploremostoftheseeectsonyourown.Youcanndinformaononalloftheminthe
jQueryAPI[hp://api.jquery.com/].Lookinthe"eects"secon.Readthe"basics","fading"and"sliding"
secons.Clickoneachmethodnameforanexplanaon.Youcanalsogotothew3schoolsLearnjQuerysecon
formorehelp.
Notethatmostofthesemethodshaveoponalparameters.Forexample,thepageforthefadeOut()method
hasthefollowingheader:
.fadeOut([duration][,complete])
Thesquarebracketsmeanthatthedurationandcompleteparametersareoponal.Ifyoucallthisfuncon
withnoparameters,itwillusedefaultvalues.Youcanalsosettheduraonifyoucallitwithoneparameter,or
setbothduraonand"complete"ifyoucallitwithtwoparameters.(Iwillexplainmoreaboutthe"complete"
parameterinthenextsecon).
Thereisalsoagenericanimate()methodwhichisexplainedunder"custom"inthe"eects"seconofthe
jQueryAPI[hp://api.jquery.com/].Thismethodneedsatleastoneparameter,specifyingasetofCSS
properesandvaluesto"movetowards".Anyofthespeciedproperesthatcanbeanimated(usuallynumeric
properes)willbeanimated.
DoItYourself
TrythisinjQuerySandbox/index.html:
$("#instructions").animate({left:"200px",width:"100px"})

Theparameterontheaboveinstruconisalileoddifyouveneverseenanythinglikebefore.Thecurly
bracketsindicatethatitisactuallyaspecicaonofaJavaScriptobjectit'sanobjectliteral,somethingthatis
uniquetolanguageswhich,likeJavaScript,werederivedfromECMAScript.Thecontentsofthecurlybrackets
consistofalistofeldnames(unquoted)andvalues(quoted).
So{left:"0px",width:"20%"}createsanewobjectwiththeeldsleftandwidthsettocontainthe
strings"200px"and"100px"respecvely.Thenthisobjectispassedasaparametertoanimate().Youwill
learnalotmoreaboutcreangJavaScriptobjectsinalaterchapter.
http://profsamscott.com/javascript/

112/137

11/15/2016

JavaScriptforSheridanStudents

<exercisessection='11.1.4'>
1.CompletethejQuerySandbox/index.htmlexercisesaslaidoutintheinstruconspanel.
2.ExplorethejQueryAPIabitmore.Takealookatthe"Aributes","CSS","Dimensions","Eects"
and"Manipulaon"secons.Findandtryoutatleast3moreinteresngmethods.
3.Gobacktothememopadexercisefrompreviouschaptersandtweakitsoitmakeseecveuseof
jQuery[hp://jquery.com/].
4.GobacktotheexercisebasedondropdownMobileExercise.htmlinwhichyoucreatedmenusthat
appearanddisappearwhenbuonswereclicked.ModifythistomakegooduseofjQueryselectors
andmethodchaining.
5.GobacktothecatchTheRabbit.htmlexercisefrompreviouschapters.UsingjQuery,changeyour
originalsoluonsothatwhenyoumouseovertherabbit,itslidestoanew,randomlygenerated
locaononthescreen.(Tip:usetheJavaScriptwindowobjecttondouttheheightandwidthof
thescreen.)
6.TaketheslidingTiles.htmlcodefromtheexamplepackandaddJavaScript(usingjQuery)to
implementaslidinglespuzzle.Whentheuserclicksale(i.e.an<a>element)thatisbesidethe
blankle,itshouldslidesmoothlyintoitsnewposionusingthejQueryanimate()method.Note
thatthiscodecanbeverytrickytowriteifyouhaveneverdoneanythinglikethisbefore.

</exercises>

11.2jQueryEventsandtheTruthaboutFunctions
Upunlnow,youhaveprobablybeenaddingeventhandlerstoelementsbyplacingJavaScriptcodeintothe
correspondingHTMLaributes,likethis:
<inputtype="button"onclick="myFunction()">
ThisisnotconsideredbestpraccebymostJavaScriptprogrammersforatleastthreereasons.
1.ItspreadsyourJavaScriptcodethroughouttheHTMLle,makingthecodehardertomaintain.(i.e.It
wouldbemuchbeerifyoucouldaddallyoureventhandlercodeinasingleplace.)
2.Itviolatesthecleanseparaonbetweenthestructureoftheinterface(thejobofHTML),thestyleofthe
interface(thejobofCSS)andthefunconalityofyourapp(thejobofJavaScript).
3.Itcausesthebrowsertocreateanewanonymousfunconwiththecodeyouputintheaributeasits
contents.Thisisunnecessaryandwasteful.(I'llexplainwhatImeanbythisinamoment.)
ItiswidelyconsideredbestpraccetoaddeventhandlersinJavaScriptaerthedocumenthasloaded.Butto
beabletodothat,youneedtounderstandhowfunconsworkinJavaScriptinalilemoredepth.Onceyou
havethisunderstanding,youwillalsobeabletousethenewjQueryreadymethod,aswellasthecallback
parametersofthejQuery[hp://jquery.com/]eectsfuncons.

11.2.1TheTruthAboutFunctions
ThetruthaboutJavaScriptfunconsisthattheyareactuallyvalues,justlikestrings,numbers,Booleans,and
objects.Likeanyothervalue,funconscanbestoredinvariables,passedasparameterstootherfuncons,and
returnedfromfunconcalls.
http://profsamscott.com/javascript/

113/137

11/15/2016

JavaScriptforSheridanStudents

ThetechnicaltermforthisisthatJavaScriptfunconsarerstclassfuncons.
Whenyouuseafuncondeclaraonlikethis:
functionfoo(a,b,c){
alert(a+b+c);
}
Whatyouarereallydoingiscreangavariablenamedfoo,
andassigningafunconvaluetoit.
Thefollowingshowstheassignmentofafunconliteraltoa
variable.ItislegalJavaScriptcode,andisbasicallyequivalent
tothefuncondeclaraonabove:
varfoo=function(a,b,c){
alert(a+b+c);
};

JavaConnection
Methodsvs.Funcons.InJava,methods
andvariablesarecompletelydierent
enes(howwouldyoudescribethe
dierence?)InJavaScript,funconnames
areactuallyvariablenames,andfuncons
aredata.

Theabovestatementcreatesavariablenamedfoo,andassignstoitananonymousfunconwith3
parameters.Notethatsincethisisanassignmentstatement,weputasemicolonattheendofit.
Themaindierencebetweenthetwonotaonsisthatyoucanonlyusefuncondeclaraonincertaincontexts,
butyoucanusevariabledeclaraonandfunconliteralsinanycontext.Becauseitislimitedandaddsnothing
tothelanguage,manyprogrammersavoidfuncondeclaraonaltogetherandalwaysusethevariable
declaraon/funconliteralnotaon.

http://profsamscott.com/javascript/

114/137

11/15/2016

JavaScriptforSheridanStudents

DoItYourself
Nomaerwhetheryouusefuncondeclaraonorvariabledeclaraonwithfunconliterals,ifyourefer
tofooinyourprogram,youarereferringtoavariable.Toseethis,trythefollowingintheJavaScript
consoleofyourbrowser:
functionfoo(){alert("hi");}fooisafunction
foo;
foo();
Queson:Whatisthedierencebetweenthelasttwolinesabove?
alert(foo);
alert(foo());
Queson:Whatisthedierencebetweentheabovetwolines?
Trythelinesbelowtoseethatyoucanswitchfoobackandforthbetweenafunconandotherdata
types.
foo=5;fooisnowanumber
alert(foo);
foo=function(){alert("hi");};fooisafunctionagain
alert(foo);
foo="hi";fooisnowastring
alert(foo);

Answers:Intheconsolewindow,fooreturnsthevalueofthevariable.It'safuncon.Butfoo()callsthe
funconsoyouwillseethepopup.Ontheotherhand,alert(foo)willdisplayapopupwhosecontentisthe
valueofthevariablefoo(ifit'safuncon,itwillshowyousomethingtothateect).Finally,alert(foo())
willrstcallthefoofuncon,displayingapopup.Thenitwillcreateanotherpopuptodisplaythereturnvalue
offoo.Sincethereisnothingexplicitlyreturned,itwillreturnthespecialvalueundefined.

11.2.2AddingEventHandlersinPlainJavaScript
Ifyouwanttoaddeventhandlerstoanelementaeritiscreated,youcandoitbygengtheelementoutof
theDOM,creangafuncon,andassigningthatfuncontotheaributefortheeventhandler.
DoItYourself
TrythefollowinginthejavaScriptconsoleforthistextbook.
document.getElementById("test6").onclick=function(event){
alert("hello!");
};
SincethisDIYboxhasanidoftest6,youshouldnowbeabletoclickitandseetheresult.
P.S.Don'tworryabouttheeventparameterabove.Itwillbeexplainedattheendofthissecon.

http://profsamscott.com/javascript/

115/137

11/15/2016

JavaScriptforSheridanStudents

Oryoucancreatethefuncon(eitherthroughfuncondeclaraonorusingafunconliteral)rst,andthen
assignittotheeventhandler.
DoItYourself
TrythefollowingintheJavaScriptconsoleforthistextbook.
varclickHandler=function(event){
alert("goodbye!");
}
document.getElementById("test7").onclick=clickHandler;
Nowyoushouldbeabletoclickthisboxforamessage.

AnotheroponthatsomeprogrammerspreferistousetheaddEventListenermethodwhichtakestwo
parameters.Therstistheeventname(withoutthe"on"souse"click"insteadof"onclick")andthesecondis
thehandlerfuncon.
DoItYourself
TrythisintheJavaScriptconsoleforthistextbook.Notethatyouwillhavetodeneclickhandlerrst.You
cangetitfromthelastDIYbox.
functionclickHandler(event){
alert("goodbye!");
}
document.getElementById("test8")
.addEventListener("click",clickHandler);
Ofcourseyoucanalsoaddahandlerusingafunconliteral.Trythis:
document.getElementById("test8")
.addEventListener("click",function(event){
alert("hello!");
});
Now,whenyouclickthisboxyoushouldgettwopopups,notone.Thisillustratesonecrucialdierence
betweenassigningtoonclickandusingaddEventListener.Thelaerallowsyoutoaddmanyevent
handlersofthesametypetothesameobject.
Youshouldalsonocethatinthesecondcaseabove,thefunconliteralisnotassignedtoanyparcular
variablename.Thismakesitananonymousfuncon.

JavaConnection
EventListeners.JavaandJavaScriptboth
useaddListenermethodstoregister
eventhandlers.Thedierenceisthatin
Javaaneventlistenerisanobject,whilein
JavaScriptit'safuncon.

http://profsamscott.com/javascript/

Notethatthefunconsaboveallcontainanevent
parameter.Anyeventhandlerisalwayspassedaspecial
eventobjectthatrepresentstheeventthatredtotrigger
thisfuncon.Youcanuseittoaccessinformaonaboutthe
event,suchaswhichelementwasthetarget
(event.target),whichmousebuonwaspressed
(event.button),thelocaonofthemouse
(event.clientXandevent.clientY),etc.

116/137

11/15/2016

JavaScriptforSheridanStudents

DoItYourself
HerearetwolastthingstotryintheJavaScriptconsoleforthistextbook.
document.getElementById("test9").onclick=function(event){
alert(event.pageX+","+event.pageY);
};
Nowwhenyouclickonthisbox,youwillgettoseetheexactXandYlocaonofyourclick,inpixelsfrom
thetoplecornerofthepage.
Theeventobjectcontainsanumberofusefulelds,butprobablythemostusefulisthetargeteld
whichcontainstheDOMnodethatwasthesubjectoftheevent.
Trythis:
document.getElementById("test9").onclick=function(event){
alert(event.target.innerHTML);
};
NowclickingthisboxshouldgetyouthefullinnerHTML.

FormoreinformaonontheJavaScriptEventobject,gotow3schoolsandclickonHTMLDOM,thenHTML
DOMObjects,thenDOMEvents.

<exercisessection='11.2.2'>
1.LoadeventHandlerTest.htmlfromtheexamplepack.Comparehowthehandlershavebeenadded
totheelementswithidtest1andtest2.
a.Considerthepageasitisloadingintothebrowser.Atwhatpointinmeiseachhandler
added?TocheckyouransweryouwillprobablyhavetolookuptheJavaScriptwindow
objectandonloadeventonw3schools.
b.Trycommenngoutthewindow.onloadlineandthe};linethatgoeswithitandreload
thepage.Describehowthepageworks(ornot)nowandexplainwhy.
2.Addtwohandlerfunconstotheelementwithid="message"usingJavaScript(notHTML
aributes).Thesefunconsshouldrespondtotheonmouseoverandonmouseoutevents.When
themouseisinsidethemessagebox,oneoftheotherboxesshouldbepinkandtheothershould
bewhite.Whenthemouseisoutsidethemessagebox,theonethatwaswhiteshouldbecomelight
blueandtheonethatwaspinkshouldbecomewhite.

</exercises>

11.2.3EventHandlersinjQuery
ThejQuerylibrarycontainsitsowneventmanagementsystemthatextendstheregularHTMLandJavaScript
system,makingitmorerobust,usefulandcrossbrowsercompable.InjQuery,eventhandlersareaddedto
elementsbychaininganeventmethodonthejQueryselectorfuncon,likethis:
$(selector).event(handler);
Intheabove,"selector"isanormaljQueryselector,"event"isaneventname(load,click,mousenter,etc.),
and"handler"isafuncon.
http://profsamscott.com/javascript/

117/137

11/15/2016

JavaScriptforSheridanStudents

DoItYourself
HeresanexampleofhowtoaddaclickHandlerfuncontotheallDIYboxesinthisdocument.Tryitin
theJavaScriptconsole.
varclickHandler=function(event){
alert(event.pageX+","+event.pageY);
}
$("div.DIY").click(clickHandler);
TheeventobjectaboveisactuallyanewjQueryeventobject.ItworksexactlyliketheoriginalJavaScript
object,butwithfullcrossbrowsercompability.

Thecorrectplacetoaddhandlersiseitherintheloadeventofthewindowobject,orinthenewjQueryready
eventofthedocumentobject.Hereswhatthiswouldlooklike.
Usingtheloadeventofthewindow:
$(window).load(function(){
$(selector).event(clickHandler);
//morecode,functiondeclarations,etc.
});

Usingthereadyeventonthedocument:
$(document).ready(function(){
$(selector).event(clickHandler);
//morecode,functiondeclarations,etc.
});
(Intheaboveexamples,youwouldreplace"selector","event",and"clickHandler"withappropriatevalues.)
Thedierencebetweentheabovetwooponsisthatthewindowonloadeventwillnotreunlallresources
(images,etc)oftheareloaded.ButthejQueryreadyeventwillreassoonastheDOMisconstructed.So
unlessyouwanttoaccessimagesandotherexternalresourcesthatmaynotbeloadedyet,thereadyeventis
theoneyoushoulduse.
Weshouldalsosaysomethinghereabout$(window)and$(document).ThesecallstothejQueryfuncondo
notuseaCSSstyleselector.Insteadtheysimplyprovideanobjectasaparameter.ThejQueryfunconsupports
thisbyreturnajQueryobject[hp://learn.jquery.com/usingjquerycore/jqueryobject/]withasingleobject
inittheonethatwaspassedin.SoifyouhaveanobjectandyouwanttochainjQuerymethodsonit,youcan
usethejQueryfunconandjustpassittheobject.

http://profsamscott.com/javascript/

118/137

11/15/2016

JavaScriptforSheridanStudents

DoItYourself
TrythefollowingintheJavaScriptconsoleforthistextbook.
$(document.getElementById("test4"));
and
varx=document.getElementById("test4");
$(x);
and
$("#test4");
Youshouldgetthesameresultineachcase.Wewillseeanotherveryimportantuseofthissoon.

GotothejQueryAPIeventsreferenceformoreinformaonontheeventssupportedbyjQuery.Themost
importantcategoriesofeventsarekeyboard,mouse,andformevents,butyoushouldtakealookattheothers
aswell.NotethatjQueryprovidescrossbrowsersupportforsomeeventsandeventuliesyoumaynothave
seenbefore(e.g.InternetExplorer'smouseenterevent).

<exercisessection='11.2.3'>
1.LoadtheleeventHandlerTest2.htmlfromtheexamplepackintoabrowser.Takealookathow
thehandlerhasbeenaddedtothetablecellelements.Changethelesothatthehandlerisadded
ontheloadeventofthewindow.
2.Adda<textarea>elementtotheHTML.UsingjQuery,addahandlerthatrespondstothekeyUp
event,checkstheelementsvalueaributeforcertain"secretwords"andchangesthecolorsof
otherelementsonthescreeninresponse.

</exercises>

11.2.4ANoteonBestPractices
ItisactuallyconsideredbestpracceinJavaScript,whetheryou'reusingjQueryornot,towriteallofyourcode
insideawindowloadeventordocumentreadyevent.Evenotherhelperfunconsshouldbedenedinside
theseevents,likethis:
$(document).ready(function(){
ALLYOURCODEGOESHERE
});
orlikethis:
$(window).load(function(){
ALLYOURCODEGOESHERE
});
orifyou'renotusingjQuery,likethis:
window.onload=function(){
ALLYOURCODEGOESHERE
});
http://profsamscott.com/javascript/

119/137

11/15/2016

JavaScriptforSheridanStudents

Whenyoudothis,thebrowserwillwaitunlthepageisreadybeforeexecungyourcode.Soyoucanputyour
codeintothe<head>ofyourdocumentwithouthavingtoworryaboutwhethertheDOMisreadyatthatpoint.
Thisisabigadvantage.Anotheradvantageisthatnowallvariablesyouuse(includingfunconnames)become
localtotheanonymousfunconyouassigntothereadyorloadevent.Thisisgoodtoobecauseitminimizes
potenalnameconictswithotherJavaScriptorjQuerycodeorlibrariesyoumightbeusing.

11.2.5jQueryCallbackFunctions
ManyjQueryeectshaveparametersforcallbackfuncons.Nowthatyouunderstandabitmoreabout
funcons,youcanusetheseeecvelyaswell.Forexample,theslideDown()methodhasparameterscalled
duration(inmilliseconds)andcomplete.Thecompleteparametershouldbeafunconthatistobecalled
aertheslideoperaonhasnished.Afunconusedinthiswayisoenreferredtoasacallbackfuncon.
DoItYourself
LoadupthelecallBackTest.htmlfromtheexamplepackandslideupallthedivelements,likethis:
$("div").slideUp();
NowtrythefollowingintheJavaScriptconsoletoslidethemdownandturnthemredwhentheslideis
nished:
$("div").slideDown(1000,function(){
$(this).css("backgroundColor","red");
});

Nocetheuseofthethiskeywordabove.Intheexample
JavaConnection
shown,thecallbackfunconisgoingtogetcalledforevery
This(keyword).InJava,thethiskeyword
singledivelementonthepage.It'sjobistoturneachone
insideamethodalwaysreferstotheobject
red.Soeachmethefunconruns,itneedstoknowwhich
thatthemethodislinkedto.Thethis
objectitisbeingrunagainstthat'swhatthethiskeyword
isforit'savariablethathasbeenautomacallyloadedwith keywordinJavaScriptdoesthesamething.
theobjectthefunconisbeingappliedto.AsImenoned
earlier,youcanusethejQueryfuncontowrapanyDOM
elementinsideajQueryobject.Sothe$(this)selectorletsyouchainjQuerymethodsagainstwhichever
elementthefunconisbeingcalledagainst.
DoItYourself
Youmightbethinkingthatwedon'tneedthecallbackfuncon.Whynotjustdothefollowingin
callBackTest.html(reloadthepagebeforetryingit):
$("div").slideDown(1000).css("backgroundColor","red");
Queson:Whatwentwronghere?
Answer:ThecalltotheslideDownmethodonlystartstheslide.Oncetheslideisstarted,itletsthecss
funconrun.Sincethishappensveryquickly,itlooslikethecssfuncongoesrst,followedbythe
slideDown.

OnemorethingtonoceaboutcallBackTest.htmlisthatitisfollowingthebestpracceofdeningallcodeina
$(document).readyeventhandler.

http://profsamscott.com/javascript/

120/137

11/15/2016

JavaScriptforSheridanStudents

<exercisessection='11.2.5'>
1.AddtocallBackTest.htmlsothatwhentheusermousesoverdiv2,itslidesdownwards100pixels
andthenchangescolorandfadesout.
2.AddtocallBackTest.htmlsothatthereisathird<div>.Whenitisclicked,itshouldstartsliding
aroundthescreenrandomlyandnotstopunlitiscaught.(Thisisabittricky.)
3.JQueryalsocontainsacooltogglemethod.Thismethodtakestwofunconsasparametersand
thencallsoneortheothereachmethetogglefunconisused.Soyoucangobacktoexercise2a
from11.1.3andusethistogglemethodtoswitchthecolorsbackandforthoneachclick.

</exercises>

11.3DOMManipulationwithjQuery
AswithmostthingsinJavaScript,jQuerycanmakeDOMmanipulaonaloteasier.IfyougotothejQuery
[hp://jquery.com/]APIandlookintothe"Manipulaon"secon.Thereyouwillndamultudeofmethods
likethefollowing:
.html()

usethistochangetheinnerHTMLpropertyoftheselectedelements

.append()

appendsaDOMNodeoranHTMLstringaertheselectedelements

.before()

insertsasiblingDOMNodeoranHTMLstringbeforetheselectedelements

.after()

insertsasiblingDOMNodeaoranHTMLstringertheselectedelements

.remove()

removestheselectedelementsfromtheDOM

Rememberthatyoucanusethethiskeywordtorefertoeachselectedelement,andthentheselector
$(this)tochainjQuerymethods.
DoItYourself
TrythefollowingintheJavaScriptconsoleforthistextbook:
$("div.DIY").click(function(event){
$(this).remove();
});
NowtryclickingonanyDIYboxandwatchitgetremoved.NocethatnomaerwherewithintheDIYbox
youclick,thewholeboxisremoved.

http://profsamscott.com/javascript/

121/137

11/15/2016

JavaScriptforSheridanStudents

DoItYourself
TotrulyappreciatewhatjQueryisdoingforyouinthisinstance,trythisroughlyequivalentrawJavaScript
codeintheconsoleforthistextbook.
vardiys=document.querySelectorAll("div.DIY");
for(vari=0;i<diys.length;i++)
diys[i].onclick=function(event){
event.target.parentNode.removeChild(event.target);
};
NowclickonasentenceoralineofcodewithinaDIYbox.NocethatonlypartoftheDIYboxcontent
disappears.
InrawJavaScriptthetargetisthelowestlevelDOMnodethatwasclickedon(i.e.the<p>elementwithin
the<div>).ButjQuerymakessurethetargetyouwereinterestedin(i.e.theonethatmatchesthe
selector)istheoneremoved.

<exercisessection='11.3'>
1.InmorePracce.htmlfromtheexamplepackyou'llndHTMLtodenealiletableandfour
buons.AddeventsusingjQuerytothesebuonssotheydeleteandaddrowsandcolumnsfrom
thetable.Careful,itsabittrickierthanitsounds!

</exercises>

http://profsamscott.com/javascript/

122/137

11/15/2016

JavaScriptforSheridanStudents

12.AJAXwithjQuery
ThetextinthischaptermirrorsthetextinChapter10.Inthischapter,youlearntouseAJAXwiththejQuerylibraryandyoualso
learnalilebitabouthowtoworkwithXMLdata.InChapter10,youlearntouseAJAXwithrawJavaScriptandwithoutXML.

EvenifyoudontknowwhatAJAXis,youhaveexperienceditseects.WhenyoustarttypingintotheGoogle
[hp://www.google.com]searchbox,itdoesnttakelongbeforeyoustartgengsomesuggesonsabout
whattosearchfor.WhenyouviewyourlistoffriendsonFacebook[hp://www.facebook.com],itstartsyou
withasmalllist,andwhenyouscrolltotheboomofthatlist,itloadssomemoreforyou.Bothoftheseare
examplesofAJAXinacon.
BeforeAJAX,ifyouwantedtogetsomemorecontentfortheuser,youhadtogetthebrowsertoloadand
displayawholenewpage.WithAJAX,youcanlaunchanHTTPrequestfromJavaScript.Thenwhentheresponse
datacomesbackfromtheserver,youcanuseJavaScriptcodetoincorporatethisdataintothepagewithout
reloadingit.

12.1TheBasicIdea
ThetermAJAXwascoinedbyawebdevelopernamedJesseJamesGarre
[hp://www.adapvepath.com/ideas/ajaxnewapproachwebapplicaons]in2005.Attheme,AJAXwasa
termforanewwayofthinkingaboutandmakinguseofacolleconofalreadyexisngtechnologies.AJAX
standsforAsynchronousJavaScriptandXML.Letsbreakthisphrasedown.
JavaScript:Youalreadyknowwhatthisis.
Asynchronous:Youalreadyknowaboutthistoo,evenifyoudontrealizeit.Asynchronousprocessesare
processesthathappenoutsideoftheregularowoftheprogram.InAsynchronousprogramming,youmake
somekindofrequestthatwilltakemetocomplete,andthenconnueonwithothertasks.Inmanycasesyou
alsospecifyacallbackfuncontobetriggeredwhentheasynchronoustaskisnished.Yousawthisinthelast
chapterwhereIintroducedyoutojQuerysanimaonandeectsfunconslikeslideUp,fadeIn,and
animate.Becausetheseareasynchronoustasks,theusercansllinteractwiththewebpagewhilethe
animaonishappening.Iftheywerenotasynchronous,everythingwouldbeatastandsllunltheynished.
XML:Youmayhaveencounteredthisbefore.XMLstandsforeXtensibleMarkupLanguage.Itsagenericmarkup
languageforrepresenngstructureddata.ItlooksalotlikeHTML,butitcanbeusedtorepresentanykindof
data(sportsscores,theweather,ashoppinglist,etc.).XMLisonepossibleformatforthedatathatcomesfrom
theserverinresponsetoanAJAXrequest.Butyoucangetyourdatafromtheserverinanyformatyouwant.It
canbeXML,HTML,JSON(JavaScriptObjectNotaon)orevenjustplaintext.Nomaerwhatkindofdata
youregeng,mostdeveloperswouldsaythatifyouregengitasynchronouslybylaunchingarequestfroma
JavaScriptprogram,youreusingAJAX.

http://profsamscott.com/javascript/

123/137

11/15/2016

JavaScriptforSheridanStudents

12.2ANewWebAppArchitecture
Upunlnow,wehavebeenassumingawebapparchitecturethatlookslikethis.

Inthisarchitecture,anHTTPrequestislaunchedbytheusereitherbytypingaURL,clickingalink,orsubming
aform.(HTTPRequestsarealsogeneratedbythebrowsertoautomacallytoloadimages,CSSles,JavaScript
lesandotherresources.ButImignoringthatminorcomplicaoninthestoryImtellinghere.)Therequest
goestotheserverwhereeitheraleisretrievedandbecomestheHTTPResponse,orascriptisrunandthe
outputofthescriptbecomestheHTTPResponse.Whentheresponsearrivesatthebrowser,itinterpretsthe
HTMLandCSSinthedocumenttodisplaythepage,andexecutestheJavaScriptcommandsinthepage.Thenit
connuestorunJavaScriptinresponsetouserinteraconsandotherevents,refreshingthepageviewwhen
somethingchanges.Itdoesntgobacktotheserveragainunlesstheuserclicksalink,typesinaURL,orsubmits
aform.
ButwithAJAX,thelifecyclelooksabitdierent:

AnAJAXrequestisanHTTPRequestjustlikeanyother,andcanhaveGETandPOSTparametersassociatedwith
itjustlikeanyother.AttheserveritistreatedinexactlythesamewayasanyotherHTTPrequest.Theonly
dierenceiswhereitcamefrom:itwaslaunchedbyaJavaScriptfuncon.SinceHTTPRequestscantakemeto
completetheyaredoneasynchronouslyandyouregisteracallbackfuncontodealwiththeresponsewhenit
comes.(Whatwouldhappenifthiswasnotasynchronous?)
TheHTTPResponsefromtheserverisalsothesameasanyother.Theonlydierenceisthatwhentheresponse
arrivesattheclient,itwillnottriggerapagereload.Insteaditwillbepassedtothecallbackfunconyou
http://profsamscott.com/javascript/

124/137

11/15/2016

JavaScriptforSheridanStudents

registered.

12.3HowjQueryMakesAJAXEasier
AJAXqueriesarelaunchedusingtheXMLHpRequestobjectthatisbuiltintoallmodernbrowsers.Tolaunch
anAJAXrequestfromscratch,youwouldcreateanewXMLHpRequestobjectandbuilditupoverseverallines
ofcode,addingheaders,GETandPOSTparameters,registeringacallbackfuncon,etc.Itisnotthathardtodo
(formoreinformaon,gotothew3schoolsLearnAJAXsecon)butitsmessyandeasytomakemistakes.As
withsomanyothertasksinJavaScript,jQuerywillmakeyourlifealoteasierhere.

12.3.1ADataSource
YoucantdomuchinAJAXwithoutaccesstoadatasourceonaserversomewhere.Therearemanyexcellent
sourcesofdataonthewebthatarefreetouseinyourAJAXprograms.ForexampleYahoosYQL
[hp://developer.yahoo.com/yql/](YahooQueryLanguage[hp://developer.yahoo.com/yql/])canbeused
toretrieveinformaonaboutgeographiclocaons,weather,music,maps,andanumberofotherdomains.But
fornow,youneedaneasiertousesourceofinformaon.
DoItYourself
Intheexamplepack,youwillndaserversfoldercontainingtwoPHPscripts:a"meserver"named
servers/meServer.phpanda"LoremIpsumserver"namedservers/loremIpsumServer.php.
Loadthetwoserverlesbyclickingonthelinksabove(don'ttrytoopenthemonyourownmachine).
ThenreadovertheAPIstheydisplayandtrythemout.YoucanexperimentwiththeGETparametersby
typingthemintoaURL.Forexample,ifyouwantedtosetthepstartparameterto2andplengthto1,
youcoulddoitlikethis:
servers/loremIpsumServer.php?pstart=2&plength=1
AndifyouwanttotestPOSTparameterswiththeLoremIpsumserver,youcanusethe
servers/loremIpsumPostTest.htmllewhichusesa<form>elementwithitsmethodaributesetto
"post"tosendrequeststotheLorumIpsumserver.
Ifyou'veforgoenwhatallthismeans,youmayneedtorevieww3schoolsorasimilarsourcetorefresh
yourmemoryaboutGETandPOSTandPHPFormHandling.

http://profsamscott.com/javascript/

125/137

11/15/2016

JavaScriptforSheridanStudents

DoItYourself
TheLoremIpsumandTimeserverswillbeusedasatestbedfortheAJAXexamplesandexercisesto
come.ButPHPleswillnotrunoutsideawebserver,andAJAXrequeststhatdonotcomefromthesame
webserverwillusuallyberejectedduetotheSameOriginPolicy.Soyouwillneedtonaildownoneofthe
twofollowingwebserveroponstodoanyfurtherworkinthischapter.
1.InstallWampServerorXAmpponyourmachinetoturnitintoawebserver,or
2.Findsomewebspace(e.g.mobile.sheridanc.on.ca)anduploadyourprogramstoitfortesng.
IftaketherstoponandyouareusingNetBeans[hps://netbeans.org/],youshouldbeabletousea
projectoftypePHPandsetupanoponsothatNetBeansautomacallycopieslestotheWampServer
orXAmpp[hp://www.apachefriends.org/en/xamppwindows.html]serverrunningonyourmachine.If
yougetthatright,youcan"run"yourPHPprojectsfromNetBeans[hp://www.netbeans.org].
Takeamomenttosetyourselfupbeforemovingon.

12.3.2YourFirstAJAXRequest
ThejQueryAPIlistsanumberofshortcutandhelperfunconstomakeyourlifeeasierusingAJAX.Wewillfocus
onjusttwohere,bothlistedundertheheading"shorthandmethods"intheAJAXporonoftheAPI.Thetwo
methodsarejQuery.get()andjQuery.post().ThenamejQueryisjustanotherwaytoaccessthe
familiar$object,sowewilluse$.get()and$.post()intheexamplesbelow.
Asyoumighthaveguessed,thesefunconsareforsendingGETandPOSTrequests,respecvely.Otherthan
theirname,thesyntaxofthesetwofunconsisidencal.Therearethreeparametersofnote:
1.URL:AstringparameterthatencodesthebaseURLoftherequest.ThiscanbeanabsoluteURLoritcanbe
relavetoyourcurrentlocaon.
2.Data:ThisisamapofyourGETorPOSTparameters.
3.CallBack:ThisisafunconthatwillbecalledwhentheHTTPResponsearrives.

http://profsamscott.com/javascript/

126/137

11/15/2016

JavaScriptforSheridanStudents

DoItYourself
LoadajaxTime.htmlfromtheexamplepackintoadesktopbrowser(ifyouareworkingwithyourown
copy,rememberthatyouneedtohaveaPHPserverrunningoritwon'tworkseetheprevioussecon).
Ignorethecontentsofthepagefornow.JustopentheJavaScriptconsoleandlaunchyourrstAJAX
request,likethis:
$.get(
"servers/timeServer.php",
{
timezone:"Canada/Eastern",
request:"time"
},
function(data){
alert(data);
}
);
Theaboveshouldpopupthecurrentmeforyouinanalertbox.

Therearethreeparametersinthe$.get()methodabove.TherstistheURL.Notethatitisspeciedrelave
towhereeverthebrowserisnow.ThesecondisamapofGETparameters(thisobjecthasasyntaxexactlylike
themapyouhadtopasstotheanimate()methodinthepreviouschapter).Together,theURLanddata
parametersaboveareequivalenttothefollowing:
/servers/timeServer.php?timeZone=Canada/Eastern&request=time
Thenalparameteristhecallbackfuncon.Thisfunconcouldtakeupto3parameters,butwewillonlybe
usingtherst(data),whichcontainsthetextoftheresponsefromtheserver.
DoItYourself
RepeatthecommandfromthelastDIYbox,butthismeuse$.post()insteadof$.get().
Nowtrychangingsomeoftheparameterstogetthedayormonth,oruseadierentmezone.
Nowtrychangingthecallbackfunconsoitputsthetextsomewhereonthescreen(maybeinthe
innerHTMLofall<h1>elements,orinthevalueaributeofall<input>elements).
Finally,tryouttheforminterfaceprovidedontheajaxTime.htmlpage.Doyouthinkyoucouldwritethe
codeforthispagenow,givenwhatyouknowaboutAJAXandjQuery?

http://profsamscott.com/javascript/

127/137

11/15/2016

JavaScriptforSheridanStudents

12.3.3AJAXFromaWebPage
TheJavaScriptcodebelowisfromtheajaxTime.htmlexample.Takeamomenttoreaditoverandtryto
understandit.
$(document).ready(function(){
varlaunchAjax=function(){
$.get(
"servers/timeServer.php",
{
timezone:$("[name=timezone]").val(),
request:$("[name=type]").val(),
delay:$("[name=delay]").val(),
},
function(data,textStatus,jqXHR){
$("#result").html(data);
};
)};
$("#ajaxButton").click(launchAjax);
});
Therstthingtonoteisthatallthecodeisinsidethedocumentobject'sreadyeventhandler.Thisisjust
followingthebestpraccesthatwereintroducedinthelastchapter.
ThesecondthingtonoceisthatthelaunchAjaxfunconcontainsacallto$.get()thatshouldlookvery
familiarfromtheprevioussecon.Theonlydierenceisthatonemoreparameterisset(delay)andthevalues
foreachparameterarecomingfromtheformelements.Also,thecallbackfunconisplacingthedataintothe
innerHTMLoftheelementwithanidof"result".
Thesyntax$("[attribute=value]")isusedtoselectalltheelementswithaparcularaributevalue.In
thiscaseitsbeingusedtoretrievenamedformelements.Theprogrammercouldjustaseasilygivethemid
aributesanduse$("#id").
AerthedenionofajaxFunction,thefunconisaddedasaclickeventhandlerontotheelementwith
anidof"ajaxBuon".ThiscouldhavebeendoneinHTML,butagain,itisconsideredbestpraccetodoithere.
Nowyouhavetwodatasources(servers/loremIpsumServer.phpandservers/meServer.php)andaworked
example(ajaxTime.html).Itsmetobuildsomethingofyourown.

http://profsamscott.com/javascript/

128/137

11/15/2016

JavaScriptforSheridanStudents

<exercisessection='12.3.3'>
1.Taketheleservers/loremIpsumPostTest.htmlfromtheexamplepackandchangeitsothat
insteadoflaunchingabrandnewPOSTrequestandreloadingthepage,itinsteadlaunchesanAJAX
queryanddisplaystheresultbelowtheform.
2.Intheexercisesfolder,lookatthelendLorem.html.YouhavetheHTMLandCSShereforagame.
YoujusthavetollintheJavaScript.ThisgamewillpulloutarandompieceofLoremIpsumtext
fromtheserver,usinganAJAXquery.Thenitwillallowtheusertoguesswherethetextcamefrom,
usingmoreAJAXqueriestocheckwhethertheywererightornot.Seethecommentsinthe
ndLorem.htmllefordetailedinstrucons.
3.Intheexamplepackyouwillndmore.htmlanditsassociatedles.AddthenecessaryJavaScript
codesothatthispageallowstheusertoloadoneparagraphatamefrom
servers/loremIpsumServer.php.Whentheyrstload,theyshouldseetherstparagraph,retrieved
withAJAX.Thenwhenevertheyhitthe"more"buon,theyshouldgetthenextparagraphin
sequence.

</exercises>

12.4WhatToDoWhileYouWait
Becausenetworkscanbeslow,AJAXrequestscansomemestakeafewsecondstocomplete.Ifthingsdon't
happeninstantly,itcancausetheusertostartpressingbuonsoverandoveragain,orbehavinginother
destrucvewayswhichcouldenduplaunchingmoreandmoreAJAXrequests.Thisisaproblemyouhaveto
thinkaboutwheneveryouuseAJAX.
DoItYourself
LoadupajaxTime.htmlfromtheexamplepack,setthedelayontheformto15seconds,andsetthe
requestto"me",thenhitthe"AJAX!"Buon.Thiswillsendarequesttotheservers/meServer.php
pagewhichinstructsthephpscriptstopausefor15secondsbeforecompleng.Sothissimulatesadelay
overaslownetwork.
Whileyourewaingforyourrstrequest,setthedelaybackto0andtrysomedierentrequests
(anythingotherthan"me").Aer15seconds,theoriginalrequestwillgetitsresponseandthiswill
disruptwhatyouarecurrentlydoing.

12.4.1SomeOptions
TheusualsoluontothisproblemistocontroltheusersomehowwhileyouarewaingfortheAJAXrequestto
complete.Forexample,iftheuserclickssomethingtoloadmorecontent,youcoulddothefollowing:
1.Intheclickhandler,disablethebuontheuserjustclicked,andperhapsgivethemsomevisualindicaon
thatwearewaingforsomethingtoload.
2.Inthecallbackfuncon,reenablethebuon.
ThiswillensurethatonlyoneAJAXrequestisdealtwithatame.
AnotherapproachmightbetohaveaglobalvariablewithanamelikewaitingForAJAX:
http://profsamscott.com/javascript/

129/137

11/15/2016

JavaScriptforSheridanStudents

1.InializewaitingForAJAXtofalse.
2.Intheclickhandler,checkifwaitingForAJAXistrue.Ifitis,givetheuseranerrormessage.Ifnot,launch
theAJAXqueryandsetwaitingForAJAXtotrue.
3.Inthecallbackfuncon,setwaitingForAJAXbacktotofalse.

<exercisessection='12.4.1'>
1.AddcodetotheajaxTime.htmlpagesothattheuserhastowaitunlthepreviousrequesthas
completedbeforeanewonewillbelaunched.Youcanuseeitherofthetwostrategiesabove.Then
testitbysengthedelayparameter.
2.Repeattheabove,butthismeusetheothersuggestedstrategyforwhattodowhileyouwait.
3.Alteryoursoluontothemore.htmlexercisefromtheprevioussecon.SetuptheAJAXrequests
toincludeashortdelayandmakesureyoudisabletheuserwhiletheywaitfortheirnext
paragraph.

</exercises>

12.4.2AJAXErrorHandling
TheonlyproblemwiththeabovestrategyisthatsomemesAJAXrequestsdonotcomplete(theserverisdown,
theresatypointheURL,etc.).Inthiscase,thecallbackfunconisnevercalled,andtheusercouldendup
waingforever.
IntheAJAXseconofthejQueryAPI,theresasubsecononGlobalAJAXEventHandlers
[hp://api.jquery.com/category/ajax/globalajaxeventhandlers].Thissecondescribesthe
$(document).ajaxError()method.Youcanusethisfuncontoregisteranerroreventhandleraachedto
anyelementorelements.ThenifanAJAXerrorhappens,thisfunconwillbecalledandyoucanreenablethe
appropriatebuonsorresettheappropriatevariables.

<exercisessection='12.4.2'>
1.AddanAJAXErroreventhandlertoajaxTime.htmlsothatthepageleavesits"waing"stateif
thereisanerror.Totest,youcancreatea404FileNotFounderrorbytemporarilyrenamingor
movingtheservers/meServer.phple.
2.AddanAJAXErroreventhandlertoyoursoluontothemore.htmlexercisefromtheprevious
secons.Makesuretheerrorhandlerworksandgetstheuseroutofthewaingstate.

</exercises>

12.5WorkingWithXMLData
YoucanuseAJAXrequeststoretrieveanytypeofdocumentthatisaccessiblethroughHTTPrequestsonthe
WorldWideWeb.ThesedocumentsdonothavetobeinXMLformatdespitethe"X"inthenameAJAX(indeed
sofarwehaveonlybeenusingplaintextles).Butmostoftheme,informaondoescomewithstructure
aached,andXMLisbyfarthemostcommonwayofrepresenngthatstructure.

http://profsamscott.com/javascript/

130/137

11/15/2016

JavaScriptforSheridanStudents

12.5.1BasicXMLStructure
Here'ssomedatafromabookstore,adaptedfromw3Schools.
cooking,EverydayItalian,GiadaDeLaurentiis,2005,30.00
web,xQueryKickStart,JamesMcGovern,PerBothner,KurtCagle,JamesLinn,
VaidyanathanNagarajan,2003,49.99
web,paperback,LearningXML,ErikT.Ray,2003,39.95
programming,JavaScriptforSheridanStudents,SamScott,2013,0.00
Thisinformaonisalilehardtoread,butifyoulookcarefullyyoumightnoceitappearstobedatafor4
dierentbooks,alongwithbooktype,tle,authors,yearofpublicaon,andprice.
HereisthesameinformaoninXMLformat:
<bookstore>
<bookcategory="cooking">
<titlelang="en">EverydayItalian</title>
<author>GiadaDeLaurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<bookcategory="web">
<titlelang="en">XQueryKickStart</title>
<author>JamesMcGovern</author>
<author>PerBothner</author>
<author>KurtCagle</author>
<author>JamesLinn</author>
<author>VaidyanathanNagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>
<bookcategory="web"cover="paperback">
<titlelang="en">LearningXML</title>
<author>ErikT.Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
<bookcategory="programming">
<titlelang="en">JavaScriptforSheridanStudents</title>
<author>SamScott</author>
<year>2013</year>
<price>0.00</price>
</book>
</bookstore>
Nocehowmucheasieritistoseethestructureofthisdocument.HTMLliketagsarebeingusedtoprovideit
withstructureandmakeiteasiertoworkwith,bothformachinesandforhumans.WheneverybodyusesXML,
datacanbemoreeasilytransportedandsharedbetweenapplicaons.

http://profsamscott.com/javascript/

131/137

11/15/2016

JavaScriptforSheridanStudents

12.5.2XMLvs.HTML
Here'salistofsimilariesbetweenXMLandHTML:
1.XMLandHTMLarebothmarkuplanguageswithtagsthatdeneelementscontainingdata.Forexample,
thetag<author>JKRowling</author>denesanelementoftype<author>withthecontents"JK
Rowling".
2.XMLandHTMLtagscancontainaributes.Forexample<bookcategory="cooking">isthestartof
anelementoftype<book>thatcontainstheaributecategory.Aributesaredescripveinformaon,or
metadatathatprovidesaddionaldescripveinformaonaboutthecontentsoftheelement.
3.XMLandHTMLdocumentsmusthaveasinglerootelementthatcontainsalltheotherelements.InHTML,
thisisthe<html>element.InXMLitcanbeanyelementyouwant.Whatistherootelementinthebook
storeexamplefromthelastsecon?
4.XMLandHTMLcommentscanbeaddedusing<!>.
5.BothXMLandHTMLdocumentsarerepresentedinbrowsersusingaDocumentObjectModel(DOM).
Moreonthisinamoment.
Andhere'salistofdierences:
1.XMLdocumentsdonotdoanything.XMLisdesignedonlytocarrystructureddata,nottodisplayit.XML
tagsandaributescannotbereadascommandslikeHTMLtagsandaributessomemescanbe.
2.XMLhasnopredenedtags.Youcanuseanysetofsinglewordtagnamesyouwant.Youcanalsodene
yourowndocumenttypes,butwewontgetintothathere.
3.XMLtagsandaributesarecasesensive.Forexample,<p>and<P>arethesametaginHTML,butwould
denetwodierentelementtypesinXML.
4.XMLaributevaluesmustbequoted.InHTMLyoucansomemesgetawaywith<pid=myparagraph>
</p>.InXMLthiswouldcauseasyntaxerrorbecausetherearenoquotaonmarksaround
myparagraph.
5.XMLtagsmustbeclosed.InHTMLtherearemanyemptytags(<br>,<img>,etc.)thatdonotneeda
closingtag.InXMLyoumusteitherprovideaclosingtag,orifthetaghasnodatayoucanuseaselfclosing
taglikethis<searchquery="AJAX"/>.Selfclosingtagsendwith"/>".
6.XMLtagsmustbeproperlynested.Nesngistheplacingofonestructurewithinanother.InHTML,youcan
dothis:<p>AJAX<b>is</p>cool</b>.Thisisok,eventhoughthe<b>tagispartlyinsideandpartly
outsidethe<p>tag.InXMLthiswouldcauseasyntaxerror.
7.XMLsyntaxerrorswillusually(silently)crashanapplicaon.UnlikeHTML,whichalwaystriestomakethe
bestofbadsyntax,XMLparserswillstopiftheyndsyntaxerrors.

12.5.3NavigatingtheXMLDOM
WhenyougointotheChromedeveloperconsoleandlookatthe"elements"viewofthedocument,youare
lookingattheHTMLDocumentObjectModel(DOM).WhenyouworkwiththeJavaScriptdocumentobject,
anduseittomakechangestoanHTMLpage,youareaccessingandmodifyingtheHTMLDOM.
XMLdocumentscanalsoberepresentedandaccessedusingaDOM.Theactofconverngatextrepresentaon
ofanXMLleintoaDOMobjectiscalledparsing.ChromecontainsaspecialJavaScriptobjectcalled
http://profsamscott.com/javascript/

132/137

11/15/2016

JavaScriptforSheridanStudents

DOMParserthatdoesthisveryjob.
DoItYourself
Openyourbrowser'sJavaScriptconsoleandtypethefollowing(ortosavetypingorcopyingandpasng,
youcanusetheprebakedexamplenote.htmlintheexamplepack):
varxmldoc="<notetype='reminder'><to>Sam</to><from>Anne</from>
<text>Don'tforgetthegroceries.</text></note>";
varparser=newDOMParser();
vardom=parser.parseFromString(xmldoc,"text/xml");
TherstcommandsimplydenesastringvariablewithXMLdatainit.Thesecondcommandcreatesa
newDOMParserobject.Thethirdcommandparsesthevariableandcreatesadocumentobject.
Nowtypedom,openthedocumentobjectandexaminethestructure.Dothesamefordocument.Note
anysimilariesordierencesyound.

TheXMLDOMtreeisconstructedjustliketheHTMLDOMtreesyoulearnedaboutinChapters4and10.The
simple<note>exampleabovehasthefollowingstructure:

Here'saterminologyreminder.Inthepictureabove,thereare13Nodes(8areDOMNodesand5are
TextNodes,includingwhitespaceTextNodesseeChapter11).Therootnodeis<note>.Ithasthreechildrenor
childnodes.Eachofthechildrensharethesameparent.Thelinefromparenttochildmeansthatthechildis
containedwithintheparent.Iftherearemanychildren,theyareshowninorderfromletoright.Nodesthat
shareaparentaresiblings(thisisthegenderneutraltermfor"brother"or"sister").Eachofthechildrenof
<note>hastwosiblings.
ADOMobjectinJavaScriptisacolleconofNodeobjectsthatarealllinkedtogetherinatreestructure.Thisis
truewhethertheDOMisforanXMLdocumentoranHTMLdocument,somostofwhatyoulearnedaboutthe
HTMLDOMinChapters4,7,and10appliestotheXMLDOMaswell.Insteadofdocumentattheroot,yound
aDOMobject,andeverypieceoftextalsoappearsasaspecialchildnodecalledaTextNode.
DoItYourself
GobacktothebookstoreexamplefromapreviousseconanddrawtheDOMforthisexampleonapiece
ofpaper.

http://profsamscott.com/javascript/

133/137

11/15/2016

JavaScriptforSheridanStudents

AswiththeHTMLDOM,youcannavigatethestructurebymovingupanddownalongthelinkswiththe
followingeldsandmethods.
childNodes:

returnsanarrayofallchildnodesofthecurrentnode

firstChild:

returnstherstchildofthecurrentnode

lastChild:

returnsthelastchildofthecurrentnode

nextSibling:

returnsthesiblingtotherightofthecurrentnode

previousSibling:

returnsthesiblingtotheleofthecurrentnode

data:

ifthisisatextnode,getsthetext

getAttribute():

(newtoXMLNodes)ifthespeciedaributeexistsforthecurrentnode,returnsits
value

DoItYourself
Connuethe<note>examplefromtheprevioussession(note.html).Trythe
followinginthebrowserconsoleandnotetheresults:
dom.childNodes
dom.firstChild
dom.lastChild
dom.childNodes[0]
dom.firstChild.getAttribute("type")
Canyouexplaintheresultineachcase?
Nowtrydom.rstChild.childNodesandexplaintheresult.
Nowforachallenge.Findasmanywaysasyoucantogetthetextofthe
<from>element.Rememberthatthetextisaspecialchildnode,notanaributeoravalue.

Justlikewiththedocumentobject,youcanalsousetagnamesandidaributes(iftheXMLdocumenthas
them)tondparcularelementsinsidetheDOM.ThemethodsarethesameasfortheHTMLDOM:
getElementById,getElementsByTagNames,querySelectorandquerySelectorAll.
Thesemethodscanbeusedtosearchwithinanynode,notjusttherootnode.Forexampleifyouwantedthe
authornameofthethirdbookinthebookstoreexample,youcouldloadtheXMLDOMintoavariablecalled
domanddothefollowing:
dom.getElementsByTagName("book")[2].getElementsByTagName("author")[0]
TherstgetElementsByTagNameretrievesalistofallthe<book>elements.The[2]retrievesthethirdnode
fromtheresulngarrayof<book>elements.ThenthenextgetElementsByTagNamelooksjustinsidethat
nodefor<author>elements,andthe[0]retrievestherstonefromthearrayoffoundnodes.

http://profsamscott.com/javascript/

134/137

11/15/2016

JavaScriptforSheridanStudents

DoItYourself
Usingthe<note>exampleagain(note.html),ndtwomorewaystogetthetextofthe<from>element,
usingoneofthetwoconveniencemethodsabove.

12.5.4LoadingXMLWithAJAX
WhenyouusejQuery,loadinganXMLdocumentisalmostaseasyasloadingplaintext.Youcanusethesame
commands($.getand$.post)withexactlythesameparametersasbefore.Theonlydierenceisthatthe
dataparameterofthecallbackfunconwillbeconvertedbyjQueryintoanXMLdocumentusingthe
DOMParser.
TroubleshoongTip
IfyouaretryingtoputsomedatafromanXMLle(sayaprovincename)intoyouroutputandyoukeepgeng
thingsthatlooklikethis:
[objectText]
ThismeansthatyouaretryingtoprintoutaTextnode.Butyoudontwanttoprintthewholenode,justthe
dataitcontains.Todothisyouneedtoaccessthedataeld.
Forexample,thiswontwork:
textOutput+=dom.getElementsByTagName("name").firstChild
Dothisinstead:
textOutput+=dom.getElementsByTagName("name").firstChild.data

http://profsamscott.com/javascript/

135/137

11/15/2016

JavaScriptforSheridanStudents

<exercisessection='12.5.4'>
Thisstucanbetricky!Makesureyougiveyourselflotsofme.Perhapsevenworkingwithapartner
wouldbeagoodidea.
1.LoadajaxSandbox.htmlfromtheexamplepackintoabrowser,thenopentheJavaScriptconsole.
(Rememberthatthehtmllemustbehostedonaserveralongwiththerestofthelesforthe
examplepack.)
a.UsethefollowingcommandtoloadthedatafromtheXMLData/note.xmlle:
$.get("XMLData/note.xml",function(data){x=data;});
Notethattherearenoparametersrequired,soweareonlyusingtheURLandthecallback
funconparameters.Thecallbackfunconsimplystoresthedataparameterintoaglobal
variablex.
b.Onceyouhaveexecutedthiscommand,openthexobjectandtakealookatitsstructureto
makesureitworked.
c.WriteaJavaScriptexpressionthatretrievesthe<note>elementfromx.Nocethatthe
rootofxactuallyhastwochildreninsteadofone.Whyisthat?
d.NowwriteaJavaScriptstatementtoloadXMLData/bookstore.xmlthroughAJAX.Inthe
callbackfuncon,putanalertstatementthatdisplaystheauthornameandlanguage
aributeforthesecondbookinthestore.
2.Completetheexercisedescribedintheheadercommentsofthecdcatalog.htmlle.
3.Completetheexercisedescribedintheheadercommentsofthecanada.htmlle.
4.CompletetheexercisedescribedintheheadercommentsoftheloremIpsum.htmlle.

</exercises>

12.5.5LearningMoreAboutXML
XMLisabigtopicandthereislotsmorethatcanbesaid.Forthosewhowanttogofurther,W3Schoolshas
goodtutorialsonallthingsXML.Onthefrontpageofw3schools,scrolldowntoXMLtutorialsandreadthrough
theLearnXMLandLearnXMLDOMtutorialsinparcularformoreinformaon.

http://profsamscott.com/javascript/

136/137

11/15/2016

http://profsamscott.com/javascript/

JavaScriptforSheridanStudents

137/137

You might also like