Pro HTML5 Programming, 2nd Edition
For your convenience Apress has placed some of the front
matter material after the index. Please use the Bookmarks
and Contents at a Glance links to access them.
iv Contents at a Glance
Foreword...............................................................................................................
AbouttheAuthors................................................................................................ Acknowledgments ............................................................................................. Chapter1:OverviewofHTML5................................................................................ Chapter3:WorkingwithScalableVectorGraphics.............................................. Chapter5:UsingtheGeolocationAPI ................................................................. Chapter7:UsingtheWebSocketAPI .................................................................. Chapter9:WorkingwithDrag-and-Drop ............................................................ Chapter10:UsingtheWebWorkersAPI............................................................. Chapter12:CreatingOfflineWebApplications.................................................. Index ...................................................................................................................
C H A P T E R 1 Overview of HTML5
ThisbookisaboutHTML5Programming.BeforeyoucanunderstandHTML5programming,however, youneedtotakeastepbackandunderstandwhatHTML5is,abitofthehistorybehindit,andthe differencesbetweenHTML4andHTML5.
Inthischapter,wegetrighttothepracticalquestionstowhicheveryonewantsanswers.Why HTML5,andwhyalltheexcitementjustnow?WhatarethenewdesignprinciplesthatmakeHTML5 trulyrevolutionary—butalsohighlyaccommodating?Whataretheimplicationsofaplugin-free paradigm;what’sinandwhat’sout?What’snewinHTML,andhowdoesthiskickoffawholenewerafor webdevelopers?Let’sgettoit.
TheStorySoFar—TheHistoryofHTML5
HTMLgoesbackalongway.ItwasfirstpublishedasanInternetdraftin1993.The’90ssawan enormousamountofactivityaroundHTML,withversion2.0,versions3.2,and4.0(inthesameyear!), andfinally,in1999,version4.01.Inthecourseofitsdevelopment,theWorldWideWebConsortium (W3C)assumedcontrolofthespecification.
Aftertherapiddeliveryofthesefourversionsthough,HTMLwaswidelyconsideredadead-end;the focusofwebstandardsshiftedtoXMLandXHTML,andHTMLwasputonthebackburner.Inthe meantime,HTMLrefusedtodie,andthemajorityofcontentonthewebcontinuedtobeservedas HTML.ToenablenewwebapplicationsandaddressHTML’sshortcomings,newfeaturesand specificationswereneededforHTML.
Wantingtotakethewebplatformtoanewlevel,asmallgroupofpeoplestartedtheWebHypertext ApplicationWorkingGroup(WHATWG)in2004.TheycreatedtheHTML5specification.Theyalsobegan workingonnewfeaturesspecificallygearedtowebapplications—theareatheyfeltwasmostlacking.It wasaroundthistimethatthetermWeb2.0wascoined.Anditreallywaslikeasecondnewweb,asstatic websitesgavewaytomoredynamicandsocialsitesthatrequiredmorefeatures—alotmorefeatures.
TheW3CbecameinvolvedwithHTMLagainin2006andpublishedthefirstworkingdraftfor HTML5in2008,andtheXHTML2workinggroupstoppedin2009.Anothertwoyearspassed,andthatis wherewestandtoday.BecauseHTML5solvesverypracticalproblems(asyouwillseelater),browser vendorsarefeverishlyimplementingitsnewfeatures,eventhoughthespecificationhasnotbeen completelylockeddown.Experimentationbythebrowsersfeedsbackintoandimprovesthe specification.HTML5israpidlyevolvingtoaddressrealandpracticalimprovementstotheweb platform.
MOMENTS IN HTML
Briansays:“Hi,I’mBrian,andI’manHTMLcurmudgeon. CHAPTER1 OVERVIEWOFHTML5 Iauthoredmyfirsthomepagebackin1995.Atthetime,a‘homepage’wassomethingyoucreatedtotalk aboutyourself.Itusuallyconsistedofbadlyscannedpictures, <blink> tags,informationaboutwhereyou
livedandwhatyouwerereading,andwhichcomputer-relatedprojectyouwerecurrentlyworkingon.
Myselfandmostofmyfellow‘WorldWideWebdevelopers’wereattendingoremployedbyuniversities.
Atthetime,HTMLwasprimitiveandtoolswereunavailable.Webapplicationshardlyexisted,otherthana fewprimitivetext-processingscripts.Pageswerecodedbyhandusingyourfavoritetexteditor.Theywere updatedeveryfewweeksormonths,ifever. We’vecomealongwayinfifteenyears. Today,itisn’tuncommonforuserstoupdatetheironlineprofilesmanytimesaday.Thistypeof interactionwouldn’thavebeenpossibleifnotforthesteady,lurchingadvancesinonlinetoolsthatbuilton eachpreviousgeneration.Keepthisinmindasyoureadthisbook.Theexamplesweshowheremayseemsimplisticattimes,but
thepotentialislimitless.Thoseofuswhofirstused <img> tagsinthemid-1990sprobablyhadnoideathatwithintenyears,manypeoplewouldbestoringandeditingtheirphotosonline,butweshouldhave
predictedit.Wehopetheexampleswepresentinthisbookwillinspireyoubeyondthebasicsandtocreatethenew
foundationoftheWebforthenextdecade.” TheMythof2022andWhyItDoesn’tMatter
TheHTML5specificationthatweseetodayhasbeenpublishedasaworkingdraft—itisnotyetfinal.So whendoesitgetcastinstone?Herearethekeydatesthatyouneedtoknow.Thefirstis2012,whichis thetargetdateforthecandidaterecommendation.Theseconddateis2022,whichistheproposed
recommendation.Wait!Notsofast!Don’tclosethisbooktosetitasidefortenyearsbeforeyouconsider
whatthesetwodatesactuallymean. Thefirstandnearestdateisarguablythemostimportantone,becauseoncewereachthatstage,
HTML5willbecomplete.That’sjustaroundthecorner.Thesignificanceoftheproposed recommendation(whichwecanallagreeisabitdistant)isthattherewillthenbetwointeroperable implementations.Inotherwords,twobrowsersequippedwithcompletelyinteroperable implementationsoftheentirespecifications—aloftygoalthatactuallymakesthe2022deadlineseem ambitious.Afterall,wehaven’tevenachievedthatinHTML4andonlyrecentlyforCSS2!
Whatisimportant,rightnow,isthatbrowservendorsareactivelyaddingsupportformanyverycool newfeatures,andsomeofthosearealreadyintheFinalCallforcommentsphase.Dependingonyour audience,youcanstartusingmanyofthesefeaturestoday.Sure,anynumberofminorchangeswill needtobemadedowntheroad,butthat’sasmallpricetopayforenjoyingthebenefitsoflivingonthe cuttingedge.Ofcourse,ifyouraudienceusesInternetExplorer6.0,manyofthenewfeatureswon’twork andwillrequireemulation—butthat’sstillnotagoodreasontodismissHTML5.Afterall,thoseusers, too,willeventuallybejumpingtoalaterversion.ManyofthemwillprobablymovetoInternetExplorer 9.0rightaway,andthatversionofIEsupportsmanymoreHTML5features.Inpractice,thecombination ofnewbrowsersandimprovingemulationtechniquesmeansyoucanusemanyHTML5featurestoday orintheverynearfuture.
CHAPTER1 OVERVIEWOFHTML5
WhoIsDevelopingHTML5?
Weallknowthatacertaindegreeofstructureisneeded,andsomebodyclearlyneedstobeinchargeof thespecificationofHTML5.Thatchallengeisthejobofthreeimportantorganizations:
- WebHypertextApplicationTechnologyWorkingGroup(WHATWG):Foundedin
2004byindividualsworkingforbrowservendorsApple,Mozilla,Google,and Opera,WHATWGdevelopsHTMLandAPIsforwebapplicationdevelopmentand providesopencollaborationofbrowservendorsandotherinterestedparties.
- WorldWideWebConsortium(W3C):TheW3CcontainstheHTMLworkinggroup thatiscurrentlychargedwithdeliveringtheirHTML5specification.
- InternetEngineeringTaskForce(IETF):Thistaskforcecontainsthegroups responsibleforInternetprotocolssuchasHTTP.HTML5definesanew WebSocketAPIthatreliesonanewWebSocketprotocol,whichisunder developmentinanIETFworkinggroup.
ANewVision
HTML5isbasedonvariousdesignprinciples,spelledoutintheWHATWGspecification,thattruly embodyanewvisionofpossibilityandpracticality.
- Compatibility
- Utility
- Interoperability
- Universalaccess
CompatibilityandPavingtheCowPaths
Don’tworry;HTML5isnotanupsettingkindofrevolution.Infact,oneofitscoreprinciplesistokeep everythingworkingsmoothly.IfHTML5featuresarenotsupported,thebehaviormustdegrade gracefully.Inaddition,sincethereisabout20yearsofHTMLcontentoutthere,supportingallthat existingcontentisimportant.
Alotofefforthasbeenputintoresearchingcommonbehavior.Forexample,Googleanalyzed millionsofpagestodiscoverthecommonIDandClassnamesforDIVtagsandfoundahugeamountof repetition.Forexample,manypeopleusedDIV id="header"tomarkupheadercontent.HTML5isall aboutsolvingrealproblems,right?Sowhynotsimplycreatea<header>element?
AlthoughsomefeaturesoftheHTML5standardarequiterevolutionary,thenameofthegameis evolutionnotrevolution.Afterall,whyreinventthewheel?(Or,ifyoumust,thenatleastmakeabetter one!)
UtilityandthePriorityofConstituencies
TheHTML5specificationiswrittenbaseduponadefinitePriorityofConstituencies.Andasprioritiesgo, “theuserisking.”Thismeans,whenindoubt,thespecificationvaluesusersoverauthors,over implementers(browsers),overspecifiers(W3C/WHATWG),andovertheoreticalpurity.Asaresult, HTML5isoverwhelminglypractical,thoughinsomecases,lessthanperfect.
CHAPTER1 OVERVIEWOFHTML5
Considerthisexample.ThefollowingcodesnippetsareallequallyvalidinHTML5: id="prohtml5" id=prohtml5
ID="prohtml5" Sure,somewillobjecttothisrelaxedsyntax,butthebottomlineisthattheenduserdoesn’treally care.We’renotsuggestingthatyoustartwritingsloppycode,butultimately,it’stheenduserwhosuffers whenanyoftheprecedingexamplesgenerateserrorsanddoesn’trendertherestofthepage.
HTML5hasalsospawnedthecreationofXHTML5toenableXMLtoolchainstogeneratevalid HTML5code.TheserializationsoftheHTMLortheXHTMLversionshouldproducethesameDOM treeswithminimaldifferences.Obviously,theXHTMLsyntaxisalotstricter,andthecodeinthelasttwo exampleswouldnotbevalid.
SecurebyDesign
AlotofemphasishasbeengiventomakingHTML5securerightoutofthestartinggate.Eachpartofthe specificationhassectionsonsecurityconsiderations,andsecurityhasbeenconsideredupfront.HTML5 introducesaneworigin-basedsecuritymodelthatisnotonlyeasytousebutisalsousedconsistentlyby differentAPIs.Thissecuritymodelallowsustodothingsinwaysthatusedtobeimpossible.For example,itallowsustocommunicatesecurelyacrossdomainswithouthavingtoreverttoallkindsof clever,creative,butultimatelyNon-securehacks.Inthatrespect,wedefinitelywillnotbelookingback tothegoodolddays.
SeparationofPresentationandContent
HTML5takesagiantsteptowardthecleanseparationofpresentationandcontent.HTML5strivesto createthisseparationwhereverpossible,anditdoessousingCSS.Infact,mostofthepresentational featuresofearlierversionsofHTMLarenolongersupported,butwillstillwork,thankstothe compatibilitydesignprinciplementionedearlier.Thisideaisnotentirelynew,though;itwasalreadyin theworksinHTML4TransitionalandXHTML1.1.Webdesignershavebeenusingthisasabestpractice foralongtime,butnow,itisevenmoreimportanttocleanlyseparatethetwo.Theproblemswith presentationalmarkupare:
- Pooraccessibility
- Unnecessarycomplexity(it’shardertoreadyourcodewithalltheinlinestyling)
- Largerdocumentsize(duetorepetitionofstylecontent),whichtranslatesinto slower-loadingpages
InteroperabilitySimplification
HTML5isallaboutsimplificationandavoidingneedlesscomplexity.TheHTML5mantra?“Simpleis better.Simplifywhereverpossible.”Herearesomeexamplesofthis:
- NativebrowserabilityinsteadofcomplexJavaScriptcode
- Anew,simplifiedDOCTYPE
- Anew,simplifiedcharactersetdeclaration
CHAPTER1 OVERVIEWOFHTML5
- PowerfulyetsimpleHTML5APIs We’llsaymoreaboutsomeoftheselater. Toachieveallthissimplicity,thespecificationhasbecomemuchbigger,becauseitneedstobe muchmoreprecise—farmoreprecise,infact,thananypreviousversionoftheHTMLspecification.It specifiesalegionofwell-definedbehaviorsinanefforttoachievetruebrowserinteroperabilityby2022. Vaguenesssimplywillnotmakethathappen.
TheHTML5specificationisalsomoredetailedthanpreviousonestopreventmisinterpretation.It aimstodefinethingsthoroughly,especiallywebapplications.Smallwonder,then,thatthespecification isover900pageslong!
HTML5isalsodesignedtohandleerrorswell,withavarietyofimprovedandambitiouserror- handlingplans.Quitepractically,itprefersgracefulerrorrecoverytohardfailure,againgivingA-1top prioritytotheinterestoftheenduser.Forexample,errorsindocumentswillnotresultincatastrophic failuresinwhichpagesdonotdisplay.Instead,errorrecoveryispreciselydefinedsobrowserscan display“broken”markupinastandardway.
UniversalAccess
Thisprincipleisdividedintothreeconcepts:
- Accessibility:Tosupportuserswithdisabilities,HTML5workscloselywitha relatedstandardcalledWebAccessibilityInitiative(WAI)AccessibleRichInternet Applications(ARIA).WAI-ARIAroles,whicharesupportedbyscreenreaders,can bealreadybeaddedtoyourHTMLelements.
- MediaIndependence:HTML5functionalityshouldworkacrossalldifferentdevices andplatformsifatallpossible.
- Supportforallworldlanguages:Forexample,thenew<ruby>elementsupports theRubyannotationsthatareusedinEastAsiantypography.
APlugin–FreeParadigm
HTML5providesnativesupportformanyfeaturesthatusedtobepossibleonlywithpluginsorcomplex hacks(anativedrawingAPI,nativevideo,nativesockets,andsoon). Plugins,ofcourse,presentmanyproblems:
- Pluginscannotalwaysbeinstalled.
- Pluginscanbedisabledorblocked(forexample,theAppleiPaddoesnotshipwith aFlashplugin).
- Pluginsareaseparateattackvector.
- PluginsaredifficulttointegratewiththerestofanHTMLdocument(becauseof pluginboundaries,clipping,andtransparencyissues).
Althoughsomepluginshavehighinstallrates(AdobeFlash,forexample),theyareoftenblockedin controlledcorporateenvironments.Inaddition,someuserschoosetodisablethesepluginsduetothe unwelcomeadvertisingdisplaysthattheyempower.However,ifusersdisableyourplugin,theyalso disabletheveryprogramyou’rerelyingontodisplayyourcontent.
Pluginsalsooftenhavedifficultyintegratingtheirdisplayswiththerestofthebrowsercontent, whichcausesclippingortransparencyissueswithcertainsitedesigns.Becausepluginsuseaself-
CHAPTER1 OVERVIEWOFHTML5
containedrenderingmodelthatisdifferentfromthatofthebasewebpage,developersfacedifficultiesif pop-upmenusorothervisualelementsneedtocrossthepluginboundariesonapage.Thisiswhere HTML5comesonthescene,smiles,andwavesitsmagicwandofnativefunctionality.Youcanstyle elementswithCSSandscriptwithJavaScript.Infact,thisiswhereHTML5flexesitsbiggestmuscle, showingusapowerthatjustdidn’texistinpreviousversionsofHTML.It’snotjustthatthenew elementsprovidenewfunctionality.It’salsotheaddednativeinteractionwithscriptingandstylingthat enablesustodomuchmorethanwecouldeverdobefore.
Takethenewcanvaselement,forexample.Itenablesustodosomeprettyfundamentalthingsthat werenotpossiblebefore(trydrawingadiagonallineinawebpageinHTML4).However,what’smost interestingisthepowerthatwecanunlockwiththeAPIsandthestylingwecanapplywithjustafew linesofCSScode.Likewell-behavedchildren,theHTML5elementsalsoplaynicelytogether.For example,youcangrabaframefromavideoelementanddisplayitonacanvas,andtheusercanjust clickthecanvastoplaybackthevideofromtheframeyoujustshowed.Thisisjustoneexampleofwhat anativecodehastoofferoveraplugin.Infact,virtuallyeverythingbecomeseasierwhenyou’renot workingwithablackbox.Whatthisalladdsuptoisatrulypowerfulnewmedium,whichiswhywe decidedtowriteabookaboutHTML5programming,andnotjustaboutthenewelements!
What’sInandWhat’sOut?
So,whatreallyispartofHTML5?Ifyoureadthespecificationcarefully,youmightnotfindallofthe featureswedescribeinthisbook.Forexample,youwillnotfindGeolocationandWebWorkersinthere. Soarewejustmakingthisstuffup?Isitallhype?No,notatall!
ManypiecesoftheHTML5effortwereoriginallypartoftheHTML5specificationandwerethen movedtoseparatestandardsdocumentstokeepthespecificationfocused.Itwasconsideredsmarterto discussandeditsomeofthesefeaturesonaseparatetrackbeforemakingthemintoofficial specifications.Thisway,onesmallcontentiousmarkupissuewouldn’tholduptheshowoftheentire specification.
Expertsinspecificareascancometogetheronmailingliststodiscussagivenfeaturewithoutthe crossfireoftoomuchchatter.Theindustrystillreferstotheoriginalsetoffeatures,including Geolocation,andsoonasHTML5.ThinkofHTML5,then,asanumbrellatermthatcoversthecore markup,aswellasmanycoolnewAPIs.Atthetimeofthiswriting,thesefeaturesarepartofHTML5:
- Canvas(2Dand3D)
- Cross-documentmessaging
- Geolocation
- AudioandVideo
- Forms
- MathML
- Microdata
- Server-Sentevents
- ScalableVectorGraphics(SVG)
- WebSocketAPIandprotocol
- Weboriginconcept
CHAPTER1 OVERVIEWOFHTML5
- Webstorage
- Indexeddatabase
- ApplicationCache(OfflineWebApps)
- WebWorkers
- DragandDrop
- XMLHttpRequestLevel2 Asyoucansee,alotoftheAPIswecoverinthisbookareonthislist.HowdidwechoosewhichAPIs tocover?Wechosetocoverfeaturesthatwereatleastsomewhatbaked.Translation?They’reavailablein someforminmorethanonebrowser.Other(less-baked)featuresmayonlyworkinonespecialbeta versionofabrowser,whileothersarestilljustideasatthispoint.
Asfarasbrowsersupportgoes,therearesomeexcellentonlineresourcesthatyoucanusetocheck current(andfuture)browsersupponexhaustivelistoffeatures andbrowsersupportbrokendownbybrowserversionandthesitehecksthe supportforHTML5featuresinthebrowseryouusetoaccessit.
Furthermore,thisbookdoesnotfocusonprovidingyouwiththeemulationworkaroundstomake yourHTML5applicationsrunseamlesslyonantiquebrowsers.Instead,wewillfocusprimarilyonthe specificationofHTML5andhowtouseit.Thatsaid,foreachoftheAPIswedoprovidesomeexample codethatyoucanusetodetectitsavailability.Ratherthanusinguseragentdetection,whichisoften unreliable,weusefeaturedetection.Forthat,youcanalsouseModernizr—aJavaScriptlibrarythat providesveryadvancedHTML5andCSS3featuredetection.WehighlyrecommendyouuseModernizr inyourapplications,becauseitishands-downthebesttoolforthis.
MORE MOMENTS IN HTML
Franksays:“Hi,I’mFrank,andIsometimespaint. OneofthefirstHTMLcanvasdemonstrationsIsawwasabasicpaintingapplicationthatmimickedthe userinterfaceofMicrosoftPaint.Althoughitwasdecadesbehindthestateoftheartindigitalpaintingand, atthetime,raninonlyafractionofexistingbrowsers,itgotmethinkingaboutthepossibilitiesit represented. WhenIpaintdigitally,Itypicallyuselocallyinstalleddesktopsoftware.Whilesomeoftheseprogramsare excellent,theylackthecharacteristicsthatmakewebapplicationssogreat.Inshort,theyare disconnected.Sharingdigitalpaintingshas,todate,involvedexportinganimagefromapainting applicationanduploadingittotheWeb.Collaborationorcritiquesonalivecanvasareoutofthequestion. HTML5applicationscanshort-circuittheexportcycleandmakethecreativeprocessfitintotheonline worldalongwithfinishedimages. ThenumberofapplicationsthatcannotbeimplementedwithHTML5isdwindling.Fortext,theWebis alreadytheultimatetwo-waycommunicationmedium.Text-basedapplicationsareavailableinentirely web-basedforms.Theirgraphicalcounterparts,likepainting,videoediting,and3Dmodelingsoftware,are justarrivingnow.
CHAPTER1 OVERVIEWOFHTML5
Wecannowbuildgreatsoftwaretocreateandenjoyimages,music,movies,andmore.Evenbetter,the
softwarewemakewillbeonandofftheWeb:aplatformthatisubiquitous,empowering,andonline.”
What’sNewinHTML5?
BeforewestartprogrammingHTML5,let’stakeaquicklookatwhat’snewinHTML5.
NewDOCTYPEandCharacterSet
Firstofall,theDOCTYPEforwebpageshasbeengreatlysimplified.Compare,forexample,thefollowing HTML4DOCTYPEs: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
Whocouldeverrememberanyofthese?Wecertainlycouldn’t.Wewouldalwaysjustcopyandpaste somelengthyDOCTYPEintothepage,alwayswithaworryinthebackofourminds,“Areyouabsolutely sureyoupastedtherightone?”HTML5neatlysolvesthisproblemasfollows: <!DOCTYPE html>
Nowthat’saDOCTYPEyoumightjustremember.LikethenewDOCTYPE,thecharactersetdeclaration hasalsobeenabbreviated.Itusedtobe <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
Now,itis: <meta charset="utf-8">
Youcanevenleaveoffthequotationmarksaround“utf-8”ifyouwantto.UsingthenewDOCTYPE triggersthebrowsertodisplaypagesinstandardsmode.Forexample,Figure1-1showstheinformation youwillseeifyouopenanHTML5pageinFirefox,andyouclickTools ➤ PageInfo.Inthisexample,the pageisrenderedinstandardsmode.
CHAPTER1 OVERVIEWOFHTML5
Figure1-1.Apagerenderedinstandards-compliantmode
WhenyouusethenewHTML5DOCTYPE,ittriggersbrowserstorenderthepageinstandards- compliantmode.Asyoumayknow,Webpagescanhavedifferentrenderingmodes,suchasQuirks, AlmostStandards,andStandards(orno-quirks)mode.TheDOCTYPEindicatestothebrowserwhich modetouseandwhatrulesareusedtovalidateyourpages.InQuirksmode,browserstrytoavoid breakingpagesandrenderthemeveniftheyarenotentirelyvalid.HTML5introducesnewelementsand hasmarkedothersasobsolete(moreonthisinthenextsection).Ifyouusetheseobsoleteelements, yourpagewillnotbevalid.However,browserswillcontinuetorenderthemastheyusedto.
NewandDeprecatedElements
HTML5introducesmanynewmarkupelements,whichitgroupsintosevendifferentcontenttypes. TheseareshownbelowinTable1-1.
Table1-1.HTML5ContentTypes
ContentType Description Embedded Contentthatimportsotherresourcesintothedocument,forexampleaudio,video, canvas,andiframe Flow Elementsusedinthebodyofdocumentsandapplications,forexampleform,h1,and small
CHAPTER1 OVERVIEWOFHTML5
Heading Sectionheaders,forexampleh1,h2,andhgroup Interactive Contentthatusersinteractwith,forexampleaudioorvideo controls,button,and textarea Metadata Elements—commonlyfoundintheheadsection—thatsetupthepresentationor behavioroftherestofthedocument,forexamplescript,style,andtitle Phrasing Textandtextmarkupelements,forexamplemark,kbd,sub,andsup Sectioning Elementsthatdefinesectionsinthedocument,forexamplearticle,aside,andtitle
MostoftheseelementscanbestyledwithCSS.Inaddition,someofthem,suchascanvas,audio, andvideo,canbeusedbythemselves,thoughtheyareaccompaniedbyAPIsthatallowforfine-grained nativeprogrammaticcontrol.TheseAPIswillbediscussedinmuchmoredetaillaterinthisbook.
Itisbeyondthescopeofthisbooktodiscussallthesenewelements,butmostofthesectioning elements(discussedinthenextsection)arenew.Thecanvas,audio,andvideoelementsarealsonewin HTML5.
Likewise,we’renotgoingtoprovideanexhaustivelistofallthedeprecatedtags(therearemany goodonlineresourcesonlineforthis),butmanyoftheelementsthatperformedinlinestylinghavebeen markedasobsoleteinfavorofusingCSS,suchasbig,center,font,andbasefont.
SemanticMarkup
OnecontenttypethatcontainsmanynewHTML5elementsisthesectioningcontenttype.HTML5 definesanewsemanticmarkuptodescribeanelement’scontent.Usingsemanticmarkupdoesn’t provideanyimmediatebenefitstotheenduser,butitdoessimplifythedesignofyourHTMLpages. What’smore,itwillmakeyourpagesmoremachine-readableandaccessible.Forexample,searchand syndicationengineswilldefinitelybetakingadvantageoftheseelementsastheycrawlandindexpages.
Aswesaidbefore,HTML5isallaboutpavingthecowpaths.GoogleandOperaanalyzedmillionsof pagestodiscoverthecommonIDnamesforDIVtagsandfoundahugeamountofrepetition.For example,sincemanypeopleusedDIV id="footer"tomarkupfootercontent,HTML5providesasetof newsectioningelementsthatyoucanuseinmodernbrowsersrightnow.Table1-2showsthedifferent semanticmarkupelements.
Table1-2.NewSectioningHTML5Elements
SectioningElement Description Headercontent(forapageorasectionofthepage) header footer Footercontent(forapageorasectionofthepage) section Asectioninawebpage article Independentarticlecontent
CHAPTER1 OVERVIEWOFHTML5
aside Relatedcontentorpullquotes nav Navigationalaids AlloftheseelementscanbestyledwithCSS.Infact,aswedescribedintheutilitydesignprinciple earlier,HTML5pushestheseparationofcontentandpresentation,soyouhavetostyleyourpageusing
CSSstylesinHTML5.Listing1-1showswhatanHTML5pagemightlooklike.ItusesthenewDOCTYPE, characterset,andsemanticmarkupelements—inshort,thenewsectioningcontent.Thecodefile (sample.html)isavailableinthecode/introfolder.
Listing1-1.AnExampleHTML5Page
<!DOCTYPE html> <html> <head> <meta charset="utf-8" > <title>HTML5</title> <link rel="stylesheet" href="html5.css"> </head> <body> <header> <h1>Header</h1> <h2>Subtitle</h2> <h4>HTML5 Rocks!</h4> </header> <div id="container"> <nav> <h3>Nav</h3> </nav> <section> <article> <header> <h1>Article Header</h1> </header> <p>Lorem ipsum dolor HTML5 nunc aut nunquam sit amet, consectetur adipiscing elit. Vivamus at est eros, vel fringilla urna.</p> <p>Per inceptos himenaeos. Quisque feugiat, justo at vehicula pellentesque, turpis lorem dictum nunc.</p> <footer> <h2>Article Footer</h2> </footer> </article>
CHAPTER1 OVERVIEWOFHTML5
<article> <header> <h1>Article Header</h1> </header> <p>HTML5: "Lorem ipsum dolor nunc aut nunquam sit amet, consectetur adipiscing elit. Vivamus at est eros, vel fringilla urna. Pellentesque odio</p> <h2>Article Footer</h2> </footer> </article> </section> <aside> <h3>Aside</h3> <p>HTML5: "Lorem ipsum dolor nunc aut nunquam sit amet, consectetur adipiscing elit. Vivamus at est eros, vel fringilla urna. Pellentesque odio rhoncus</p> </aside> <footer> <h2>Footer</h2> </footer> </div> </body> </html>
Withoutstyles,thepagewouldbeprettydulltolookat.Listing1-2showssomeoftheCSScodethat canbeusedtostylethecontent.Thecodefile(html5.css)isavailableinthecode/introfolder.Thisstyle sheetusessomeofthenewCSS3features,suchasroundedcorners(border-radius)androtate transformations(transform: rotate();).CSS3—justlikeHTML5itself—isstillunderdevelopment,and itismodularizedwithsubspecificationsforeasierbrowseruptake(forexample,transformation, animation,andtransitionareallareasthatareinseparatesubspecifications).
ExperimentalCSS3featuresareprefixedwithvendorstringstoavoidnamespaceconflictsshould thespecificationschange.Todisplayroundedcorners,gradients,shadows,andtransformations,itis currentlynecessarytouseprefixessuchas-moz-(forMozilla),o-(forOpera),-webkit-(forWebKit- basedbrowserssuchasSafariandChrome),and-ms-(forInternetExplorer)inyourdeclarations.
Listing1-2.CSSFilefortheHTML5Page
body { background-color:#CCCCCC; font-family:Geneva,Arial,Helvetica,sans-serif; margin: 0px auto; max-width:900px; border:solid; border-color:#FFFFFF; } header { background-color: #F47D31; display:block; color:#FFFFFF; text-align:center;
CHAPTER1 OVERVIEWOFHTML5
} header h2 { margin: 0px; } h1 { margin: 0px; } h2 { font-size: 24px; margin: 0px; text-align:center; color: #F47D31; } h3 { font-size: 18px; margin: 0px; text-align:center; color: #F47D31; } h4 { color: #F47D31; background-color: #fff;
- webkit-box-shadow: 2px 2px 20px #888;
- webkit-transform: rotate(-45deg);
- moz-box-shadow: 2px 2px 20px #888;
- moz-transform: rotate(-45deg); position: absolute; padding: 0px 150px; top: 50px; left: -120px; text-align:center; } nav { display:block; width:25%; float:left; } nav a:link, nav a:visited { display: block; border-bottom: 3px solid #fff; padding: 10px; text-decoration: none; font-weight: bold;
CHAPTER1 OVERVIEWOFHTML5
margin: 5px; } nav a:hover { color: white; background-color: #F47D31; } nav h3 { margin: 15px; color: white; } #container { background-color: #888; } section { display:block; width:50%; float:left; } article { background-color: #eee; display:block; margin: 10px; padding: 10px;
- webkit-border-radius: 10px;
- moz-border-radius: 10px; border-radius: 10px;
- webkit-box-shadow: 2px 2px 20px #888;
- webkit-transform: rotate(-10deg);
- moz-box-shadow: 2px 2px 20px #888;
- moz-transform: rotate(-10deg); } article header {
- webkit-border-radius: 10px;
- moz-border-radius: 10px; border-radius: 10px; padding: 5px; } article footer {
- webkit-border-radius: 10px;
- moz-border-radius: 10px; border-radius: 10px; padding: 5px; }
CHAPTER1 OVERVIEWOFHTML5
article h1 { font-size: 18px; } aside { display:block; float:left; } aside h3 { margin: 15px; color: white; } aside p { margin: 15px; color: white; font-weight: bold; font-style: italic; } footer { clear: both; display: block; background-color: #F47D31; color:#FFFFFF; text-align:center; padding: 15px; } footer h2 { font-size: 14px; color: white; } /* links */ a { color: #F47D31; } a:hover { text-decoration: underline; }
CHAPTER1 OVERVIEWOFHTML5
Figure1-2showsanexampleofthepageinListing1-1,styledwithCSS(andsomeCSS3)styles.Keep inmind,however,thatthereisnosuchthingasatypicalHTML5page.Anythinggoes,really,andthis exampleusesmanyofthenewtagsmainlyforpurposesofdemonstration.
Figure1-2.AnHTML5pagewithallthenewsemanticmarkupelements
Onelastthingtokeepinmindisthatbrowsersmayseemtorenderthingsasiftheyactually understandthesenewelements.Thetruthis,however,thattheseelementscouldhavebeenrenamed fooandbarandthenstyled,andtheywouldhavebeenrenderedthesameway(butofcourse,they wouldnothaveanybenefitsinsearchengineoptimization).TheoneexceptiontothisisInternet Explorer,whichrequiresthatelementsbepartoftheDOM.So,ifyouwanttoseetheseelementsinIE, youmustprogrammaticallyinsertthemintotheDOManddisplaythemasblockelements.Ahandy scriptthatdoesthatforyouishtml5shiv(
CHAPTER1 OVERVIEWOFHTML5
SimplifyingSelectionUsingtheSelectorsAPI
Alongwiththenewsemanticelements,HTML5alsointroducesnewsimplewaystofindelementsin yourpageDOM.Table1-3showsthepreviousversionsofthedocumentobjectalloweddevelopersto makeafewcallstofindspecificelementsinthepage.
Table1-3.PreviousJavaScriptMethodstoFindElements
FunctionDescription Example getElementById() Returnstheelementwiththe <div id="foo"> specifiedidattributevalue getElementById("foo"); getElementsByName() Returnsallelementswhosename <input type="text" name="foo"> attributehasthespecifiedvalue getElementsByName("foo"); getElementsByTagName() Returnallelementswhosetagname <input type="text"> matchesthespecifiedvalue getElementsByTagName("input");
WiththenewSelectorsAPI,therearenowmoreprecisewaystospecifywhichelementsyouwould liketoretrievewithoutresortingtoloopinganditeratingthroughadocumentusingstandardDOM.The
SelectorsAPIexposesthesameselectorrulespresentinCSSasameanstofindoneormoreelementsin thepage.Forexample,CSSalreadyhashandyrulesforselectingelementsbasedontheirnesting, sibling,andchildpatterns.ThemostrecentversionsofCSSaddsupportformorepseudo-classes—for example,whetheranobjectisenabled,disabled,orchecked—andjustaboutanycombinationof propertiesandhierarchyyoucouldimagine.ToselectelementsinyourDOMusingCSSrules,simply utilizeoneofthefunctionsshowninTable1-4.
Table1-4.NewQuerySelectorMethods
FunctionDescription Example Result querySelector() Returnthefirst document.querySelector("input.error"); Returnthe elementinthepage firstinput whichmatchesthe fieldwitha specifiedselector styleclassof rules(s) “error” querySelectorAll() Returnsall document.querySelectorAll("#results Returnany elementswhich td"); tablecells matchthespecified insidethe ruleorrules elementwith idresults
ItisalsopossibletosendmorethanoneselectorruletotheSelectorAPIfunctions,forexample:
// select the first element in the document with the // style class highClass or the style class lowClass var x = document.querySelector(“.highClass”, “.lowClass”);