Upload
others
View
7
Download
0
Embed Size (px)
Citation preview
CodingForDummies®
Publishedby:JohnWiley&Sons,Inc.,111RiverStreet,Hoboken,NJ07030-5774,www.wiley.com
Copyright©2015byJohnWiley&Sons,Inc.,Hoboken,NewJersey
Mediaandsoftwarecompilationcopyright©2015byJohnWiley&Sons,Inc.Allrightsreserved.
PublishedsimultaneouslyinCanada
Nopartofthispublicationmaybereproduced,storedinaretrievalsystemortransmittedinanyformorbyanymeans,electronic,mechanical,photocopying,recording,scanningorotherwise,exceptaspermittedunderSections107or108ofthe1976UnitedStatesCopyrightAct,withoutthepriorwrittenpermissionofthePublisher.RequeststothePublisherforpermissionshouldbeaddressedtothePermissionsDepartment,JohnWiley&Sons,Inc.,111RiverStreet,Hoboken,NJ07030,(201)748-6011,fax(201)748-6008,oronlineatwww.wiley.com/go/permissions.
Trademarks:Wiley,ForDummies,theDummiesManlogo,Dummies.com,MakingEverythingEasier,andrelatedtradedressaretrademarksorregisteredtrademarksofJohnWiley&Sons,Inc.andmaynotbeusedwithoutwrittenpermission.Allothertrademarksarethepropertyoftheirrespectiveowners.JohnWiley&Sons,Inc.isnotassociatedwithanyproductorvendormentionedinthisbook.
LIMITOFLIABILITY/DISCLAIMEROFWARRANTY:THEPUBLISHERANDTHEAUTHORMAKENOREPRESENTATIONSORWARRANTIESWITHRESPECTTOTHEACCURACYORCOMPLETENESSOFTHECONTENTSOFTHISWORKANDSPECIFICALLYDISCLAIMALLWARRANTIES,INCLUDINGWITHOUTLIMITATIONWARRANTIESOFFITNESSFORAPARTICULARPURPOSE.NOWARRANTYMAYBECREATEDOREXTENDEDBYSALESORPROMOTIONALMATERIALS.THEADVICEANDSTRATEGIESCONTAINEDHEREINMAYNOTBESUITABLEFOREVERYSITUATION.THISWORKISSOLDWITHTHEUNDERSTANDINGTHATTHEPUBLISHERISNOTENGAGEDINRENDERINGLEGAL,ACCOUNTING,OROTHERPROFESSIONALSERVICES.IFPROFESSIONAL
ASSISTANCEISREQUIRED,THESERVICESOFACOMPETENTPROFESSIONALPERSONSHOULDBESOUGHT.NEITHERTHEPUBLISHERNORTHEAUTHORSHALLBELIABLEFORDAMAGESARISINGHEREFROM.THEFACTTHATANORGANIZATIONORWEBSITEISREFERREDTOINTHISWORKASACITATIONAND/ORAPOTENTIALSOURCEOFFURTHERINFORMATIONDOESNOTMEANTHATTHEAUTHORORTHEPUBLISHERENDORSESTHEINFORMATIONTHEORGANIZATIONORWEBSITEMAYPROVIDEORRECOMMENDATIONSITMAYMAKE.FURTHER,READERSSHOULDBEAWARETHATINTERNETWEBSITESLISTEDINTHISWORKMAYHAVECHANGEDORDISAPPEAREDBETWEENWHENTHISWORKWASWRITTENANDWHENITISREAD.
Forgeneralinformationonourotherproductsandservices,pleasecontactourCustomerCareDepartmentwithintheU.S.at877-762-2974,outsidetheU.S.at317-572-3993,orfax317-572-4002.Fortechnicalsupport,pleasevisitwww.wiley.com/techsupport.
Wileypublishesinavarietyofprintandelectronicformatsandbyprint-on-demand.Somematerialincludedwithstandardprintversionsofthisbookmaynotbeincludedine-booksorinprint-on-demand.IfthisbookreferstomediasuchasaCDorDVDthatisnotincludedintheversionyoupurchased,youmaydownloadthismaterialathttp://booksupport.wiley.com.FormoreinformationaboutWileyproducts,visitwww.wiley.com.
LibraryofCongressControlNumber:2014954659
ISBN978-1-118-95130-9(pbk);ISBN978-1-118-95130-9(ebk);ISBN978-1-118-97091-1(ebk)
ManufacturedintheUnitedStatesofAmerica
10987654321
CodingForDummies®Visitwww.dummies.com/cheatsheet/codingtoviewthisbook'scheatsheet.
TableofContentsIntroduction
AboutThisBook
FoolishAssumptions
IconsUsedinThisBook
BeyondtheBook
WheretoGofromHere
PartI:GettingStartedwithCodingChapter1:WhatIsCoding?
DefiningWhatCodeIs
Followinginstructions
WritingcodewithsomeAngryBirds
UnderstandingWhatCodingCanDoforYou
Eatingtheworldwithsoftware
Codingonthejob
Scratchingyourownitch(andbecomingrichandfamous)
SurveyingtheTypesofProgrammingLanguages
Comparinglow-levelandhigh-levelprogramminglanguages
Contrastingcompiledcodeandinterpretedcode
Programmingfortheweb
TakingaTourofaWebAppBuiltwithCode
Definingtheapp’spurposeandscope
Standingontheshouldersofgiants
Chapter2:ProgrammingfortheWebDisplayingWebPagesonYourDesktopandMobileDevice
Hackingyourfavoritenewswebsite
UnderstandinghowtheWorldWideWebworks
Watchingoutforyourfrontendandbackend
Definingwebandmobileapplications
CodingWebApplications
StartingwithHTML,CSS,andJavaScript
AddinglogicwithPython,Ruby,orPHP
CodingMobileApplications
Buildingmobilewebapps
Buildingnativemobileapps
Chapter3:BecomingaProgrammerWritingCodeUsingaProcess
Researchingwhatyouwanttobuild
Designingyourapp
Codingyourapp
Debuggingyourcode
PickingToolsfortheJob
Workingoffline
WorkingonlinewithCodecademy.com
PartII:BuildingtheSilentandInteractiveWebPageChapter4:ExploringBasicHTML
WhatDoesHTMLDo?
UnderstandingHTMLStructure
Identifyingelements
Featuringyourbestattribute
Standinghead,title,andbodyabovetherest
GettingFamiliarwithCommonHTMLTasksandTags
Writingheadlines
Organizingtextinparagraphs
Linkingtoyour(heart’s)content
Addingimages
StylingMePretty
Highlightingwithbold,italics,underline,andstrikethrough
Raisingandloweringtextwithsuperscriptandsubscript
BuildingYourFirstWebsiteUsingHTML
Chapter5:GettingMoreOutofHTMLOrganizingContentonthePage
ListingData
Creatingorderedandunorderedlists
Nestinglists
PuttingDatainTables
Basictablestructuring
Stretchingtablecolumnsandrows
Aligningtablesandcells
FillingOutForms
Understandinghowformswork
Creatingbasicforms
PracticingMorewithHTML
Chapter6:GettingStylishwithCSSWhatDoesCSSDo?
CSSStructure
Choosingtheelementtostyle
Mypropertyhasvalue
HackingtheCSSonyourfavoritewebsite
CommonCSSTasksandSelectors
Fontgymnastics:size,color,style,family,anddecoration
Customizinglinks
Addingbackgroundimagesandstylingforegroundimages
StylingMePretty
AddingCSStoyourHTML
Buildingyourfirstwebpage
Chapter7:NextStepswithCSSStyling(More)ElementsonYourPage
Stylinglists
Designingtables
SelectingElementstoStyle
Stylingspecificelements
NamingHTMLelements
AligningandLayingOutYourElements
Organizingdataonthepage
Shapingthediv
Understandingtheboxmodel
Positioningtheboxes
WritingMoreAdvancedCSS
Chapter8:WorkingFasterwithTwitterBootstrapFiguringOutWhatBootstrapDoes
InstallingBootstrap
UnderstandingtheLayoutOptions
Lininguponthegridsystem
Dragginganddroppingtoawebsite
Usingpredefinedtemplates
Adaptinglayoutformobile,tablet,anddesktop
CodingBasicWebPageElements
Designingbuttons
Navigatingwithtoolbars
Addingicons
BuildtheAirbnbHomePage
Chapter9:AddinginJavaScriptWhatDoesJavaScriptDo?
UnderstandingJavaScriptStructure
UsingSemicolons,Quotes,Parentheses,andBraces
CodingCommonJavaScriptTasks
Storingdatawithvariables
Makingdecisionswithif-elsestatements
Workingwithstringandnumbermethods
Alertingusersandpromptingthemforinput
Namingcodewithfunctions
AddingJavaScripttothewebpage
WritingYourFirstJavaScriptProgram
WorkingwithAPIs
WhatdoAPIsdo?
ScrapingdatawithoutanAPI
ResearchingandchoosinganAPI
UsingJavaScriptLibraries
jQuery
D3.js
SearchingforVideoswithYouTube’sAPI
PartIII:PuttingTogetheraWebApplicationChapter10:BuildingYourOwnApp
BuildingaLocation-BasedOfferApp
Understandingthesituation
Plottingyournextsteps
FollowinganAppDevelopmentProcess
PlanningYourFirstWebApplication
ExploringtheOverallProcess
MeetingthePeopleWhoBringaWebApptoLife
Creatingwithdesigners
Codingwithfront-andback-enddevelopers
Managingwithproductmanagers
Testingwithqualityassurance
Chapter11:ResearchingYourFirstWebApplicationDividingtheAppintoSteps
Findingyourapp’sfunctionality
Findingyourapp’sfunctionality:Myversion
Findingyourapp’sform
Findingyourapp’sform:TheMcDuck’sOfferAppdesign
IdentifyingResearchSources
ResearchingtheStepsintheMcDuck’sOfferApp
ChoosingaSolutionforEachStep
Chapter12:CodingandDebuggingYourFirstWebApplicationGettingReadytoCode
CodingYourFirstWebApplication
Developmentenvironment
Pre-writtencode
Codingstepsforyoutofollow
DebuggingYourApp
PartIV:DevelopingYourCodingSkillsFurtherChapter13:GettingFamiliarwithRuby
WhatDoesRubyDo?
DefiningRubyStructure
UnderstandingtheprinciplesofRuby
Stylingandspacing
CodingCommonRubyTasksandCommands
Definingdatatypesandvariables
Computingsimpleandadvancedmath
Usingstringsandspecialcharacters
Decidingwithconditionals:If,elsif,else
Inputandoutput
ShapingYourStrings
Stringmethods:upcase,downcase,strip
Insertingvariablesinstringswith#
BuildingaSimpleForm-TextFormatterUsingRuby
Chapter14:WrappingYourHeadaroundPythonWhatDoesPythonDo?
DefiningPythonStructure
UnderstandingtheZenofPython
Stylingandspacing
CodingCommonPythonTasksandCommands
Definingdatatypesandvariables
Computingsimpleandadvancedmath
Usingstringsandspecialcharacters
Decidingwithconditionals:If,elif,else
Inputandoutput
ShapingYourStrings
Dotnotationwithupper(),lower(),capitalize(),andstrip()
Stringformattingwith%
BuildingaSimpleTipCalculatorUsingPython
PartV:ThePartofTensChapter15:TenFreeResourcesforCodingandCoders
Learning-to-CodeWebsites
Codecademy
CourseraandUdacity
Hackdesign.org
Code.org
Coding-ReferenceWebsites
W3Schools
MozillaDeveloperNetwork
StackOverflow
TechNewsandCommunityWebsites
TechCrunch
HackerNews
Meetup
Chapter16:TenTipsforNoviceCodersPickaLanguage,AnyLanguage
DefineaGoal
BreakDownYourGoalintoBite-SizedSteps
DistinguishCupcakefromFrosting
GoogleIsaDeveloper’sBestFriend
ZapThoseBugs
JustShipIt
CollectFeedback
IterateonYourCode
ShareYourSuccessandFailure
AbouttheAuthorCheatSheetMoreDummiesProducts
IntroductionTheabilitytoread,write,andunderstandcodehasneverbeenmoreimportant,useful,orlucrativeasitistoday.Computercodehasforeverchangedourlives.Somepeoplecan’tevenmakeitthroughthedaywithoutinteractingwithsomethingbuiltwithcode.Evenso,formanypeople,theworldofcodingseemscomplexandinaccessible.Maybeyouparticipatedinatech-relatedbusinessmeetinganddidnotfullyunderstandtheconversation.Perhapsyoutriedtobuildawebpageforyourfamilyandfriends,butranintoproblemsdisplayingpicturesoraligningtext.Maybeyou’reevenintimidatedbytheunrecognizablewordsonthecoversofbooksaboutcoding:wordssuchasHTML,CSS,JavaScript,Python,orRuby.
Ifyou’vepreviouslybeeninthesesituations,thenCodingForDummiesisforyou.Thisbookexplainsbasicconceptssoyoucanparticipateintechnicalconversations,andasktherightquestions.Don’tworry—inthisbookI’veassumedyouarestartingwithlittletonopreviouscodingknowledge,andIhaven’ttriedtocrameverypossiblecodingconceptintothesepages.Additionally,Iencourageyouheretolearnbydoing,andbyactuallycreatingyourownprograms.Insteadofawebsite,imaginethatyouwantedtobuildahouse.Youcouldspendeightyearsstudyingtobeanarchitect,oryoucouldstarttodaybylearningalittlebitaboutfoundationsandframing.Thisbookkickstartsyourcodingjourneytoday.
Theimportanceofcodingiseverincreasing.AsauthorandtechnologistDouglasRushkofffamouslysaid,“programorbeprogrammed.”Whenhumansinventedlanguagesandthenthealphabet,peoplelearnedtolistenandspeak,andthenreadandwrite.Inourincreasinglydigitalworld,itisimportanttolearnnotjusthowtouseprograms,buthowtomakethemaswell.Forexample,observethistransitioninmusic.Foroveracentury,musiclabelsdecidedwhatsongsthepubliccouldlistentoandpurchase.In2005,threecoderscreatedYouTube,whichallowedanyonetoreleasesongs.TodaymoresongshavebeenuploadedtoYouTubethanhavebeenreleasedbyalltherecordlabelsinthelastcenturycombined.
Accompanyingthisbookareexamplesatwww.codecademy.com,whoseexercisesareoneoftheeasiestwaystolearnhowtocodewithoutinstallingordownloadinganything.TheCodecademycompanionsiteincludes
examplesandexercisesfromthisbook,alongwithprojectsandexamplesforadditionalpractice.
AboutThisBookThisbookisdesignedforreaderswithlittletonocodingexperience,andgivesanoverviewofprogrammingtonon-programmers.InplainEnglish,youlearnhowcodeisusedtocreatewebprograms,whomakesthoseprograms,andtheprocessestheyuse.Thetopicscoveredinclude:
Explainingwhatcodingisandansweringthecommonquestionsrelatedtocode.Buildingbasicwebsitesusingthethreemostcommonlanguages:HTML,CSS,andJavaScript.SurveyingotherprogramminglanguagessuchasRubyandPython.Buildinganapplicationusingeverythingyoulearninthebook.
Asyoureadthisbook,keepthefollowinginmind:
Thebookcanbereadfrombeginningtoend,butfeelfreetoskiparoundifyoulike.Ifanytopicinterestsyou,startthere.Youcanalwaysreturntothepreviouschapter,ifnecessary.Atsomepointyouwillgetstuck,andcodeyouwritewillnotworkasintended.Donotfear!Therearemanyresourcestohelpyouincludingsupportforums,othersontheInternet,andme!UsingTwitter,youcansendmeapublicmessageat@nikhilgabrahamwiththehashtag#codingFD.
Codeinthebookwillappearinamonospacedfontlikethis:<h1>Hithere!</h1>.
FoolishAssumptionsIdonotmakemanyassumptionsaboutyou,thereader,butIdomakeafew:
Iassumeyoudon’thavepreviousprogrammingexperience.Tofollowalong,then,youonlyneedtobeabletoread,type,andfollowdirections.Itryto
explainasmanyconceptsaspossibleusingexamplesandanalogiesyoualreadyknow.
IassumeyouhaveacomputerrunningthelatestversionofGoogleChrome.TheexamplesinthebookhavebeentestedandoptimizedfortheChromebrowser,whichisavailableforfreefromGoogle.Evenso,theexamplesmayalsoworkinthelatestversionofFirefox.UsingInternetExplorerfortheexamplesinthisbook,however,isdiscouraged.
IassumeyouhaveaccesstoanInternetconnection.SomeoftheexamplesinthebookcanbedonewithoutanInternetconnection,butmostrequireonesoyoucanaccessandcompletetheexercisesonwww.codecademy.com.
IconsUsedinThisBookHerearetheiconsusedinthebooktoflagtextthatshouldbegivenextraattentionorcanbeskipped.
Thisiconflagsusefulinformationorexplainsashortcuttohelpyouunderstandaconcept.
Thisiconexplainstechnicaldetailsabouttheconceptbeingexplained.Thedetailsmightbeinformativeorinteresting,butarenotessentialtoyourunderstandingoftheconceptatthisstage.
Trynottoforgetthematerialmarkedwiththisicon.Itsignalsanimportantconceptorprocessthatyoushouldkeepinmind.
Watchout!Thisiconflagscommonmistakesandproblemsthatcanbeavoidedifyouheedthewarning.
BeyondtheBook
Alotofextracontentthatyouwon’tfindinthisbookisavailableatwww.dummies.com.Goonlinetofindthefollowing:
ThesourcecodefortheexamplesinthisbookandalinktotheCodecademyexercises:Youcanfindtheseat
www.dummies.com/go/codingfd
Thesourcecodeisorganizedbychapter.Thebestwaytoworkwithachapteristodownloadallthesourcecodeforitatonetime.
CheatSheet:YoucanfindalistofcommonHTML,CSS,andJavaScriptcommands,amongotherusefulinformation,at
www.dummies.com/cheatsheet/coding
Extras:Additionalarticleswithextracontentarepostedforroughlyeachsectionofthebook.Youcanaccesstheseadditionalmaterialsat
www.dummies.com/extras/coding
Updates:Codeandspecificationsareconstantlychanging,sothecommandsandsyntaxthatworktodaymaynotworktomorrow.Youcanfindanyupdatesorcorrectionsbyvisiting
www.dummies.com/extras/coding
WheretoGofromHereAllright,nowthatalloftheadministrativestuffisoutoftheway,it’stimetogetstarted.Youcantotallydothis.Congratulationsontakingyourfirststepintotheworldofcoding!
PartIGettingStartedwithCoding
Visitwww.dummies.comforgreatForDummiescontentonline.
Inthispart…Understandwhatcodeisandwhatyoucanbuildwithit.Reviewprogramminglanguagesusedtowritecode.Codeforthewebusingfront-endandback-endprogramminglanguages.Followtheprocessprogrammersusetocreatecode.Writeyourfirstprogramusingcode.
Chapter1WhatIsCoding?
InThisChapterSeeingwhatcodeisandwhatitcandoTouringyourfirstprogramusingcodeUnderstandingprogramminglanguagesusedtowritecode
“Amilliondollarsisn’tcool,youknowwhat’scool?Abilliondollars.”—SeanParker,TheSocialNetwork
Everyweekthenewspapersreportonanothertechnologycompanythathasraisedcapitalorsoldformillionsofdollars.Sometimes,inthecaseofcompanieslikeInstagram,WhatsApp,andUber,theamountintheheadlineisforbillionsofdollars.Thesearticlesmaypiqueyourcuriosity,andyoumaywanttoseehowcodeisusedtobuildtheapplicationsthatexperiencethesefinancialoutcomes.Alternatively,yourinterestsmaylieclosertowork.Perhapsyouworkinanindustryindecline,likeprintmedia,orinafunctionthattechnologyisrapidlychanging,likemarketing.Whetheryouarethinkingaboutswitchingtoanewcareerorimprovingyourcurrentcareer,understandingcomputerprogrammingor“coding”canhelpwithyourprofessionaldevelopment.Finally,yourinterestmaybemorepersonal—perhapsyouhaveanidea,aburningdesiretocreatesomething,awebsiteoranapp,tosolveaproblemyouhaveexperienced,andyouknowreadingandwritingcodeisthefirststeptobuildingyoursolution.Whateveryourmotivation,thisbookwillshedlightoncodingandprogrammers,andhelpyouthinkofbothnotasmysteriousandcomplexbutapproachableandsomethingyoucandoyourself.
Inthischapter,youwillunderstandwhatcodeis,whatindustriesareaffectedbycomputersoftware,thedifferenttypesofprogramminglanguagesusedtowritecode,andtakeatourofawebappbuiltwithcode.
DefiningWhatCodeIsComputercodeisnotacrypticactivityreservedforgeniusesandoracles.Infact,inafewminutesyouwillbewritingsomecomputercodeyourself!Mostcomputercodeperformsarangeoftasksinourlivesfromthemundanetotheextraordinary.Coderunsourtrafficlightsandpedestriansignals,theelevatorsinourbuildings,thecellphonetowersthattransmitourphonesignals,andthespaceshipsheadedforouterspace.Wealsointeractwithcodeonamorepersonallevel,onourphonesandcomputers,andusuallytocheckemailortheweather.
FollowinginstructionsComputercodeisasetofstatements,likesentencesinEnglish,andeachstatementdirectsthecomputertoperformasinglesteporinstruction.Eachofthesestepsisveryprecise,andfollowedtotheletter.Forexample,ifyouareinarestaurantandaskawaitertodirectyoutotherestroom,hemightsay,“headtotheback,andtrythemiddledoor.”Toacomputer,thesedirectionsaresovagueastobeunusable.Instead,ifthewaitergaveinstructionstoyouasifyouwereacomputerprogramhemightsay,“Fromthistable,walknortheastfor40paces.Thenturnright90degrees,walk5paces,turnleft90degrees,andwalk5paces.Openthedoordirectlyinfrontofyou,andentertherestroom.”Figure1-1showslinesofcodefromthepopulargame,Pong.Donotworryabouttryingtounderstandwhateverysinglelinedoes,orfeelintimated.Youwillsoonbereadingandwritingyourowncode.
Figure1-1:ComputercodefromthegamePong.
Oneroughwaytomeasureaprogram’scomplexityistocountitsstatementsorlinesofcode.BasicapplicationslikethePonggamehave5,000linesofcode,whilemorecomplexapplicationslikeFacebookcurrentlyhaveover10
millionlinesofcode.Whetherfewormanylinesofcode,thecomputerfollowseachinstructionexactlyandeffortlessly,nevertiringlikethewaitermightwhenaskedforthe100thtimeforthelocationoftherestroom.
Becarefulofonlyusinglinesofcodeasameasureforaprogram’scomplexity.JustlikewhenwritinginEnglish,100wellwrittenlinesofcodecanperformthesamefunctionalityas1,000poorlywrittenlinesofcode.
WritingcodewithsomeAngryBirdsIfyouhaveneverwrittencodebefore,nowisyourchancetotry!Gotohttp://csedweek.org/learnandundertheheading“TutorialsforBeginners”clickthe“WriteYourFirstComputerProgram”linkwiththeAngryBirdsicon,asshowninFigure1-2.Thistutorialismeantforthosewithnopreviouscomputerprogrammingexperience,andintroducesthebasicbuildingblocksusedbyallcomputerprograms.Themostimportanttake-awayfromthetutorialistounderstandthatcomputerprogramsusecodetoliterallyandexactlytellthecomputertoexecuteasetofinstructions.
Figure1-2:Writeyourfirstcomputerprogramwithagame-liketutorialusingAngryBirds.
ComputerScienceEducationWeekisanannualprogramdedicatedtoelevatingtheprofileofcomputerscienceduringoneweekinDecember.Inthepast,PresidentObama,BillGates,basketballplayerChrisBosh,andsingerShakira,amongothers,havesupportedandencouraged
peoplefromtheUSandaroundtheworldtoparticipate.
UnderstandingWhatCodingCanDoforYou
Codingcanbeusedtoperformtasksandsolveproblemsthatyouexperienceeveryday.The“everyday”situationsinwhichprogramsorappscanprovideassistancecontinuestogrowatanexponentialpace,butthiswasnotalwaysthecase.Theriseofwebapplications,internetconnectivity,andmobilephoneshaveinsertedsoftwareprogramsintodailylife,andloweredthebarrierforyoutobecomeacreator,solvingpersonalandprofessionalproblemswithcode.
EatingtheworldwithsoftwareIn2011,MarcAndreessen,creatorofNetscapeNavigatorandnowventurecapitalist,notedthat“softwareiseatingtheworld.”Hepredictedthatsoftwarecompanieswoulddisruptexistingcompaniesatarapidpace.Traditionally,codepoweredsoftwareusedondesktopsandlaptops.Thesoftwarehadtofirstbeinstalled,andthenyouhadtosupplydatatotheprogram.Threetrendshavedramaticallyincreasedtheuseofcodeineverydaylife:
Web-basedsoftware:Thissoftwareoperatesinthebrowserwithoutrequiringinstallation.Forexample,ifyouwantedtocheckyouremail,youpreviouslyhadtoinstallanemailclienteitherbydownloadingthesoftwareorfromaCD-ROM.Sometimes,issuesarosewhenthesoftwarewasnotavailableforyouroperatingsystem,orconflictedwithyouroperatingsystemversion.Hotmail,aweb-basedemailclient,rosetopopularity,inpart,becauseitallowedusersvisitingwww.hotmail.comtoinstantlychecktheiremailwithoutworryingaboutinstallationorsoftwarecompatibility.Webapplicationsincreasedconsumerappetitetotrymoreapplications,anddevelopersinturnwereincentivizedtowritemoreapplications.Internetbroadbandconnectivity:Broadbandconnectivityhasincreased,providingafastInternetconnectiontomorepeopleinthelast
fewyearsthaninthepreviousdecade.Today,morethantwobillionpeoplecanaccessweb-basedsoftware,upfromapproximately50milliononlyadecadeago.Mobilephones:Today’ssmartphonesbringprogramswithyouwhereveryougo,andhelpsupplydatatoprograms.Manysoftwareprogramsbecamemoreusefulwhenaccessedon-the-gothanwhenlimitedtoadesktopcomputer.Forinstance,useofmapsapplicationsgreatlyincreasedthankstomobilephonesbecauseusersneeddirectionsthemostwhenlost,notjustwhenplanningatripathomeonthecomputer.Inaddition,mobilephonesareequippedwithsensorsthatmeasureandsupplydatatoprogramslikeorientation,acceleration,andcurrentlocationthroughGPS.Nowinsteadofhavingtoinputallthedatatoprogramsyourself,mobiledevicescanhelp.Forinstance,afitnessapplicationlikeRunKeeperdoesnotrequireyoutoinputstartandendtimestokeeptrackofyourruns.Youcanpressstartatthebeginningofyourrun,andthephonewillautomaticallytrackyourdistance,speed,andtime.
Thecombinationofthesetrendshavecreatedsoftwarecompaniesthathaveupendedincumbentsinalmosteveryindustry,especiallyonestypicallyimmunetotechnology.Somenotableexamplesinclude:
Airbnb:Airbnbisapeer-to-peerlodgingcompanythatownsnorooms,yetbooksmorenightsthantheHiltonandIntercontinental,thelargesthotelchainsintheworld.(SeeFigure1-3.)
Figure1-3:Airbnbbooked5millionnightsafter3.5years,anditsnext5millionnights6
monthslater.
Uber:Uberisacartransportationcompanythatownsnovehicles,booksmoretrips,andhasmoredriversinthelargest200citiesthananyothercarortaxiservice.Groupon:Groupon,thedailydealscompany,generatedalmost$1billionafterjusttwoyearsinbusiness,growingfasterthananyothercompanyinhistory,letaloneanyothertraditionaldirectmarketingcompany.
CodingonthejobCodingcanbeusefulintheworkplaceaswell.Outsidethetechnologysector,codingintheworkplaceiscommonforsomeprofessionslikefinancialtraders,economists,andscientists.However,formostprofessionalsoutsidethetechnologysector,codingisjustbeginningtopenetratetheworkplace,andgraduallystartingtoincreaseinrelevance.Hereareareaswherecodingisplayingalargerroleonthejob:
Advertising:SpendisshiftingfromprintandTVtodigitalcampaigns,andsearchengineadvertisingandoptimizationreliesonkeywordstobringvisitorstowebsites.Advertiserswhounderstandcodeseesuccessfulkeywordsusedbycompetitors,andusethatdatatocreatemoreeffectivecampaigns.Marketing:Whenpromotingproducts,personalizingcommunicationisonestrategythatoftenincreasesresults.Marketerswhocodecanquerycustomerdatabasesandcreatepersonalizedcommunicationsthatincludecustomernamesandproductstailoredtospecificinterests.Sales:Thesalesprocessalwaysstartswithleads.Salespeoplewhocoderetrievetheirownleadsfromwebpagesanddirectories,andthensortandqualitythoseleads.
Retrievinginformationbycopyingtextonwebpagesandindirectoriesisreferredtoasscraping.
Design:Aftercreatingawebpageoradigitaldesign,designersmustpersuadeotherdesignersandeventuallydeveloperstoactuallyprogram
theirdrawingsintotheproduct.Designerswhocodecanmoreeasilybringtheirdesignstolife,andcanmoreeffectivelyadvocateforspecificdesignsbycreatingworkingprototypesthatotherscaninteractwith.Publicrelations:Companiesconstantlymeasurehowcustomersandthepublicreacttoannouncementsandnews.Forinstance,ifacelebrityspokespersonforacompanydoesorsayssomethingoffensive,shouldthecompanydumpthecelebrity?PublicrelationspeoplewhocodequerysocialmedianetworkslikeTwitterorFacebook,andanalyzehundredsofthousandsofindividualmessagestounderstandmarketsentiment.Operations:Additionalprofitcanbegenerated,inpart,byanalyzingacompany’scosts.Operationspeoplewhocodewriteprogramstotrymillionsofcombinationstooptimizepackagingmethods,loadingroutines,anddeliveryroutes.
Scratchingyourownitch(andbecomingrichandfamous)Usingcodebuiltbyothersandcodingintheworkplacemaycauseyoutothinkofproblemsyoupersonallyfacethatyoucouldsolvewithcodeofyourown.Youmayhaveanideaforasocialnetworkwebsite,abetterfitnessapp,orsomethingnewaltogether.Thepathfromideatofunctioningprototypeusedbyothersinvolvesagoodamountoftimeandwork,butmightbemoreachievablethanyouthink.Forexample,takeCoffitivity,aproductivitywebsitethatstreamsambientcoffeeshopsoundstocreatewhitenoise.Thewebsitewascreatedbytwopeoplewhohadjustlearnedhowtoprogramafewmonthsprior.ShortlyafterCoffitivitylaunched,TimeMagazinenamedthewebsiteoneof50BestWebsitesof2013,andtheWallStreetJournalalsoreviewedthewebsite.Whilenoteverystartuporappwillinitiallyreceivethismuchmediacoverage,itcanbehelpfultoknowwhatispossiblewhenasolutionreallysolvesaproblem.
Havingagoal,likeawebsiteorappyouwanttobuild,isoneofthebestwaystolearnhowtocode.Whenfacingadifficultbugorahardconcept,theideaofbringingyourwebsitetolifewillprovidethemotivationyouneedtokeepgoing.Justasimportant,donotlearnhowtocodetobecomerichandfamous,astheprobabilityofyourwebsiteorappbecomingsuccessfulislargelyduetofactorsoutofyourcontrol.
ThecharacteristicsthatmakeawebsiteorappaddictivearedescribedusingtheHookModelherehttp://techcrunch.com/2012/03/04/how-to-manufacture-desire.Productsareusuallymadebycompanies,andthecharacteristicsofanenduringcompanyaredescribedherehttp://www.sequoiacap.com/grove/posts/yal6/elements-of-enduring-companies,basedonareviewofcompaniesfundedbySequoia,oneofthemostsuccessfulventurecapitalfirmsintheworldandearlyinvestorsinApple,Google,andPayPal.
SurveyingtheTypesofProgrammingLanguages
Codecomesindifferentflavorscalledprogramminglanguages.SomepopularprograminglanguagesareshowninFigure1-4.
Figure1-4:Somepopularprogramminglanguages.
Youcanthinkofprogramminglanguagesjustlikespokenlanguages,astheybothsharemanyofthesamecharacteristics,suchas:
Functionalityacrosslanguages:Programminglanguagescanallcreatethesamefunctionalitysimilartohowspokenlanguagescanallexpress
thesameobjects,phrases,andemotions.Syntaxandstructure:Commandsinprogramminglanguagescanoverlapjustlikewordsinspokenlanguagesoverlap.TooutputtexttoscreeninPythonorRubyyouusetheprintcommand,justlikeimprimerandimprimiraretheverbsfor“print”inFrenchandSpanish.Naturallifespan:Programminglanguagesarebornwhenaprogrammerthinksofaneworeasierwaytoexpressacomputationalconcept.Ifotherprogrammersagree,theyadoptthelanguagefortheirownprogramsandtheprogramminglanguagespreads.However,justlikeLatinorAramaic,iftheprogramminglanguageisnotadoptedbyotherprogrammersorabetterlanguagecomesalong,thentheprogramminglanguageslowlydiesfromlackofuse.
Despitethesesimilarities,programminglanguagesalsodifferfromspokenlanguagesinafewkeyways:
Onecreator:Unlikespokenlanguages,programminglanguagescanbecreatedbyonepersoninashortperiodoftime,sometimesinjustafewdays.PopularlanguageswithasinglecreatorincludeJavaScript(BrendanEich),Python(GuidovanRossum),andRuby(YukihiroMatsumoto).WritteninEnglish:Unlikespokenlanguages(except,ofcourse,English),almostallprogramminglanguagesarewritteninEnglish.Whetherthey’reprogramminginHTML,JavaScript,Python,orRuby,Brazilian,French,orChineseprogrammersallusethesameEnglishkeywordsandsyntaxintheircode.Somenon-Englishprogramminglanguagesexist,suchaslanguagesinHindiorArabic,butnoneoftheselanguagesarewidespreadormainstream.
Comparinglow-levelandhigh-levelprogramminglanguagesOnewaytoclassifyprogramminglanguagesiseitheraslow-levellanguagesorhigh-levellanguages.Low-levellanguagesinteractdirectlywiththecomputerprocessororCPU,arecapableofperformingverybasiccommands,andaregenerallyhardtoread.Machinecode,oneexampleofalow-levellanguage,usescodethatconsistsofjusttwonumbers—0and1.Figure1-5
showsanexampleofmachinecode.Assemblylanguage,anotherlow-levellanguage,useskeywordstoperformbasiccommandslikereaddata,movedata,andstoredata.
Figure1-5:Machinecodeconsistsof0sand1s.
Bycontrast,high-levellanguagesusenaturallanguagesoitiseasierforpeopletoreadandwrite.Oncecodeiswritteninahigh-levellanguage,likeC++,Python,orRuby,aninterpreterorcompilertranslatesthishigh-levellanguageintolow-levelcodeacomputercanunderstand.
ContrastingcompiledcodeandinterpretedcodeHigh-levelprogramminglanguagesmustbeconvertedtolow-levelprogramminglanguagesusinganinterpreterorcompiler,dependingonthelanguage.Interpretedlanguagesareconsideredmoreportablethancompiledlanguages,whilecompiledlanguagesexecutefasterthaninterpretedlanguages.However,thespeedadvantagecompiledlanguageshaveisstartingtofadeinimportanceasimprovingprocessorspeedsmakeperformancedifferencesbetweeninterpretedandcompiledlanguagesnegligible.
High-levelprogramminglanguageslikeJavaScript,Python,andRubyareinterpreted.Fortheselanguagestheinterpreterexecutestheprogramdirectly,translatingeachstatementonelineatatimeintomachinecode.High-levelprogramminglanguageslikeC++,COBOL,andVisualBasicarecompiled.Fortheselanguages,afterthecodeiswrittenacompilertranslatesallthecodeintomachinecode,andanexecutablefileiscreated.Thisexecutablefile
isthendistributedviatheinternet,CD-ROMs,orothermediaandrun.Softwareyouinstallonyourcomputer,likeMicrosoftWindowsorMacOSX,arecodedusingcompiledlanguages,usuallyCorC++.
ProgrammingforthewebSoftwareaccessibleonwebsitesisgraduallystartingtotakeoverinstalledsoftware.Thinkofthelasttimeyoudownloadedandinstalledsoftwareforyourcomputer—youmaynotevenremember!InstalledsoftwarelikeWindowsMediaPlayerandWinampthatplaymusicandmovieshavebeenreplacedwithwebsiteslikeYouTubeandNetflix.TraditionalinstalledwordprocessorandspreadsheetsoftwarelikeMicrosoftWordandExcelarestartingtoseecompetitionfromwebsoftwarelikeGoogleDocsandSheets.GoogleisevensellinglaptopscalledChromebooksthatcontainnoinstalledsoftware,andinsteadrelyexclusivelyonwebsoftwaretoprovidefunctionality.
Theremainderofthisbookwillfocusondevelopingandcreatingwebsoftware,notjustbecausewebsoftwareisgrowingrapidly,butalsobecauseprogramsforthewebareeasiertolearnandlaunchthantraditionalinstalledsoftware.
TakingaTourofaWebAppBuiltwithCode
Withallthistalkofprogramming,letusactuallytakealookatawebapplicationbuiltwithcode.Yelp.comisawebsitethatallowsyoutosearchandfindcrowd-sourcedreviewsforlocalbusinesseslikerestaurants,nightlife,andshopping.AsshowninFigure1-6,Yelpdidnotalwayslookaspolishedasitdoestoday,butitspurposehasstayedrelativelyconstantovertheyears.
Figure1-6:Yelp’swebsitein2004andin2014.
Definingtheapp’spurposeandscopeOnceyouunderstandanapp’spurpose,youcanidentifyafewactionabletasksausershouldbeabletoperformtoachievethatpurpose.Regardlessofdesign,theYelp’swebsitehasalwaysallowedusersto
Searchlocallistingsbasedonvenuetypeandlocation.Browselistingresultsforaddress,hours,reviews,photos,andlocationonamap.
Successfulwebapplicationsgenerallyallowforcompletingonlyafewkeytaskswhenusingtheapp.Addingtoomanyfeaturestoanappiscalledscopecreep,dilutesthestrengthoftheexistingfeatures,andsoisavoidedbymostdevelopers.Forexample,ittookYelp,whichhas30,000restaurantreviews,exactlyonedecadeafteritsfoundingtoallowuserstomakereservationsatthoserestaurantsdirectlyonitswebsite.Whetheryouareusingorbuildinganapp,haveaclearsenseoftheapp’spurpose.
StandingontheshouldersofgiantsDevelopersmakestrategicchoicesanddecidewhichpartsoftheapptocodethemselves,andwhichpartsoftheapptousecodebuiltbyothers.Developersoftenturnto3rdpartyprovidersforfunctionalitythatiseithernotcoretothebusinessornotanareaofstrength.Inthisway,appsstandontheshouldersofothers,andbenefitfromotherswhohavecomebeforeandsolvedchallengingproblems.
Yelp,forinstance,displayslocallistingreviewsandplaceseverylistingonamap.WhileYelpsolicitsthereviews,andwritesthecodetodisplaybasiclistingdata,itisGoogle,asshowninFigure1-7,whichdevelopsthemapsusedonYelp’swebsite.ByusingGoogle’smapapplicationinsteadofbuildingitsown,Yelpcreatedthefirstversionoftheappwithfewerengineersthanotherwisewouldhavebeenrequired.
Figure1-7:GooglemapsusedfortheYelpwebapplication.
Chapter2ProgrammingfortheWeb
InThisChapterSeeingthecodepoweringwebsitesyouuseeverydayUnderstandingthelanguagesusedtomakewebsitesLearninghowapplicationsarecreatedformobiledevices
Tothinkyoucanstartsomethinginyourcollegedormroom…andbuildsomethingabillionpeopleuseiscrazytothinkabout.It’samazing.
—MarkZuckerbergProgrammingfortheweballowsyoutoreachmassiveaudiencesaroundtheworldfasterthaneverbefore.Fouryearsafterits2004launch,Facebookhad100millionusers,andby2012ithadoverabillion.Bycontrast,ittookdesktopsoftwareyearstoreacheven1millionpeople.Thesedays,mobilephonesareincreasingthereachofwebapplications.Althoughroughly300milliondesktopcomputersaresoldeveryyear,almost2billionmobilephonesaresoldinthattime—andthenumberissteadilyincreasing.
Inthischapteryoulearnhowwebsitesaredisplayedonyourcomputerormobiledevice.Iintroducethelanguagesusedtoprogramwebsites,andshowyouhowmobile-deviceapplicationsaremade.
DisplayingWebPagesonYourDesktopandMobileDevice
Ondesktopcomputersandmobiledevices,webpagesaredisplayedbyapplicationscalledbrowsers.ThemostpopularwebbrowsersincludeGoogleChrome,MozillaFirefox(formerlyNetscapeNavigator),MicrosoftInternetExplorer,andAppleSafari.Untilnow,youhavelikelyinteractedwithwebsitesyouvisitasanobedientuser,andfollowedtherulesthewebsitehas
createdbypointingandclickingwhenallowed.Thefirststeptobecomingaproducerandprogrammerofwebsitesistopeelbackthewebpage,andseeandplaywiththecodeunderneathitall.
HackingyourfavoritenewswebsiteWhat’syourfavoritenewswebsite?Byfollowingafewsteps,youcanseeandevenmodifythecodeusedtocreatethatwebsite.(Noneedtoworry,youwon’tbebreakinganyrulesbyfollowingtheseinstructions.)
Althoughyoucanusealmostanymodernbrowsertoinspectawebsite’scode,theseinstructionsassumeyou’reusingtheGoogleChromebrowser.Installthelatestversionbygoingtowww.google.com/chrome/browser.
To“hack”yourfavoritenewswebsite,followthesesteps:
1. OpenyourfavoritenewswebsiteusingtheChromebrowser.(Inthisexample,Iusewww.huffingtonpost.com.)
2. Placeyourmousecursoroveranystaticfixedheadlineandright-clickonce,whichopensacontextualmenu.Then,left-clickonceontheInspectElementmenuchoice.(SeeFigure2-1.)
Figure2-1:Right-clickonaheadlineandselectInspectElementfromthemenu.
IfusingaMacintoshcomputer,youcanright-clickbyholdingdowntheControlkeyandclickingonce.
TheDeveloperToolspanelopensatthebottomofyourbrowser.Thispanelshowsyouthecodeusedtocreatethiswebpage!Highlightedinblueisthespecificcodeusedtocreatetheheadlinewhereyouoriginallyputyourmousecursor.(SeeFigure2-2.)
Figure2-2:Thebluehighlightedcodeisusedtocreatethewebpageheadline.
Lookattheleftedgeofthehighlightedcode.Ifyouseearightarrow,left-clickonceonthearrowtoexpandthecode.
3. Scanthehighlightedcodecarefullyforthetextofyourheadline.Whenyoufindit,double-clickontheheadlinetext.Thisallowsyoutoedittheheadline.(SeeFigure2-3.)
Becarefulnottoclickonanythingthatbeginswithhttp,whichistheheadlinelink.Clickingonaheadlinelinkwillopenanewwindowortabandloadthelink.
Figure2-3:Double-clicktheheadlinetexttoedititwithyourownheadline.
4. InsertyournameintheheadlineandpressEnter.
Yournamenowappearsontheactualwebpage.(SeeFigure2-4.)Enjoyyournewfoundfame!
Figure2-4:Yousuccessfullychangedtheheadlineofamajornewswebsite.
Ifyouwereunabletoedittheheadlineafterfollowingthesesteps,visithttp://goggles.webmaker.orgforaneasier,moreguidedtutorial.It’safoolproofguidedversiontoeditcodeonapage.It’sateachingaidthatshowsthatanycodeontheInternetcanbemodified.Onthatpage,clicktheyellowActivateX-RayGogglestoseeandeditthecodeonthewebmaker.orgwebpage.Tryagaintohackyourfavorite
newswebsitebyfollowingthe“RemixAnyWebpage”instructions.
Ifyousuccessfullycompletedthestepsaboveandchangedtheoriginalheadline,it’stimeforyour15minutesoffametocometoanend.Reloadthewebpageandtheoriginalheadlinereappears.Whatjusthappened?Didyourchangesappeartoeveryonevisitingthewebpage?Andwhydidyoureditedheadlinedisappear?
Toanswerthesequestions,youfirstneedtounderstandhowtheInternetdeliverswebpagestoyourcomputer.
UnderstandinghowtheWorldWideWebworksAfteryoutypeaURL,suchashuffingtonpost.com,intoyourbrowser,thefollowingstepshappenbehindthescenesinthesecondsbeforeyourpageloads(seeFigure2-5):
1. Yourcomputersendsyourrequestforthewebpagetoarouter.TherouterdistributesInternetaccessthroughoutyourhomeorworkplace.
2. TherouterpassesyourrequestontoyourInternetserviceprovider(ISP).IntheUnitedStates,yourISPisacompanylikeComcast,TimeWarner,AT&T,orVerizon.
3. YourISPthenconvertsthewordsandcharactersinyourURL—“huffingtonpost.com,”inmyexample—intoanumericaladdresscalledtheInternetprotocoladdress(or,morecommonly,IPaddress).AnIPaddressisasetoffournumbersseparatedbyperiods(suchas,forexample,192.168.1.1).Justlikeyourphysicaladdress,thisnumberisunique,andeverycomputerhasone.YourISPhasadigitalphonebook,similartoaphysicalphonebook,calledadomainnameserverthat’susedtoconverttextURLsintoIPaddresses.
4. WiththeIPaddresslocated,yourISPknowswhichserverontheInternettoforwardyourrequestto,andyourpersonalIPaddressisincludedinthisrequest.
5. Thewebsiteserverreceivesyourrequest,andsendsacopyofthewebpagecodetoyourcomputerforyourbrowsertodisplay.
6. Yourwebbrowserrendersthecodeontothescreen.
Figure2-5:Stepsfollowedtodeliverawebsitetoyourbrowser.
WhenyoueditedthewebsitecodeusingtheDeveloperTools,youmodifiedonlythecopyofthewebsitecodethatexistsonyourcomputer,soonlyyoucouldseethechange.Whenyoureloadedthepage,youstartedsteps1through6again,andretrievedafreshcopyofthecodefromtheserver,overwritinganychangesyoumadeonyourcomputer.
Youmayhaveheardofasoftwaretoolcalledanadblocker.Adblockersworkbyeditingthelocalcopyofwebsitecode,justasyoudidabove,toremovewebsiteadvertisements.Adblockersarecontroversialbecausewebsitesuseadvertisingrevenuetopayforoperatingcosts.Ifadblockerscontinuerisinginpopularity,adrevenuecoulddryup,andwebsiteswouldhavetodemandthatreaderspaytoseetheircontent.
WatchingoutforyourfrontendandbackendNowthatyouknowhowyourbrowseraccesseswebsites,letusdivedeeperintothewaytheactualwebsiteisconstructed.AsshowninFigure2-6,thecodeforwebsites,andforprogramsingeneral,canbedividedintofourcategories,accordingtothecode’sfunction:
Appearance:Appearanceisthevisiblepartofthewebsite,includingcontentlayoutandanyappliedstyling,suchfontsize,fonttypeface,andimagesize.ThiscategoryiscalledthefrontendandiscreatedusinglanguageslikeHTML,CSS,andJavaScript.Logic:Logicdetermineswhatcontenttoshowandwhen.Forexample,a
NewYorkeraccessinganewswebsiteshouldseeNewYorkweather,whereasChicagoansaccessingthesamesiteshouldseeChicagoweather.ThiscategoryispartofthegroupcalledthebackendandiscreatedusinglanguageslikeRuby,Python,andPHP.ThesebackendlanguagescanmodifytheHTML,CSS,andJavaScriptthatisdisplayedtotheuser.Storage:Storagesavesanydatageneratedbythesiteanditsusers.User-generatedcontent,preferences,andprofiledatamustbestoredforretrievallater.ThiscategoryispartofthebackendandisstoredindatabaseslikeMongoDBandMySQL.Infrastructure:Infrastructuredeliversthewebsitefromtheservertoyou,theclientmachine.Whentheinfrastructureisproperlyconfigured,noonenoticesit,butitcanbecomenoticeablewhenawebsitebecomesunavailableduetohightrafficfromeventslikepresidentialelections,theSuperBowl,andnaturaldisasters.
Usually,websitedevelopersspecializeinoneoratmosttwoofthesecategories.Forexample,anengineermightreallyunderstandthefrontendandlogiclanguages,orspecializeinonlydatabases.Websitedevelopershavestrengthsandspecializations,andoutsideoftheseareastheirexpertiseislimited,muchinthesamewaythatJerrySeinfeld,aterrificcomedywriter,wouldlikelymakeaterribleromancenovelist.
Therarewebsitedeveloperproficientinallfourofthesecategoriesisreferredtoasafullstackdeveloper.Usually,smallercompanieshirefullstackdevelopers,whereaslargercompaniesrequiretheexpertisethatcomeswithspecialization.
Figure2-6:Everywebsiteismadeupoffourdifferentparts.
DefiningwebandmobileapplicationsWebapplicationsarewebsitesyouvisitusingawebbrowseronanydevice.Websitesoptimizedforuseonamobiledevice,likeaphoneortablet,arecalledmobilewebapplications.Bycontrast,nativemobileapplicationscannotbeviewedusingawebbrowser.Instead,nativemobileapplicationsaredownloadedfromanappstoreliketheAppleAppStoreorGooglePlay,anddesignedtorunonaspecificdevicesuchasaniPhoneoranAndroidtablet.Historically,desktopcomputersoutnumberedandoutsoldmobiledevices,butrecentlytwomajortrendsinmobileusagehaveoccurred:
In2014,peoplewithmobiledevicesoutnumberedpeoplewithdesktopcomputers.Thisgapisprojectedtocontinueincreasing,asshowninFigure2-7.Mobile-deviceusersspend80percentoftheirtimeusingnativemobileapplications,and20percentoftheirtimebrowsingmobilewebsites.
Figure2-7:Mobiledeviceshaveincreasedatafasterpacethandesktops.
Theincreaseinmobiledeviceshashappenedsoquicklyoverthelast10yearsthatmanycompaniesarebecoming“mobilefirst,”designinganddevelopingthemobileversionoftheirapplicationsbeforethedesktopversion.WhatsAppandInstagram,twopopularmobileapplications,firstbuiltmobileapplications,whichcontinuetohavemorefunctionalitythentheirregularwebsites.
CodingWebApplicationsWebapplicationsareeasiertobuildthanmobileapplications,requirelittleto
noadditionalsoftwaretodevelopandtest,andrunonalldevices,includingdesktop,laptops,andmobile.Althoughmobileapplicationscanperformmanycommonweb-applicationtasks,suchasemail,sometasksarestilleasiertoperformusingwebapplications.Forexample,bookingtraveliseasierusingwebapplications,especiallysincethestepsnecessary—reviewingflights,hotels,andrentalcars,andthenpurchasingallthree—arebestachievedwithmultiplewindows,accesstoacalendar,andtheentryofsubstantialpersonalandpaymentinformation.
Theprogramminglanguagesusedtocodebasicwebapplications,furtherdefinedinthefollowingsections,includeHTML(HypertextMarkupLanguage),CSS(CascadingStyleSheets),andJavaScript.AdditionalfeaturescanbeaddedtothesewebsitesusinglanguageslikePython,Ruby,orPHP.
StartingwithHTML,CSS,andJavaScriptSimplewebsites,suchastheoneshowninFigure2-8,arecodedusingHTML,CSS,andJavaScript.HTMLisusedtoplacetextonthepage,CSSisusedtostylethattext,andJavaScriptisusedtoaddinteractiveeffectsliketheTwitterorFacebookSharebuttonthatallowsyoutosharecontentonsocialnetworksandupdatesthenumberofotherpeoplewhohavealsosharedthesamecontent.Websitesconveyingmainlystatic,unchanginginformationareoftencodedonlyinthesethreelanguages.Youwilllearnabouteachoftheselanguagesinlaterchapters.
AddinglogicwithPython,Ruby,orPHPWebsiteswithmoreadvancedfunctionality,suchasuseraccounts,fileuploads,ande-commerce,typicallyrequireaprogramminglanguagetoimplementthesefeatures.AlthoughPython,Ruby,andPHParenottheonlyprogramminglanguagesthesesitescanuse,theyareamongthemostpopular.Thispopularitymeanstherearelargeonlinecommunitiesofdeveloperswhoprogramintheselanguages,freelypostcodethatyoucancopytobuildcommonfeatures,andhostpubliconlinediscussionsthatyoucanreadforsolutionstocommonissues.
Figure2-8:Thelindaliukas.fiwebsite,builtusingHTML,CSS,andJavaScript.
Eachoftheselanguagesalsohaspopularandwelldocumentedframeworks.Aframeworkisacollectionofgenericcomponents,suchasuseraccountsandauthenticationschemesthatarereusedfrequently,allowingdeveloperstobuild,test,andlaunchwebsitesmorequickly.Youcanthinkofaframeworkassimilartothecollectionoftemplatesthatcomeswithawordprocessor.Youcandesignyourresume,greetingcard,orcalendarfromscratch,butusingthebuilt-intemplateforeachofthesedocumenttypeshelpsyoucreateyourdocumentfasterandwithgreaterconsistency.Popularframeworksfortheselanguagesinclude
DjangoandFlaskforPythonRailsandSinatraforRubyZendandLaravelforPHP
CodingMobileApplicationsMobileapplicationsarehottopicstoday,inpartbecausemobileappssuchasWhatsAppandInstagramwereacquiredforbillionsofdollars,andmobileappcompanieslikeRovio,makersofAngryBirds,andKingDigital,makersofCandyCrush,generateannualrevenuesofhundredsofmillionstobillionsofdollars.
Whencodingmobileapplications,developerscaneitherbuild
Mobilewebapplications,usingHTML,CSS,andJavaScript.
Nativemobileapplicationsusingaspecificlanguage.Forexample,AppledevicesareprogrammedusingObjective-CorSwift,andAndroiddevicesareprogrammedusingJava.
Thechoicebetweenthesetwooptionsmayseemsimple,butthereareafewfactorsatplay.Considerthefollowing:
Companiesdevelopingmobilewebapplicationsmustmakesurethemobileversionworksacrossdifferentbrowsers,differentscreensizes,andevendifferentmanufacturers,suchasApple,Samsung,RIM,andMicrosoft.Thisresultsinthousandsofpossiblephonecombinations,whichcangreatlyincreasethecomplexityoftestingneededbeforelaunch.Nativemobileappsrunonlyononephoneplatform,sothereislessvariationtoaccountfor.Despiterunningononlyoneplatform,nativemobileappsaremoreexpensiveandtakelongertobuildthanmobilewebapps.Somedevelopershavereportedthatmobilewebapplicationshavemoreperformanceissuesandloadmoreslowlythannativemobileapplications.Asmentionedbefore,usersarespendingmoretimeusingnativemobileapplicationsandlesstimeusingbrowser-basedmobilewebapps.Nativemobileappsaredistributedthroughanappstore,whichmayrequireapprovalfromtheappstoreowner,whereasmobilewebappsareaccessiblefromanywebbrowser.Forexample,ApplehasastrictapprovalpolicyandtakesuptosixdaystoapproveanappforinclusionintheAppleAppStore,whileGooglehasamorerelaxedapprovalpolicyandtakestwohourstoapproveanapp.
Inonefamousexampleofanapprejectedfromanappstore,AppleblockedGooglefromlaunchingtheGoogleVoiceappintheAppleAppStorebecauseitoverlappedwithApple’sownphonefunctionality.Googlerespondedbycreatingamobilewebappaccessiblefromanybrowser,andApplecoulddonothingtoblockit.
Ifyou’remakingthischoice,considerthecomplexityofyourapplication.Simpleapplications,likeschedulesormenus,canlikelybecheaply
developedwithamobilewebapp,whereasmorecomplexapplications,likemessagingandsocialnetworking,maybenefitfromhavinganativemobileapp.Evenwell-establishedtechnologycompaniesstrugglewiththischoice.Initially,FacebookandLinkedIncreatedmobilewebapplications,butbothhavesinceshiftedtoprimarilypromotingandsupportingnativemobileapps.Thecompaniescitedbetterspeed,memorymanagement,anddevelopertoolsassomeofthereasonsformakingtheswitch.
BuildingmobilewebappsAlthoughanywebsitecanbeviewedwithamobilebrowser,thosewebsitesnotoptimizedformobiledeviceslookalittleweird,asiftheregularwebsitefontsizeandimagedimensionsweredecreasedtofitonamobilescreen.(SeeFigure2-9.)Bycontrast,websitesoptimizedformobiledeviceshavefontsthatarereadable,imagesthatscaletothemobiledevicescreen,andaverticallayoutsuitableforamobilephone.
BuildingmobilewebappsisdoneusingHTML,CSS,andJavaScript.CSScontrolsthewebsiteappearanceacrossdevicesbasedonthescreenwidth.Screenswithasmallwidth,suchasthoseonphones,areassignedonevertically-basedlayout,whereasscreenswithalargerwidth,likethoseontablets,areassignedanother,horizontally-basedlayout.Becausemobilewebappsareaccessedfromthebrowser,andarenotinstalledontheuser’sdevice,thesewebappscan’tsendpushnotifications(alerts)toyourphone,runinthebackgroundwhilethebrowserisminimized,orcommunicatewithotherapps.
AlthoughyoucanwritetheHTML,CSS,andJavaScriptforyourmobilewebappfromscratch,mobilewebframeworksallowyoutodevelopfromabaseofpre-writtencode,muchliketheframeworksforprogramminglanguagesImentionedearlier.Thesemobilewebframeworksincludeacollectionofgenericcomponentsthatarereusedfrequently,andallowdeveloperstobuild,test,andlaunchwebsitesmorequickly.TwitterBootstrapisonesuchmobilewebframework,whichIintroduceinChapter8.
Figure2-9:Left:starbucks.comnotoptimizedformobile.Right:starbucks.comoptimizedformobile.
BuildingnativemobileappsNativemobileappscanbefaster,morereliable,andlookmorepolishedthanmobilewebapps,asshowninFigure2-10.BuiltusingJavaforuseonAndroiddevices,andObjective-CorSwiftforuseonAppledevices(iOS),nativemobileappsmustbeuploadedtoanappstore,whichmayrequireapprovals.Themainbenefitofanappstoreisitscentralizeddistribution,andtheappmaybefeaturedinpartsoftheappstorethatcandrivedownloads.Also,sincenativemobileapplicationsareprogramsthatareinstalledonthemobiledevice,theycanbeusedinmoresituationswithoutanInternetconnection.Finally,andmostimportantly,usersappeartoprefernativemobileappstomobilewebappsbyawidemargin,onethatcontinuestoincrease.
Nativemobileappscantakeadvantageoffeaturesthatruninthebackgroundwhiletheappisminimized,suchaspushnotifications,andcommunicatewithotherapps,andthesefeaturesarenotavailablewhencreatingamobilewebapp.Additionally,nativemobileappsperformbetterwhenhandlinggraphics-intensiveapplications,suchasgames.Tobeclear,nativemobileappsofferbetterperformanceandagreaternumberoffeatures,buttheyrequirelongerdevelopmenttimesandaremoreexpensivetobuildthanmobilewebapps.
Figure2-10:Left:facebook.comnativemobileapp.Right:facebook.commobilewebapp.
Thereisanalternativewaytobuildanativemobileapp—ahybridapproachthatinvolvesbuildinganappusingHTML,CSS,andJavaScript,packagingthatcodeusinga“wrapper,”andthenrunningthecodeinsideanativemobileappcontainer.Themostpopular“wrapper”isaproductcalledPhoneGap,anditrecognizesspecificJavaScriptcommandsthatallowaccesstodevice-levelfunctionalitythat’snormallyinaccessibletomobilewebapplications.Afteroneversionoftheappisbuilt,nativemobileappcontainerscanbelaunchedforuptonineplatformsincludingApple,Android,Blackberry,andWindowsPhone.Themajoradvantagetousingthishybridapproachisbuildingyourapponce,andthenreleasingittosomanyplatformssimultaneously.
Imagineyouknewhowtoplaythepiano,butyouwantedtoalsolearnhowtoplaytheviolin.Onewayyoucoulddothisistobuyaviolinandstartlearninghowtoplay.Anotheroptionistobuyasynthesizerkeyboard,setthetonetoviolin,andplaythekeyboardtosoundlikeaviolin.Thisissimilartothehybridapproach,except,inthisexample,thepianoisHTML,CSS,andJavaScript,theviolinisanativeiOSapp,andthesynthesizerkeyboardisawrapperlikePhoneGap.Justlikethesynthesizerkeyboardcanbesettoviolin,cello,orguitar,sotoocan
PhoneGapcreatenativeappsforApple,Android,andotherplatforms.
Whataboutallthoseotherprogramminglanguages?(C,Java,andsoon)
Youmaywonderwhysomanylanguagesexist,andwhattheyalldo.Programminglanguagesarecreatedwhenadeveloperseesaneednotaddressedbythecurrentlanguages.Forexample,ApplerecentlycreatedtheSwiftprogramminglanguagetomakedevelopingiPhoneandiPadappseasierthanObjective-C,thecurrentprogramminglanguageused.Afterthey’recreated,programminglanguagesareverysimilartospokenlanguages,likeEnglishorLatin.Ifdeveloperscodeusingthenewlanguage,thenitthrivesandgrowsinpopularity,likeEnglishhasoverthelastsixcenturies;otherwise,theprogramminglanguagesuffersthesamefateasLatin,andbecomesadeadlanguage.
YoumayrememberlanguageslikeC++,Java,andFORTRAN.Theselanguagesstillexisttoday,andthey’reusedinmoreplacesthanyoumightthink.C++ispreferredwhenspeedandperformanceisextremelyimportant,andisusedtoprogramwebbrowsers,suchasChrome,Firefox,andSafari,alongwithgameslikeCallofDuty,andCounterStrike.Javaispreferredbymanylarge-scalebusiness,andisalsothelanguageusedtoprogramappsfortheAndroidphone.Finally,FORTRANisnotaswidespreadorpopularasitoncewas,butitispopularwithinthescientificcommunity,anditpowerssomefunctionalityinthefinancialsector,especiallyatsomeofthelargestbanksintheworld,manyofwhichcontinuetohaveoldcode.
Aslongasprogrammersthinkoffasterandbetterwaystoprogram,newprogramminglanguageswillcontinuetobecreated,whileolderlanguagesfalloutoffavor.
Chapter3BecomingaProgrammer
InThisChapterLearningtheprocessprogrammersfollowwhencodingSeeingthedifferentrolespeopleplaytocreateaprogramPickingtoolstostartingcodingofflineoronline
Thewaytogetstartedistoquittalkingandbegindoing.—WaltDisney
Programmingisaskillthatcanbelearnedbyanyone.Youmightbeastudentincollegewonderinghowtostartlearning,oraprofessionalhopingtofindanewjoborimproveyourperformanceatyourcurrentjob.Injustabouteverycase,thebestwaytolearnhowtocodeisto
Haveagoalofwhatyouwouldliketobuild.Actuallystartcoding.
Inthischapter,youdiscovertheprocesseveryprogrammerfollowswhenprogramming,andthedifferentrolesprogrammersplaytocreateaprogram(or,morecommonlythesedays,an“app”).Youalsolearnthetoolstousewhencodingeitherofflineoronline.
WritingCodeUsingaProcessWritingcodeismuchlikepainting,furnituremaking,orcooking—itisn’talwaysobvioushowtheendproductwascreated.However,allprograms,evenmysteriousones,arecreatedusingaprocess.Twoofthemostpopularprocessesusedtodayare
Waterfall:Asetofsequentialstepsfollowedtocreateaprogram.Agile:Asetofiterativestepsfollowedtocreateaprogram.(SeeFigure
3-1.)
Letmedescribeaspecificscenariotoexplainhowthesetwoprocesswork.Imagineyouwanttobuildarestaurantappthatdoesthefollowingtwothings:
Itdisplaysrestaurantinformation,suchasthehoursofoperationandthemenu.Itallowsuserstomakeorcancelreservations.
Usingthewaterfallmethod,you’ddefineeverythingtheappneedstodo:You’ddesignboththeinformation-displayandthereservationpartsoftheapp,codetheentireapp,andthenreleasetheapptousers.Bycontrast,usingtheagilemethod,youwoulddefine,design,andcodeonlytheinformation-displayportionoftheapp,releaseittousers,andcollectfeedback.Basedonthefeedbackcollected,youwouldthenredesignandmakechangestotheinformation-displaytoaddressmajorconcerns.Whenyouweresatisfiedwiththeinformation-displaypiece,you’dthendefine,design,andbuildthereservationpartoftheapp.Again,youwouldcollectfeedbackandrefinethereservationfeaturetoaddressmajorconcerns.
Figure3-1:Thewaterfallandagileprocessesaretwodifferentwaysofcreatingsoftware.
Theagilemethodologystressesshorterdevelopmenttimes,andhasincreasedinpopularityasthepaceoftechnologicalchangehasincreased.Thewaterfallapproach,ontheotherhand,demandsthatthedevelopercodeandreleasetheentireappatonce,butsincecompletingalargeprojecttakesanenormousamountoftime,changesintechnologymayhaveoccurredbeforethefinishedproductarrives.Ifyouusedthewaterfallmethodtocreateourrestaurant-appexample,thetechnologytotakeuserreservationsmayhavechangedbythetimeyougetaroundtocodingthatportionoftheapp.Still,thewaterfall
approachremainspopularincertaincontexts,suchaswithfinancialandgovernmentsoftware,whererequirementsandapprovalareobtainedatthebeginningofaproject,andwhosedocumentationofaprojectmustbecomplete.
Thehealthcare.govwebsite,releasedinOctober2013,wasdevelopedusingawaterfallstyleprocess.TestingofallthecodeoccurredinSeptember2013,whentheentiresystemwasassembled.Unfortunately,thetestsoccurredtoolateandwerenotcomprehensive,resultinginnotenoughtimetofixerrorsbeforelaunchingthesitepublicly.
Regardlessofwhetheryoupicktheagileorwaterfallmethodology,codinganappinvolvesfoursteps:
1. Researchingwhatyouwanttobuild2. Designingyourapp3. Codingyourapp4. Debuggingyourcode
Onaverage,youwillspendmuchmoretimeresearching,designing,anddebuggingyourappthandoingtheactualcoding,whichistheoppositeofwhatyoumayexpect.
Thesestepsaredescribedinthesectionsthatfollow.You’llusethisprocesswhenyoucreateyourownappinChapter10.
ResearchingwhatyouwanttobuildYouhaveanideaforawebormobileapplication,andusuallyitstartswith“Wouldn’titbegreatif…”Beforewritinganycode,ithelpstodosomeinvestigating.Considerthepossibilitiesinyourprojectasyouanswerthefollowingquestions:
Whatsimilarwebsite/appalreadyexists?Whattechnologywasusedtobuildit?
WhichfeaturesshouldIinclude—andmoreimportantlyexclude—inmyapp?Whichproviderscanhelpcreatethesefeatures?Forexample,companieslikeGoogle,Yahoo,Microsoft,orothersmayhavesoftwarealreadybuiltthatyoucouldincorporateintoyourapp.
Toillustrate,considertherestaurantappIdiscussedearlier.Whenconductingmarketresearchandansweringthethreequestionsabove,searchingusingGoogleisusuallythebestresource.SearchingforrestaurantreservationappshowsexistingrestaurantappsthatincludeOpenTable,SeatMe,andLivebookings.OpenTable,forexample,allowsuserstoreserveatablefromrestaurantsdisplayedonamapusingGoogleMaps.
Intherestaurantappexample,you’dwanttoresearchexactlywhatkindsofrestaurantinformationyou’dneedtoprovide,andhowextensivethereservationsystemportionoftheappshouldbe.Inaddition,foreachofthesequestionsyoumustdecidewhethertobuildthefeaturefromscratchoruseanexistingprovider.Forexample,whenprovidingrestaurantinformationdoyouwanttojustshowname,cuisine,address,telephonenumber,andhoursofoperation,ordoyoualsowanttoshowrestaurantmenus?Whenshowingrestaurantdata,doyoupreferextensivecoverageofasinglegeographicalarea,ordoyouwantnationalcoverageevenifthatmeansyou’dcoverfewerrestaurantsinanyspecificarea?
DesigningyourappYourapp’svisualdesignincorporatesallofyourresearchanddescribesexactlyhowyouruserswillinteractwitheverypageandfeature.Becauseyouruserswillbeaccessingyoursitefromdesktop,laptop,andmobiledevices,you’dwanttomakesureyoucreatearesponsive(multi-device)designandcarefullyconsiderhowyoursitewilllookonallthesedevices.Atthisstageoftheprocess,ageneralwebdesigner,illustrator,oruserinterfacespecialistwillhelpcreatevisualdesignsfortheapp.
ManyresponsiveappdesignsandtemplatescanbefoundontheInternetandusedfreely.Forspecificexamples,seeChapter8,orsearchGoogleusingthequeryresponsivewebsitedesignexamples.
Therearetwotypesofvisualdesigns(seeFigure3-2):
Wireframes:Thesearelowfidelitywebsitedrawingsthatshowstructurallythewaysyourcontentandyoursite’sinterfaceinteract.Mockups:Thesearehighfidelitywebsitepreviewsthatincludecolors,images,andlogos.
Figure3-2:Wireframes(left)aresimplesiterenderings,whereasmockups(right)showfullsitepreviews.
Balsamiqisapopulartoolusedtocreatewireframes,andPhotoshopisapopulartooltocreatemockups.However,youcanavoidpayingforadditionalsoftwarebyusingPowerPoint(PC),Keynote(Mac),orthefreeandopen-sourceOpenOfficetocreateyourappdesigns.
ProfessionaldesignerscreatemockupswithAdobePhotoshopanduselayers,whichisolateindividualsiteelements.AproperlycreatedlayeredPhotoshopfilehelpsdevelopersmoreeasilywritethecodeforthosewebsiteelements.
Inadditiontovisualdesign,complexappswillalsohavetechnicaldesignsanddecisionstofinalize.Forexample,ifyourappstoresandretrievesuserdatayouwillneedadatabasetoperformthesetasks.Initialdecisionsherewillincludethetypeofdatabasetoadd,thespecificdatabaseprovidertouse,
andthebestwaytointegratethedatabaseintotheapplication.Additionally,developersmustdesignthedatabasebychoosingthefieldstostore.Theprocessissimilartotheprocessofcreatingaspreadsheettomodelacompany’sincome—youfirstdecidethenumberofcolumnstouse,andwhetheryou’llincludefieldsasapercentageofrevenueoranumericalvalue,andsoon.Similarly,otherfeatureslikeuserloginsorcreditcardpaymentsallrequireyoutomakechoicesonhowtoimplementthesefeatures.
CodingyourappWithresearchanddesigndone,youarenowreadytocodeyourapplication.Ineverydaywebdevelopment,youwouldbeginbychoosingwhichpagesandfeaturestostartcoding.Asyouworkthroughtheprojectsinthisbook,however,Iwillguideyouonwhattocodefirst.
Knowinghowmuchtocodeandwhentostopcanbetough.Developerscallthefirstiterationofanapptheminimumviableproduct—meaningyou’vecodedjustenoughtotestyourappwithrealusersandreceivefeedback.Ifnoonelikesyourapporthinksit’suseful,it’sbesttofindoutassoonaspossible.
Anappisthesumofitsfeatures,andforanyindividualfeatureit’sagoodideatowritetheminimumcodenecessaryandthenaddtoit.Forexample,yourrestaurantappmayhaveatoolbaratthetopofthepagewithdrop-downmenus.Insteadoftryingtocreatethewholemenuatonce,it’sbettertojustcreatethemenu,andthenlatercreatethedrop-downmenueffect.
Projectscaninvolvefront-enddevelopers,who’llcodetheappearanceoftheapp,andback-enddevelopers,who’llcodethelogicandcreatedatabases.A“fullstackdeveloper”isonewhocandobothfront-endandback-enddevelopment.Onlargeprojectsit’smorecommontoseespecializedfront-endandback-enddevelopers,alongwithprojectmanagerswhoensureeveryoneiscommunicatingwitheachotherandadheringtotheschedulesotheprojectfinishesontime.
DebuggingyourcodeDebuggingisgoingtobeanaturalpartofanyapplication.Thecomputeralwaysfollowsyourinstructionsexactlyandyetnoprogrameverworksasyouexpectitto.Debuggingcanbefrustrating.Threeofthemorecommonmistakestowatchoutforare
Syntaxerrors:Theseareerrorscausedbymisspellingwords/commands,byomittingcharacters,orbyincludingextracharacters.Somelanguages,suchasHTMLandCSS,areforgivingoftheseerrorsandyourcodewillstillworkevenwithsomesyntaxerrors,whereasotherlanguages,suchasJavaScript,aremoreparticularandyourcodewon’trunwhenanysucherrorispresent.Logicerrors:Thesearehardertofix.Withlogicerrors,yoursyntaxiscorrectbuttheprogrambehavesdifferentlythanyouexpected,suchaswhenthepricesoftheitemsintheshoppingcartofane-commercesitedonotsumuptothecorrecttotal.Displayerrors:Thesearecommonmainlytowebapplications.Withdisplayerrors,yourprogrammightrunandworkproperly,butitwon’tappearproperly.Webappstodayrunonmanydevices,browsers,andscreensizes,soextensivetestingistheonlywaytocatchthesetypesoferrors.
Theworddebuggingwaspopularizedinthe1940sbyGraceHopper,whofixedacomputererrorbyliterallyremovingamothfromacomputer.
PickingToolsfortheJobNowyou’rereadytoactuallystartcoding.Youcandevelopwebsiteseitheroffline,byworkingwithaneditor,oronline,withawebservicesuchasCodecademy.com.Especiallyifyouhaveneverdoneanycodingbefore,IwouldstronglyrecommendyoucodewithaccesstoanInternetconnectionusingtheCodecademy.complatformbecauseyoudonothavetodownloadandinstallanysoftwaretostartcoding,youdonothavetofindawebhosttoserveyourwebpages,andyoudonotneedtouploadyourwebpagetoawebhost.Asyoucode,theCodecademy.complatformwilldothesetasksforyouautomatically.
WorkingofflineTocodeoffline,you’llneedthefollowing:
Editor:Thisreferstothetexteditoryou’llusetowriteallthecodeyoulearninthisbook,includingHTML,CSS,JavaScript,Ruby,Python,andPHP.Theeditoryouusewilldependonthetypeofcomputeryouhave:
PC:Usethepre-installedNotepad,orinstallNotepad++,afreeeditoravailablefordownloadathttp://notepad-plus-plus.org.
Mac:Usethepre-installedTextEditorinstallTextMate2.0,anopen-sourceeditoravailablefordownloadathttp://macromates.com.
Browser:Manybrowsersexist,includingFirefox,Safari,InternetExplorer,andOpera;however,IrecommendyouuseChrome,becauseitoffersthemostsupportforthelatestHTMLstandards.It’savailablefordownloadatwww.google.com/chrome/browser.
Webhost:InorderforyourwebsitecodetobeaccessibletoeveryoneontheInternet,youneedtohostyourwebsiteonline.FreemiumwebhostsincludeWeebly(www.weebly.com)andWix(www.wix.com);thesesitesofferbasichostingbutchargeforadditionalfeatureslikeadditionalstorageorremovingads.GoogleprovidesfreewebhostingthroughSites(http://sites.google.com)andDrive(http://drive.google.com).
WorkingonlinewithCodecademy.comCodecademy.comistheeasiestwaytostartlearninghowtocodeonline,andlessonsfromthesiteformthebasisofthisbook.Thesitedoesn’trequireyoutoinstallacodeeditororsignupforawebhostbeforeyoustartcoding,andit’sfreetoindividualuserslikeyou.
Thesitecanbeaccessedusinganyup-to-datemodernbrowser,butGoogleChromeorMozillaFirefoxisrecommended.
TouringthelearningenvironmentAftersigninguporsigningintothesite,youwilleitherseeaninteractivecardorthecodinginterface,dependingonthecontentyoulearn.(SeeFigure3-3.)
Figure3-3:Codecademy.cominteractivecards(left)andthecodinginterface(right).
Theinteractivecardsallowyoutoclicktogglebuttonstodemonstrateeffectsofpre-writtencode,whereasthecodinginterfacehasancodingeditorandalivepreviewwindowthatshowsyoutheeffectsofthecodeenteredintothecodingeditor.
Thecodinginterfacehasfourparts:
Backgroundinformationontheupper-leftsideofthescreentellsyouaboutthecodingtaskyouareabouttodo.Thelower-leftsideofthescreenshowsinstructionstocompleteinthecodingwindow.Thecodingwindowallowsyoutofollowtheexerciseinstructionsandwritecode.Thecodingwindowalsoincludesapreviewscreenthatshowsalivepreviewofyourcodeasyoutype.Aftercompletingthecodinginstructions,pressSave&SubmitorRun.Ifyousuccessfullyfollowedtheinstructions,youadvancetothenextexercise;otherwise,thesitewillgiveyouahelpfulerrormessageandahint.
Theinteractivecardshavethreeparts:
Backgroundinformationaboutacodingconcept.Acodingwindowtocompleteonesimplecodingtask.Apreviewwindowalsoshowsalivepreviewofyourcodeasyoutype.Aftercompletingthecodinginstructions,presstheGotItbutton.YoucanreviewanypreviousinteractivecardsbyclickingtheGoBackbutton.
Receivingsupportfromthecommunity
Ifyourunintoaproblemorhaveabugyoucannotfix,trythefollowingsteps
Clickonthehintunderneaththeinstructions.UsetheQ&AForumstopostyourproblemorquestion,andreviewquestionsothershaveposted.Tweetmeat@nikhilgabrahamwithyourquestionorproblem,andincludethehashtag#codingFDattheendofyourtweet.
PartIIBuildingtheSilentandInteractive
WebPage
BuildwebpagesusingHTML,CSS,andJavaScriptatwww.dummies.com/extras/coding.
Inthispart…PlacecontentonwebpageswithHTML,andstylingcontentwithCSS.StructureyourwebsitelayoutwithHTMLandCSS.Createyourfirstwebpage—theAirbnbhomepage.AddinteractivitytowebpageswithJavaScript.AccessreallivedatawithAPIs.
Chapter4ExploringBasicHTML
InThisChapterLearningthepurposeofHTMLUnderstandingbasicHTMLstructureAddingheadlines,paragraphs,hyperlinks,andimagesFormattingwebpagetextCreatingabasicHTMLwebsite
Youaffecttheworldbywhatyoubrowse.—TimBerners-Lee
HTML,orHyperTextMarkupLanguage,isusedineverysinglewebpageyoubrowseontheInternet.Becausethelanguageissofoundational,agoodfirststepforyouistostartlearningHTML.
Inthischapter,youlearnHTMLbasics,includingbasicHTMLstructureandhowtomaketextappearinthebrowser.Next,youlearnhowtoformattextanddisplayimagesinawebbrowser.Finally,youcreateyourown,andpossiblyfirst,HTMLwebsite.YoumayfindthatHTMLwithoutanyadditionalstylingappearstobeveryplain,anddoesnotlooklikethewebsitesyounormallyvisitontheInternet.AfteryoucodeabasicwebsiteusingHTML,youwilluseadditionallanguagesinlaterchapterstoaddevenmorestyletoyourwebsites.
WhatDoesHTMLDo?HTMLinstructsthebrowseronhowtodisplaytextandimagesinawebpage.Recallthelasttimeyoucreatedadocumentwithawordprocessor.WhetheryouuseMicrosoftWordorWordpad,ApplePages,oranotherapplication,yourwordprocessorhasamainwindowinwhichyoutypetext,andamenuortoolbarwithmultipleoptionstostructureandstylethattext
(seeFigure4-1).Usingyourwordprocessor,youcancreateheadings,writeinparagraphs,insertpictures,orunderlinetext.Similarly,youcanuseHTMLtostructureandstyletextthatappearsonwebsites.
Figure4-1:Thelayoutofawordprocessor.
Markuplanguagedocuments,likeHTMLdocuments,arejustplaintextfiles.Unlikedocumentscreatedwithawordprocessor,youcanviewanHTMLfileusinganywebbrowseronanytypeofcomputer.
HTMLfilesareplaintextfilesthatwillappearstyledonlywhenviewedwithabrowser.Bycontrast,therichtextfileformatusedbywordprocessorsaddunseenformattingcommandstothefile.Asaresult,HTMLwritteninarichtextfilewon’trendercorrectlyinthebrowser.
UnderstandingHTMLStructureHTMLfollowsafewrulestoensurethatawebsitewillalwaysdisplayinthesamewaynomatterwhichbrowserorcomputerisused.Onceyouunderstandtheserules,you’llbebetterabletopredicthowthebrowserwilldisplayyourHTMLpages,andtodiagnoseyourmistakeswhen(notif!)thebrowserdisplaysyourwebpagedifferentlythanyouexpected.Sinceitscreation,HTMLhasevolvedtoincludemoreeffects,butthefollowingbasicstructuralelementsremainunchanged.
YoucanuseanybrowsertodisplayyourHTMLfiles,thoughIstronglyrecommendyoudownload,install,anduseChromeorFirefox.Bothofthesebrowsersareupdatedoften,aregenerallyfast,andsupportandconsistentlyrenderthewidestvarietyofHTMLtags.
IdentifyingelementsHTMLusesspecialtextkeywordscalledelementstostructureandstyleawebsite.Thebrowserrecognizesanelementandappliesitseffectifthefollowingthreeconditionsexist:
Theelementisaletter,word,orphrasewithspecialmeaning.Forexample,h1isanelementrecognizedbythebrowsertoapplyaheadereffect,withboldtextandanenlargedfontsize.Theelementisenclosedwithaleft-anglebracket(<)andright-anglebracket(>).Anelementenclosedinthiswayiscalledatag(suchas,forexample,<h1>).
Anopeningtag(<element>)isfollowedbyaclosingtag(</element>).Notethattheclosingtagdiffersfromtheopeningtagbytheadditionofaforwardslashafterthefirstleftbracketandbeforetheelement(suchas,forexample,</h1>).
SomeHTMLtagsareself-closing,anddon’tneedseparateclosingtags,onlyaforwardslashintheopeningtag.Formoreaboutthis,seethesection,“GettingFamiliarwithCommonHTMLTasksandTags,”laterinthischapter.
Whenallthreeconditionsaremet,thetextbetweentheopeningandclosingtagsisstyledwiththetag’sdefinedeffect.Ifevenoneoftheseconditionsisnotmet,thebrowserjustdisplaysplaintext.
Forabetterunderstandingofthesethreeconditions,seetheexamplecodebelow:
<h1>Thisisabigheadingwithallthreeconditions</h1>
h1Thisistextwithoutthe<and>signsurroundingthetag/h1<rockstar>Thisistextwithatagthathasnomeaningtothebrowser</rockstar>Thisisregulartext
YoucanseehowabrowserwoulddisplaythiscodeinFigure4-2.
Figure4-2:Theexamplecodedisplayedinabrowser.
Thebrowserappliesaheadereffectto“Thisisabigheadingwithallthreeconditions”becauseh1isaheadertagandallthreeconditionsforavalidHTMLtagexist:
Thebrowserrecognizestheh1element.
Theh1elementissurroundedwithaleft(<)andrightanglebracket(>).
Theopeningtag(<h1>)isfollowedbytextandthenaclosingtag(</h1>).
Noticehowtheh1tagitselfdoesnotdisplayintheheading.ThebrowserwillneverdisplaytheactualtextofanelementinaproperlyformattedHTMLtag.
Theremaininglinesofcodedisplayasplaintextbecausetheyeacharemissingoneoftheconditions.Onthesecondlineofcode,the<h1>tagismissingtheleftandrightbrackets,whichviolatesthesecondcondition.ThethirdlineofcodeviolatesthefirstconditionbecauserockstarisnotarecognizedHTMLelement.(Onceyoufinishthischapter,however,youmayfeellikearockstar!)Finally,thefourthlineofcodedisplaysasplaintextbecauseithasnoopeningtagprecedingthetext,andnoclosingtagfollowingthetext,whichviolatesthethirdcondition.
Everyleftangle-bracketmustbefollowedaftertheelementwitharightangle-bracket.Inaddition,everyopeningHTMLtagmustbefollowedwithaclosingHTMLtag.
Over100HTMLelementsexist,andwecoverthemostimportantelementsinthefollowingsections.Fornow,don’tworryaboutmemorizingindividualelementnames.
HTMLisaforgivinglanguage,andmayproperlyapplyaneffectevenifyou’remissingpiecesofcode,likeaclosingtag.However,ifyouleaveintoomanyerrors,yourpagewon’tdisplaycorrectly.
FeaturingyourbestattributeAttributesprovideadditionalwaystomodifythebehaviorofanelementorspecifyadditionalinformation.Usually,butnotalways,yousetanattributeequaltoavalueenclosedinquotes.Here’sanexampleusingthetitleattributeandthehiddenattribute:
<h1title="UnitedStatesofAmerica">USA</h1><h1hidden>NewYorkCity</h1>
Thetitleattributeprovidesadvisoryinformationabouttheelementthatappearswhenthemousecursorhoversovertheaffectedtext(inotherwords,atooltip).Inthisexample,thewordUSAisstyledasaheaderusingthe<h1>tagwithatitleattributesetequalto"UnitedStatesofAmerica".Inabrowser,then,whenyouplaceyourmousecursoroverthewordUSA,thetextUnitedStatesofAmericadisplaysasatooltip.(SeeFigure4-3.)
Figure4-3:Aheadingwithtitleattributehasatooltip.
Thehiddenattributeindicatesthattheelementisnotrelevant,sothebrowserwon’trenderanyelementswiththisattribute.Inthisexample,thewordsNewYorkCityneverappearinthebrowserwindowbecausethehiddenattributeisintheopening<h1>tag.Morepractically,hiddenattributesareoftenusedtohidefieldsfromuserssotheycan’teditthem.Forexample,anRSVPwebsitemaywanttoincludebuthidefromuserviewadateandtimefield.
ThehiddenattributeisnewinHTML5,whichmeansitmaynotworkonsomeolderbrowsers.
Youdon’thavetouseoneattributeatatime.YoucanincludemultipleattributesintheopeningHTMLtag,likethis:
<h1title="UnitedStatesofAmerica"lang="en">USA</h1>
Inthisexample,Iusedthetitleattribute,andthelangattribute,settingitequalto"en"tospecifythatthecontentoftheelementisintheEnglishlanguage.
Whenincludingmultipleattributes,separateeachattributewithonespace.
Keepthefollowingrulesinmindwhenusingattributes:
Ifusinganattribute,alwaysincludetheattributeintheopeningHTMLtag.
Multipleattributescanmodifyasingleelement.Iftheattributehasavalue,thenusetheequalsign(=)andenclosethevalueinquotes.
Standinghead,title,andbodyabovetherestHTMLfilesarestructuredinaspecificwaysobrowserscancorrectlyinterpretthefile’sinformation.EveryHTMLfilehasthesamefiveelements:fourwhoseopeningandclosingtagsappearonceandonlyonce,andonethatappearsonceanddoesn’tneedaclosingtag.Theseareasfollows:
!DOCTYPEhtmlmustappearfirstinyourHTMLfile,anditappearsonlyonce.ThistagletsbrowsersknowwhichversionofHTMLyouareusing.Inthiscase,it’sthelatestversion,HTML5.Noclosingtagisnecessaryforthiselement.
ForHTML4websites,thefirstlineintheHTMLfilewouldread<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
htmlrepresentstherootorbeginningofanHTMLdocument.The<html>tagisfollowedbyfirstanopeningandclosing<head>tag,andthenanopeningandclosing<body>tag.
headcontainsotherelements,whichspecifygeneralinformationaboutthepage,includingthetitle.titledefinesthetitleinthebrowser’stitlebarorpagetab.SearchengineslikeGoogleusetitletorankwebsitesinsearchresults.
bodycontainsthemaincontentofanHTMLdocument.Text,images,andothercontentlistedbetweentheopeningandclosingbodytagisdisplayedbythebrowser.
HereisanexampleofaproperlystructuredHTMLfilewiththesefivetags(seeFigure4-4):
<!DOCTYPEhtml>
<html><head><title>FavoriteMovieQuotes</title></head><body><h1>"I'mgoingtomakehimanofferhecan'trefuse"</h1><h1>"Houston,wehaveaproblem"</h1><h1>"MaytheForcebewithyou"</h1><h1>"Youtalkingtome?"</h1></body></html>
Figure4-4:AwebpagecreatedwithbasicHTMLelements.
Usingspacestoindentandseparateyourtagsishighlyrecommended.Ithelpsyouandothersreadandunderstandyourcode.Thesespacesareonlyforyouandanyotherhumanthatreadsthecode,however.Yourbrowserwon’tcare.Asfarasyourbrowserisconcerned,youcouldrunallyourtagstogetherononeline.(Don’tdothis,though.Thenextpersonthatreadsyourcodewillbemostunhappy.)HTMLdoesrecognizeanddisplaythefirstwhitespacecharacterintextbetweenopeningandclosingHTMLtags.
Ourexamplehadmanyh1tagsbutonlyoneopeningandclosinghtml,head,title,andbodytag.
GettingFamiliarwithCommonHTMLTasksandTags
YourbrowsercaninterpretoverahundredHTMLtags,butmostwebsitesusejustafewtagstodomostoftheworkwithinthebrowser.Tounderstandthis,let’stryalittleexercise:Thinkofyourfavoritenewswebsite.Haveoneinmind?NowconnecttotheInternet,openyourbrowser,andtypeintheaddressofthatwebsite.Bringthisbookwithyou,andtakeyourtime—Icanwait!
Intheeventyoucan’taccesstheInternetrightnow,takealookatthearticlefrommyfavoritenewswebsite,TheNewYorkTimes,foundinFigure4-5.
Figure4-5:ANewYorkTimesarticlewithheadline,paragraphs,hyperlinks,andimages.
Lookcloselyatthenewswebsiteonyourscreen(orlookatmine).FourHTMLelementsareusedtocreatethemajorityofthepage:
Headlines:Headlinesaredisplayedinboldandhavealargerfontsize
thanthesurroundingtext.Paragraphs:Eachstoryisorganizedintoparagraphswithwhitespacedividingeachparagraph.Hyperlinks:Thesite’shomepageandarticlepageshavelinkstootherstories,andlinkstosharethestoryonsocialnetworkslikeFacebook,Twitter,andGoogle+.Images:Writersplaceimagesthroughoutthestory,butalsolookforsiteimageslikeiconsandlogos.
InthefollowingsectionsIexplainhowtowritecodetocreatethesecommonHTMLfeatures.
WritingheadlinesUseheadlinestodescribeasectionofyourpage.HTMLhassixlevelsofheadings(seeFigure4-6):
h1,whichisusedforthemostimportantheadings
h2,whichisusedforsubheadings
h3toh6,whichareusedforlessimportantheadings
Thebrowserrendersh1headingswithafontsizelargerthanh2’s,whichinturnislargerthanh3’s.Headingsstartwithanopeningheadingtag,theheadingtext,andthentheclosingheadingtag,asfollows:
<h1>Headingtexthere</h1>
Herearesomeadditionalcodeexamplesshowingvariousheadings:<h1>Heading1:"I'mgoingtomakehimanofferhecan'trefuse"</h1><h2>Heading2:"Houston,wehaveaproblem"</h2><h3>Heading3:"MaytheForcebewithyou"</h3><h4>Heading4:"Youtalkingtome?"</h4><h5>Heading5:"I'llbeback"</h5><h6>Heading6:"Myprecious"</h6>
Figure4-6:Headingscreatedusingelementsh1throughh6.
Alwaysclosewhatyouopen.Withheadings,remembertoincludeaclosingheadingtag,suchas</h1>.
OrganizingtextinparagraphsTodisplaytextinparagraphsyoucanusethepelement:Placeanopening<p>tagbeforetheparagraph,andaclosingtagafterit.Thepelementtakestextandinsertsalinebreakaftertheclosingtag.
Toinsertasinglelinebreakafteranyelement,usethe<br>tag.The<br>tagisself-closingsonoclosingtagisneeded,and</br>isnotused.
Paragraphsstartwithanopeningparagraphtag,theparagraphtext,andthentheclosingparagraphtag:
<p>Paragraphtexthere</p>
Someadditionalexamplesofcodingaparagraph(seeFigure4-7):<p>Armstrong:Okay.I'mgoingtostepofftheLMnow.</p><p>Armstrong:That'sonesmallstepforman;onegiantleapformankind.</p><p>Armstrong:Yes,thesurfaceisfineandpowdery.Icankickituplooselywithmytoe.Itdoesadhereinfine
layers,likepowderedcharcoal,tothesoleandsidesofmyboots.</p>
Figure4-7:Textdisplayedinparagraphsusingthepelement.
Linkingtoyour(heart’s)contentHyperlinksareoneofHTML’smostvaluablefeatures.Webpagesthatincludehyperlinkedreferencestoothersourcesallowthereadertoaccessthosesourceswithjustaclick,abigadvantageoverprintedpages.
Hyperlinkshavetwoparts:
Linkdestination:Thewebpagethebrowservisitsoncethelinkisclicked.
TodefinethelinkdestinationinHTML,startwithanopeninganchortag(<a>)thathasanhrefattribute.Then,addthevalueofthehrefattribute,whichisthewebsitethebrowserwillgotooncethelinkisclicked.
Linkdescription:Thewordsusedtodescribethelink.
Todothis,addtexttodescribethelinkaftertheopeninganchortag,andthenaddtheclosinganchortag.
TheresultingHTMLshouldlooksomethinglikethis:<ahref="websiteurl">Linkdescription</a>
Threemoreexamplesofcodingahyperlink(seeFigure4-8):
<ahref="http://www.amazon.com">Purchaseanything</a><ahref="http://www.airbnb.com">Rentaplacetostayfromalocalhost</a><ahref="http://www.techcrunch.com">Techindustryblog</a>
Figure4-8:Threehyperlinkscreatedusingtheaelement.
Whenrenderinghyperlinks,thebrowser,bydefault,willunderlinethelinkandcolorthelinkblue.Tochangethesedefaultproperties,seeChapter6.
The<a>tagdoesnotincludealinebreakafterthelink.
Google’ssearchenginerankswebpagesbasedonthewordsusedtodescribeawebpagebetweentheopeningandclosing<a>tags.Thisimprovedonsearchresultsfrompreviousmethods,whichreliedprimarilyonanalyzingpagecontent.
AddingimagesImagesspruceupotherwiseplainHTMLtextpages.Toincludeanimageonyourwebpage—yourownorsomeoneelse’s—youmustobtaintheimage’swebaddress.WebsiteslikeGoogleImages(images.google.com)andFlickr(www.flickr.com)allowyoutosearchforonlineimagesbasedonkeywords.Whenyoufindanimageyoulike,right-clickontheimage,andselectCopyImageURL.
Makesureyouhavepermissiontouseanonlineimage.Flickrhastoolsthatallowyoutosearchforimageswithfewtonolicenserestrictions.Additionally,websitespaytohostimages,andincurcharges
whenawebsitedirectlylinkstoanimage.Forthisreason,somewebsitesdonotallowhotlinking,orlinkingdirectlyfromthird-partywebsites(likeyou)toanimage.
IfyouwanttouseanimagethathasnotalreadybeenuploadedtotheInternet,youcanuseasitelikewww.imgur.comtouploadtheimage.Afteruploading,youwillbeabletocopytheimageURLanduseitinyourHTML.
Toincludeanimage,startwithanopeningimagetag<img>,definethesourceoftheimageusingthesrcattribute,andincludeaforwardslashattheendoftheopeningtagtoclosethetag(seeFigure4-9):
<imgsrc="http://upload.wikimedia.org/wikipedia/commons/5/55/Grace_Hopper.jpg"/><imgsrc="http://upload.wikimedia.org/wikipedia/commons/b/bd/Dts_news_bill_gates_wikipedia.JPG"/>
Figure4-9:ImagesofGraceHopper,aUSNavyrearadmiral,andBillGates,theco-founderofMicrosoft,renderedusing<img>.
Theimagetagisself-closing,whichmeansaseparate</img>closingimagetagisnotused.Theimagetagisoneoftheexceptionstothealways-close-what-you-openrule!
StylingMePrettyNowthatyouknowhowtodisplaybasictextandimagesinabrowser,youshouldunderstandhowtofurthercustomizeandstylethem.HTMLhasbasiccapabilitiestostylecontent,andlaterchaptersshowyouhowtouseCSStostyleandpositionyourcontentdowntothelastpixel.Here,however,IexplainhowtodosomebasictextformattinginHTML,andthenyou’llbuildyourfirstwebpage.
Highlightingwithbold,italics,underline,andstrikethroughHTMLallowsforbasictextstylingusingthefollowingelements:
strongmarksimportanttext,whichthebrowserdisplaysasbold.
emmarksemphasizedtext,whichthebrowserdisplaysasitalicized.
umarkstextasunderlined.
delmarksdeletedtext,whichthebrowserdisplaysasstrikethrough.
Theunderlineelementisnottypicallyusedfortextbecauseitcanleadtoconfusion.Hyperlinks,afterall,areunderlinedbydefault.
Tousetheseelements,startwiththeelement’sopeningtag,followedbytheaffectedtext,andthenaclosingtag,asfollows:
<elementname>Affectedtext</elementname>
Someexamples(seeFigure4-10):GraceHopper,<strong>aUSNavyrearadmiral</strong>,popularizedtheterm"debugging."BillGatesco-foundedacompanycalled<em>Microsoft</em>.StuartRussellandPeterNorvigwroteabookcalled<u>ArtificialIntelligence:AModernApproach</u>.MarkZuckerbergcreatedawebsitecalled<del>Nosebook</del>Facebook.SteveJobsco-foundedacompanycalled<del>
<em>Peach</em></del><em>Apple</em>
Figure4-10:Sentencesformattedusingbold,italics,underline,andstrikethrough.
YoucanapplymultipleeffectstotextbyusingmultipleHTMLtags.Alwaysclosethemostrecentlyopenedtagfirstandthenthenextmostrecentlyusedtag.Foranexample,lookatthelastlineofcodeinFigure4-10,andthetagsappliedtothewordPeach.
RaisingandloweringtextwithsuperscriptandsubscriptReferenceworkslikeWikipedia,andtechnicalpapersoftenusesuperscriptforfootnotesandsubscriptforchemicalnames.Toapplythesestyles,usetheelements
supfortextmarkedassuperscript
subfortextmarkedassubscript
Tousetheseelements,startwiththeelement’sopeningtag,followedbytheaffectedtext,andthenaclosingtagasfollows:
<elementname>Affectedtext</elementname>
Twoexamples(seeFigure4-11):<p>TheUniversityofPennsylvaniaannouncedtothepublicthefirstelectronicgeneral-purposecomputer,namedENIAC,onFebruary14,1946.<sup>1</sup></p><p>TheCentersforDiseaseControlandPreventionrecommendsdrinkingseveralglassesofH<sub>2</sub>0perday.</p>
Whenusingthesuperscriptelementtomarkfootnotes,usean<a>anchortagtolinkdirectlytothefootnotesothereadercanviewthefootnoteeasily.
Figure4-11:Textformattedtoshowsuperscriptandsubscripteffects.
BuildingYourFirstWebsiteUsingHTML
Nowthatyouhavelearnedthebasics,youcanputthatknowledgetouse.Youcanpracticedirectlyonyourcomputerbyfollowingthesesteps:
1. Openanytexteditor,suchasNotepad(onaPC)orTextEdit(onaMac).
OnaPCrunningMicrosoftWindows,youcanaccessNotepadbyclickingtheStartbuttonandselectingRun;inthesearchbox,typeNotepad.OnaMacintosh,selecttheSpotlightSearch(hourglassicononthetop-rightcornerofthetoolbar),andtypeTextEdit.
2. Enterintothetexteditoranyofthecodesamplesyouhaveseeninthischapter,orcreateyourowncombinationofthecode.
3. Onceyouhavefinished,savethefileandmakesuretoinclude“.html”attheendofthefilename.
4. Double-clickonthefile,whichshouldopeninyourdefaultbrowser.
Youcandownloadatnocostspecializedtexteditorsthathavebeen
createdspecificallyforwritingcode.ForPCs,youcandownloadNotepad++atwww.notepad-plus-plus.org.ForMaccomputers,youcandownloadTextMateathttp://macromates.com/download.
IfyouwouldliketopracticeyourHTMLonline,youcanusetheCodecademywebsite.Codecademyisafreewebsitecreatedin2011toallowanyonetolearnhowtocoderightinthebrowser,withoutinstallingordownloadinganysoftware.(SeeFigure4-12.)Practiceallofthetags(andafewmore)thatyoulearnedinthischapterbyfollowingthesesteps:
1. Openyourbrowser,gotowww.dummies.com/go/codingandclickontheCodecademylink.
2. SignupforaCodecademyaccountorsigninifyoualreadyhaveanaccount.Creatinganaccountallowsyoutosaveyourprogressasyouwork,butit’soptional.
3. NavigatetoandclickonHTMLBasics.4. Backgroundinformationispresentedintheupper-leftportionofthe
site,andinstructionsarepresentedinthelower-leftportionofthesite.
5. Completetheinstructionsinthemaincodingwindow.Asyoutype,alivepreviewofyourcodeisgenerated.
6. Afteryouhavefinishedcompletingtheinstructions,clicktheSaveandSubmitCodebutton.
Ifyouhavefollowedtheinstructionscorrectly,agreencheckmarkappears,andyouproceedtothenextexercise.Ifanerrorexistsinyourcodeawarningappearswithasuggestedfix.Ifyourunintoaproblem,orhaveabugyoucannotfix,clickonthehint,usetheQ&AForums,ortweetmeat@nikhilgabrahamandincludehashtag#codingFD.
Figure4-12:Codecademyin-browserexercises.
HistoryofHTMLAcomputerengineer,TimBerners-Lee,wantedacademicstoeasilyaccessacademicpapersandcollaboratewitheachother.Toaccomplishthisgoal,in1989Mr.Berners-LeecreatedthefirstversionofHTML,whichhadthesamehyperlinkelementsyoulearnedinthischapter,andhostedthefirstwebsitein1991.Unlikemostothercomputersoftware,Mr.Berners-LeemadeHTMLavailableroyalty-free,allowingwidespreadadoptionandusearoundtheworld.ShortlyaftercreatingthefirstiterationofHTML,Mr.Berners-LeeformedtheW3C(“WorldWideWebConsortium”),whichisagroupofpeoplefromacademicinstitutionsandcorporationswhodefineandmaintaintheHTMLlanguage.TheW3CcontinuestodeveloptheHTMLlanguage,andhasdefinedmorethan100HTMLelements,farmorethanthe18Mr.Berners-Leeoriginallycreated.ThelatestversionofHTMLisHTML5,andithasconsiderablenewfunctionality.InadditiontosupportingelementsfrompreviousHTMLversions,HTML5allowsbrowserstoplayaudioandvideofiles,easilylocateauser’sphysicallocation,andbuildchartsandgraphs.
Chapter5GettingMoreOutofHTML
InThisChapterOrganizingcontentinawebpageWritingHTMLlistsCreatingHTMLtablesFillingoutHTMLforms
I’mcontrolling,andIwanteverythingorderly,andIneedlists.—SandraBullock
Evenyourbestcontentneedsstructuretoincreasereadabilityforyourusers.Thisbookisnoexception.Considerthe“InThisChapter”bulletedlistofitemsatthetopofthispage,orthetableofcontentsatthebeginningofthebook.Listsandtablesmakethingseasierforyoutounderstandataglance.Bymirroringthestructureyoufindinabookormagazine,webelementsletyoupreciselydefinehowcontent,suchastextandimages,appearontheweb.
Inthischapter,youlearnhowtouseHTMLelementssuchaslists,tables,andforms,andhowtoknowwhentheseelementsareappropriateforyourcontent.
OrganizingContentonthePageReadabilityisthemostimportantprinciplefororganizinganddisplayingcontentonyourwebpage.Yourwebpageshouldallowvisitorstoeasilyread,understand,andactonyourcontent.Thedesiredactionyouhaveinmindforyourvisitorsmaybetoclickonandreadadditionalcontent,sharethecontentwithothers,orperhapsmakeapurchase.Poorlyorganizedcontentwillleaduserstoleaveyourwebsitebeforeengagingwithyourcontentforlongenoughtocompletethedesiredaction.
Figures5-1and5-2showtwoexamplesofwebsitereadability.InFigure5-1,IsearchedCraigslist.orgforanapartmentinNewYork.Thesearchresultsarestructuredlikealist,andyoucanlimitthecontentdisplayedusingthefiltersandsearchforms.Eachlistinghasmultipleattributes,suchasadescription,thenumberofbedrooms,theneighborhood,and,mostimportantly,theprice.Comparingsimilarattributesfromdifferentlistingstakessomeeffort—noticethejaggedlineyoureyemustfollow.
Figure5-2showstheresultsofasearchIconductedatHipmunk.comforflightsfromNewYorktoLondon.AswiththeCraigslistsearchresults,youcanlimitthecontentdisplayedusingthefiltersandsearchforms.Additionally,eachflightlistinghasmultipleattributes,includingprice,carrier,departuretime,landingtime,andduration,whicharesimilartotheattributesoftheapartmentlistings.ComparingsimilarattributesfromdifferentflightsismucheasierwiththeHipmunklayout,however.Noticehowthecontent,incontrasttoCraigslist’s,hasalayoutthatallowsyoureyetofollowastraightlinedownthepage,soyoucaneasilyrankandcomparedifferentoptions.
Figure5-1:ACraigslist.orglistingofapartmentsinNewYork(2014).
Don’tunderestimatethepowerofsimplicitywhendisplayingcontent.AlthoughCraigslist’scontentlayoutmaylookalmosttoosimple,thesiteisoneofthetop50mostvisitedwebsitesintheworld.Reddit.comisanotherexampleofatop50websitewithasimplelayout.
Figure5-2:AHipmunk.comlistingofflightsfromNewYorktoLondon(2014).
Beforedisplayingyourcontent,askyourselfafewquestionsfirst:
Doesyourcontenthaveoneattributewithrelateddata,ordoesitfollowsequentialsteps?Ifso,considerusinglists.Doesyourcontenthavemultipleattributessuitableforcomparison?Ifso,considerusingtables.Doyouneedtocollectinputfromthevisitor?Ifso,considerusingforms.
Don’tletthesechoicesoverwhelmyou.Pickone,seehowyourvisitorsreact,andifnecessarychangehowyoudisplaythecontent.TheprocessofevaluatingoneversionagainstanotherversionofthesamewebpageiscalledA/Btesting.
ListingDataWebsiteshaveusedlistsfordecadestoconveyrelatedorhierarchicalinformation.InFigure5-3,youcanseeanolderversionofYahoo.comthatusesbulletedliststodisplayvariouscategoriesandtoday’sAllrecipes.comrecipepage,whichusesliststodisplayvariousingredients.
Figure5-3:Yahoo’s1997homepageusinganunorderedlist(left)andAllrecipes.com’s2014recipeusinganorderedlist(right).
Listsbeginwithasymbol,anindentation,andthenthelistitem.Thesymbolusedcanbeanumber,letter,bullet,ornosymbolatall.
CreatingorderedandunorderedlistsThetwomostpopulartypesoflistsare:
Ordered:Orderedlistsarenumericaloralphabeticallistsinwhichthesequenceoflistitemsisimportant.Unordered:Theselistsareusuallybulletedlistsinwhichthesequenceoflistitemshasnoimportance.
Youcreatelistsbyspecifyingthetypeoflistasorderedorunordered,andthenaddingeachlistitemusingthelitag,asshowninthefollowingsteps:
1. Specifythetypeoflist.
Addopeningandclosinglisttagsthatspecifyeitheranordered(ol)orunordered(ul)list,asfollows:
oltospecifythebeginningandendofanorderedlist.
ultospecifythebeginningandendofanunorderedlist.
2. Addanopeningandclosingtag(thatis,<li>and</li>)foreachiteminthelist.
Forexample,here’sanorderedlist:
<ol>
<li>Listitem#1</li><li>Listitem#2</li><li>Listitem#3</li></ol>
NestinglistsAdditionally,youcannestlistswithinlists.Alistofanytypecanbenestedinsideanotherlist;tonestalist,replacethelistitemtag<li>withalisttypetag,either<ol>or<ul>.
TheexamplecodeinFigure5-4showsvariousliststypesincludinganestedlist.(SeeFigures5-4and5-5.)
Figure5-4:Codinganorderedlistandanestedlist.
Figure5-5:ThepageproducedbythecodeinFigure5-4.
The<h1>tagshowninthiscodesampleisnotnecessarytocreatealist.Iuseithereonlytonameeachlist.
Everyopeninglistorlistitemtagmustbefollowedwithaclosinglistorlistitemtag.
PuttingDatainTablesTableshelpfurtherorganizetextandtabulardataonthepage.(SeeFigure5-6.)Thetableformatisespeciallyappropriatewhendisplayingpricinginformation,comparingfeaturesacrossproducts,orinanysituationwherethecolumnsorrowsshareacommonattribute.Tablesactascontainers,andcanholdanddisplayanytypeofcontent,includingtext,suchasheadingandlists,andimages.Forexample,thetableinFigure5-6includesadditionalcontentandstylinglikeiconsatthetopofeachcolumn,graybackgroundshading,androundedbuttons.Thiscontentandstylingcanmaketablesyouseeonlinedifferfromtablesyouordinarilyseeinbooks.
Figure5-6:Box.netusestablestodisplaypricinginformation.
Avoidusingtablestocreatepagelayouts.Inthepast,developerscreatedmulti-columnlayoutsusingtables,buttodaydevelopersuseCSS(seeChapter7)forlayout-relatedtasks.
BasictablestructuringTablesarecomprisedofseveralparts,liketheoneshowninFigure5-7.
Figure5-7:Thedifferentpartsofatable.
Youcreateatablebyusingthefollowingbasicsteps:
1. Defineatablewiththetableelement.
Todothis,addtheopeningandclosing<table>tags.
2. Dividethetableintorowswiththetrelement.
Betweentheopeningandclosingtabletags,createopening<tr>tagsandclosing</tr>tagsforeachrowofyourtable.
3. Dividerowsintocellsusingthetdelement.
Betweentheopeningandclosingtrtags,createopeningandclosingtdtagsforeachcellintherow.
4. Highlightcellsthatareheadersusingthethelement.
Finally,specifyanycellsthatareheadersbyreplacingthetdelementwithathelement.
Yourtablewillhaveonlyoneopeningandclosing<table>tag;however,youcanhaveoneormoretablerows(tr)andcells(td).
ThefollowingexamplecodeshowsthesyntaxforcreatingthetableshowninFigure5-7.
<table><tr><th>Tableheader1</th><th>Tableheader2</th></tr><tr><td>Row#1,Cell#1</td><td>Row#1,Cell#2</td></tr><tr><td>Row#2,Cell#1</td><td>Row#2,Cell#2</td></tr></table>
Afteryou’vedecidedhowmanyrowsandcolumnsyourtablewillhave,makesuretouseanopeningandclosing<tr>tagforeachrow,andanopeningandclosing<td>tagforeachcellintherow.
StretchingtablecolumnsandrowsTakealookatthetabledescribingFacebook’sincomestatementinFigure5-8.Datafor2011,2012,and2013appearsinindividualcolumnsofequal-sizedwidth.NowlookatTotalRevenue,whichappearsinacellthatstretchesorspansacrossseveralcolumns.
Figure5-8:Anincomestatementinatablewithcolumnsofdifferentsizes.
Stretchingacellacrosscolumnsorrowsiscalledspanning.
Thecolspanattributespansacolumnoversubsequentverticalcolumns.Thevalueofthecolspanattributeissetequaltothenumberofcolumnsyouwanttospan.Youalwaysspanacolumnfromlefttoright.Similarly,therowspanattributespansarowoversubsequenthorizontalrows.Setrowspanequaltothenumberofrowsyouwanttospan.
ThefollowingcodegeneratesapartofthetableshowninFigure5-8.YoucanseethecolspanattributespanstheTotalRevenuecellacrosstwocolumns.AsdescribedinChapter4,the<strong>tagisusedtomarkimportanttext,andisshownasboldbythebrowser.
<tr><tdcolspan="2"><strong>TotalRevenue</strong></td><td><strong>7,872,000</strong></td><td><strong>5,089,000</strong></td><td><strong>3,711,000</strong></td></tr>
Ifyousetacolumnorrowtospanbymorecolumnsorrowsthanareactuallypresentinthetable,thebrowserwillinsertadditionalcolumnsorrows,changingyourtablelayout.
CSShelpssizeindividualcolumnsandrows,aswellasentiretables.SeeChapter7.
Aligningtablesandcells
ThelatestversionofHTMLdoesnotsupportthetagsandattributesinthissection.Althoughyourbrowsermaycorrectlyrenderthiscode,thereisnoguaranteeyourbrowserwillcorrectlyrenderitinthefuture.Iincludetheseattributesbecauseasofthiswriting,HTMLcodeontheInternet,includingtheYahooFinancesiteinthepreviousexamples,stillusethesedeprecated(older)attributesintables.Thiscodeissimilartoexpletives—recognizethembuttrynottousethem.RefertoChapter6toseemoderntechniquesusingCascadingStyleSheets(CSS)forachievingtheidenticaleffects.
Thetableelementhasthreedeprecatedattributestoknow—align,width,andborder.TheseattributesaredescribedinTable5-1.
Table5-1TableattributesreplacedbyCSS
Attributename
Possiblevalues Description
align
left
center
right
Positionoftablerelativetothecontainingdocumentaccordingtothevalueoftheattribute.Forexample,align="right"positionsthetableontherightsideofthewebpage.
widthpixels(#)
%
Widthoftablemeasuredeitherinpixelson-screenorasapercentageofthebrowserwindoworcontainertag.
border pixels(#) Widthoftableborderinpixels.
ThefollowingexamplecodeshowsthesyntaxforcreatingthetableinFigure5-9withalign,width,andborderattributes.
Figure5-9:Atablewithdeprecatedalign,width,andborderattributes.
<tablealign="right"width=50%border=1><tr><td>TheSocialNetwork</td><td>GenerationLike</td></tr><tr><td>Tron</td><td>WarGames</td></tr></table>
Alwaysinsertattributesinsidetheopening<html>tag,andenclosewordsinquotes.
Thetrelementhastwodeprecatedattributestoknow—align,andvalign.ThesearedescribedinTable5-2.
Table5-2TablerowattributesreplacedbyCSS
Attributename
Possiblevalues Description
align
left
right
center
justify
Horizontalalignmentofarow’scellcontentsaccordingtothevalueoftheattribute.Forexample,align="right"positionsarow’scellcontentsontherightsideofeachcell.
valign
top
middle
bottom
Verticalalignmentofarow’scellcontentsaccordingtothevalueoftheattribute.Forexample,align="bottom"positionsarow’scellcontentsonthebottomofeachcell.
Thetdelementhasfourdeprecatedattributestoknow—align,valign,width,andheight.ThesearedescribedinTable5-3.
Table5-3TablecellattributesreplacedbyCSS
Attributename
Possiblevalues Description
align
left
right
centerHorizontalalignmentofacell’scontentsaccordingtothevalueoftheattribute.Forexample,align="center"positionsthecell’scontentsinthecenterofthecell.
justify
valign
top
middle
bottom
Verticalalignmentofacell’scontentsaccordingtothevalueoftheattribute.Forexample,align="middle"positionsacell’scontentsinthemiddleofthecell.
widthpixels(#)
%
Widthofacellmeasuredeitherinpixelson-screenorasapercentageofthetablewidth.
heightpixels(#)
%
Heightofacellmeasuredeitherinpixelson-screenorasapercentageofthetablewidth.
ThefollowingexamplecodeshowsthesyntaxforcreatingthetableinFigure5-10withalign,valign,width,andheightattributes.
Figure5-10:Atablewithdeprecatedalign,valign,width,andheightattributes.
<tablealign="right"width=50%border=1><tralign="right"valign="bottom"><tdheight=100>TheSocialNetwork</td><td>GenerationLike</td></tr><tr><tdheight=200align="center"valign="middle">Tron</td><tdalign="center"valign="top"width=20%>WarGames</td></tr></table>
Remember,theseattributesarenolongersupportedandshouldnotbeusedinyourcode.
FillingOutFormsFormsallowyoutocaptureinputfromyourwebsitevisitors.Untilnowwehavedisplayedcontentas-is,butcapturinginputfromvisitorsallowsyouto:
Modifyexistingcontentonthepage.Forexample,priceanddatefiltersonairlinewebsitesallowforfindingadesiredflightmorequickly.Storetheinputforlateruse.Forexample,awebsitemayusearegistrationformtocollectyouremail,username,andpasswordinformationtoallowyoutoaccessitatalaterdate.
UnderstandinghowformsworkFormspassinformationenteredbyausertoaserverbyusingthefollowingprocess:
1. Thebrowserdisplaysaformontheclientmachine.2. Theusercompletestheformandpressesthesubmitbutton.3. Thebrowsersubmitsthedatacollectedfromtheformtoaserver.4. Theserverprocessesandstoresthedataandsendsaresponsetotheclient
machine.5. Thebrowserdisplaystheresponse,usuallyindicatingwhetherthe
submissionwassuccessful.
SeeChapter2foranadditionaldiscussionabouttherelationshipbetweentheclientandserver.
Afulldescriptionofhowtheserverreceivesandstoresdata(Steps3to5)isbeyondthescopeofthisbook.Fornow,allyouneedtoknowisthatserver-sideprogramminglanguagessuchasPython,PHP,andRubyareusedtowritescriptsthatreceiveandstoreformsubmissions.
Formsareveryflexible,andcanrecordavarietyofuserinputs.Inputfieldsusedinformscanincludefreetextfields,radiobuttons,checkboxes,drop-
downmenus,rangesliders,dates,phonenumbers,andmore.(SeeTable5-4.)Additionally,inputfieldscanbesettoinitialdefaultvalueswithoutanyuserinput.
Table5-4Selectedformattributes
Attributename Possiblevalues Description
type
checkbox
submit
text
password
radio
(acompletelistofvalueshasbeenomittedhereforbrevity)
Definesthetypeofinputfieldtodisplayintheform.Forexample,textisusedforfreetextfields,andsubmitisusedtocreateasubmitbutton.
value text Theinitialvalueoftheinputcontrol.
Viewtheentirelistofforminputtypesandexamplecodeatwww.w3schools.com/tags/att_input_type.asp.
CreatingbasicformsYoucreateabasicformby
1. Definingaformwiththeformelement.
Startbyaddinganopening<form>tagandclosing</form>tag.
2. Usingtheactionattribute,specifyintheformelementwheretosendformdata.
Addanactionattributetoyouropening<form>tagandsetitequaltotheURLofascriptthatwillprocessandstoretheuserinput.
3. Usingthemethodattribute,specifyintheformelementhowtosendformdata.
Addamethodattributetoyouropening<form>tagandsetitequaltoPOST.
ThemethodattributeissetequaltoGETorPOST.Thetechnicalitiesofeacharebeyondthescopeofthisbook,but,ingeneral,POSTisusedforstoringsensitiveinformation(suchascreditcardnumbers),whereasGETisusedtoallowuserstobookmarkorsharewithotherstheresultsofasubmittedform(suchas,forexample,airlineflightlistings).
4. Providingawayforuserstoinputandsubmitresponseswiththeinputelement.
Betweentheopening<form>andclosing</form>tags,createone<input>tag.
Yourformwillhaveonlyoneopeningandclosing<form>tag;however,youwillhaveatleasttwo<input>tagstocollectandsubmituserdata.
5. Specifyinputtypesusingthetypeattributeintheinputelement.
Forthisexample,setthetypeattributeequalto"text".
The<input>tagdoesnothaveaclosingtag,whichisanexceptiontothe“closeeverytagyouopen”rule.Thesetagsarecalledself-closingtags,andyoucanseemoreexamplesinChapter4.
6. Finally,createanother<input>tagandsetthetypeattributeequaltosubmit.
Thefollowingexamplecodeshowsthesyntaxforcreatingtheformshownin
Figure5-11.
Figure5-11:Aformwithoneuserinputandasubmitbutton.
<formaction="mailto:[email protected]"method="POST"><inputtype="text"value="Typeashortmessagehere"><inputtype="submit"></form>
Theactionattributeinthisformissetequaltomailto,whichsignalstothebrowsertosendanemailusingyourdefaultmailclient(suchasOutlookorGmail).Ifyourbrowserisnotconfiguredtohandleemaillinks,thenthisformwon’twork.Ordinarily,formsaresubmittedtoaservertoprocessandstoretheform'scontents,butinthisexampleformthecontentsaresubmittedtotheuser'semailapplication.
PracticingMorewithHTMLPracticeyourHTMLonlineusingtheCodecademywebsite.Codecademyisafreewebsitecreatedin2011toallowanyonetolearnhowtocoderightinthebrowser,withoutinstallingordownloadinganysoftware.Practiceallofthetags(andafewmore)thatyoulearnedinthischapterbyfollowingthesesteps:
1. Openyourbrowser,gotowww.dummies.com/go/codingandclickonthelinktoCodecademy.
2. SignintoyourCodecademyaccount.
SigningupisdiscussedinChapter3.Creatinganaccountallowsyoutosaveyourprogressasyouwork,butit’soptional.
3. NavigatetoandclickonHTMLBasicsIItopracticecreatinglists,andHTMLBasicsIIItopracticecreatingtables.
4. Backgroundinformationispresentedintheupperleftportionofthesite,andinstructionsarepresentedinthelowerleftportionofthesite.
5. Completetheinstructionsinthemaincodingwindow.Asyoutype,alivepreviewofyourcodeisgenerated.
6. Afteryouhavefinishedcompletingtheinstructions,clicktheSaveandSubmitCodebutton.
Ifyouhavefollowedtheinstructionscorrectly,agreencheckmarkappears,andyouproceedtothenextexercise.Ifanerrorexistsinyourcodeawarningappearswithasuggestedfix.Ifyourunintoaproblemorabugyoucannotfix,clickonthehint,usetheQ&AForum,ortweetmeat@nikhilgabrahamandincludehashtag#codingFD.
Chapter6GettingStylishwithCSS
InThisChapterUnderstandingCSSanditsstructureFormattingtextsize,color,andstyleStylingimagesUsingCSSinthreedifferentcontexts
Createyourownstyle…letitbeuniqueforyourselfandyetidentifiableforothers.
—AnnaWintourThewebsitecodeexamplesIhaveshownyouintheprecedingchaptersresemblewebsitesyoumayhaveseenfromapreviousera.Websitesyoubrowsetodayaredifferent,andhaveamorepolishedlookandfeel.Numerousfactorsenabledthischange.TwentyyearsagoyoumighthavebrowsedtheInternetwithadial-upmodem,buttodayyoulikelyuseaveryfastInternetconnectionandamorepowerfulcomputer.Programmershaveusedthisextrabandwidthandspeedtowritecodetofurthercustomizeandstylewebsites.
InthischapteryoulearnmoderntechniquestostylewebsitesusingCascadingStyleSheets(CSS).First,IdiscussbasicCSSstructure,andthentheCSSrulestostyleyourcontent.Finally,Ishowyouhowtoapplytheserulestoyourwebsites.
WhatDoesCSSDo?CSSstylesHTMLelementswithgreatercontrolthanjustusingHTML.TakealookatFigure6-1.Ontheleft,Facebookappearsasitcurrentlyexists;ontheright,however,thesameFacebookpageisshownwithoutalltheCSSstyling.WithouttheCSS,alltheimagesandtextappearleft-justified,borders
andshadingdisappear,andtexthasminimalformatting.
Figure6-1:Left:FacebookwithCSS.Right:FacebookwithoutCSS.
CSScanstylealmostanyHTMLtagthatcreatesavisibleelementonthepage,includingalltheHTMLtagsusedtocreateheadings,paragraphs,links,images,lists,andtablesthatIshowedyouinpreviouschapters.Specifically,CSSallowsyoutostyle:
Textsize,color,style,typeface,andalignmentLinkcolorandstyleImagesizeandalignmentListbulletstylesandindentationTablesize,shading,borders,andalignment
CSSstylesandpositionstheHTMLelementsthatappearonawebpage.However,someHTMLelements(suchas,forexample,<head>)arenotvisibleonthepageandarenotstyledusingCSS.
YoumaywonderwhycreatingaseparatelanguagelikeCSStohandlestylingwasconsideredabetterapproachthanexpandingthecapabilitiesofHTML.Therearethreereasons:
History:CSSwascreatedfouryearsafterHTMLasanexperimenttoseewhetherdevelopersandconsumerswantedextrastylingeffects.Atthetime,itwasunclearwhetherCSSwouldbeuseful,andonlysomemajorbrowserssupportedit.Asaresult,CSSwascreatedseparatelyfromHTMLtoallowdeveloperstobuildsitesusingjustHTML.
Codemanagement:Initially,someCSSfunctionalityoverlappedwithexistingHTMLfunctionality.However,specifyingstylingeffectsinHTMLresultsinclutteredandmessycode.Forexample,specifyingaparticularfonttypefaceinHTMLrequiresthatyouincludethefonttypefaceattributeineveryparagraph(<p>)tag.Stylingasingleparagraphthiswayiseasy,butapplyingthefonttoaseriesofparagraphs(oranentirepageorwebsite)quicklybecomestedious.Bycontrast,CSSrequiresthetypefacetobespecifiedonlyonce,anditautomaticallyappliestoallparagraphs.Thisfeaturemakesiteasierfordeveloperstowriteandmaintaincode.Inaddition,separatingthestylingofthecontentfromtheactualcontentitselfhasallowedsearchenginesandotherautomatedwebsiteagentstomoreeasilyprocessthecontentonwebpages.Inertia:CurrentlymillionsofwebpagesuseHTMLandCSSseparately,andeverydaythatnumbergrows.CSSstartedasaseparatelanguageforreasonsstatedabove,anditremainsaseparatelanguagebecauseitspopularitycontinuestogrow.
CSSStructureCSSfollowsasetofrulestoensurethatwebsiteswillbedisplayedinthesamewaynomatterthebrowserorcomputerused.Sometimes,becauseofvaryingsupportoftheCSSstandard,browserscananddodisplaywebpagesdifferently.Nevertheless,generallyspeaking,CSSensuresthatusershaveaconsistentexperienceacrossallbrowsers.
YoucanuseanybrowsertoseeCSSyouwritestyleyourHTMLfiles,thoughIstronglyrecommendyoudownload,install,anduseChromeorFirefox.
ChoosingtheelementtostyleCSScontinuestoevolveandsupportincreasedfunctionality,butthebasicsyntaxfordefiningCSSrulesremainsthesame.CSSmodifiesHTMLelementswithrulesthatapplytoeachelement.Theserulesarewrittenasfollows:
selector{property:value;}
ACSSruleiscomprisedofthreeparts:
Selector:TheHTMLelementyouwanttostyle.Property:ThefeatureoftheHTMLelementyouwanttostyle,suchas,forexample,fonttypeface,imageheight,orcolor.Value:TheoptionsforthepropertythattheCSSrulesets.Forexample,ifcolorwastheproperty,thevaluecouldbered.
TheselectoridentifieswhichHTMLelementyouwanttostyle.InHTML,anelementissurroundedbyanglebrackets,butinCSStheselectorstandsalone.Theselectorisfollowedbyaspace,anopeningleftcurlybracket({),propertywithavalue,andthenaclosingrightcurlybracket(}).Thelinebreakaftertheopeningcurlybracket,andbeforetheclosingcurlybracketisnotrequiredbyCSS—infact,youcouldputallyourcodeononelinewithnolinebreaksorspaces.UsinglinebreaksisconventionfollowedbydeveloperstomakeCSSeasiertomodifyandread.
YoucanfindcurlybracketsonmostkeyboardstotherightofthePkey.
ThefollowingcodeshowsyouanexampleofCSSmodifyingaspecificHTMLelement.TheCSScodeappearsfirst,followedbytheHTMLcodethatitmodifies:
TheCSS:h1{font-family:cursive;}
AndnowtheHTML:<h1>LargestIPOsinUSHistory</h1><ul>
<li>2014:Alibaba-$20B</li><li>2008:Visa-$18B</li></ul>
TheCSSselectortargetsandstylestheHTMLelementwiththesamename(inthiscase,<h1>tags).Forexample,inFigure6-2,theheading“LargestIPOsinUSHistory,”createdusingtheopeningandclosing<h1>tagisstyledusingtheh1selector,andthefont-familypropertywithcursivevalue.
CSSusesacoloninsteadoftheequalssign(=)tosetvaluesagainstproperties.
ThefontinFigure6-2likelydoesnotappeartobecursive,asdefinedinthecodeabove,becausecursiveisthenameofagenericfontfamily,andnotaspecificfont.Genericfontfamiliesaredescribedlaterinthischapter.
MypropertyhasvalueCSSsyntaxrequiresthataCSSpropertyanditsvalueappearwithinopeningandclosingcurlybrackets.Aftereachpropertyisacolon,andaftereachvalueisasemi-colon.Thiscombinationofpropertyandvaluetogetheriscalledadeclaration,andagroupofpropertiesandvaluesiscalledadeclarationblock.
Figure6-2:CSStargetingtheheadingh1element.
Letuslookataspecificexamplewithmultiplepropertiesandvalues:
h1{font-size:15px;color:blue;}
Inthisexample,CSSstylestheh1element,changingthefont-sizepropertyto15px,andthecolorpropertytoblue.
Youcanimprovethereadabilityofyourcodebyputtingeachdeclaration(eachproperty/valuecombination)onitsownline.Additionally,addingspacesortabstoindentthedeclarationsalsoimprovesthereadability.Addingtheselinebreaksandindentionsdoesn’taffectbrowserperformanceinanyway,butitwillmakeiteasierforyouandotherstoreadyourcode.
HackingtheCSSonyourfavoritewebsiteInChapter2,youmodifiedanewswebsite’sHTMLcode.Inthischapter,youmodifyitsCSS.Let’stakealookatsomeCSSrulesinthewild.Inthisexample,youchangetheCSSonhuffingtonpost.com(oryournewswebsiteofchoice)usingtheChromebrowser.Justfollowthesesteps:
1. UsingaChromebrowser,navigatetoyourfavoritenewswebsite,ideallyonewithmanyheadlines.(SeeFigure6-3.)
2. Placeyourmousepointeroveraheadline,right-click,andfromthemenuthatappearsselectInspectElement.
Awindowopensatthebottomofyourbrowser.
3. ClicktheStyletabontherightsideofthiswindowtoseetheCSSrulesbeingappliedtoHTMLelements.(SeeFigure6-4.)
Figure6-3:TheHuffingtonPostwebsitebeforemodification.
4. ChangethecoloroftheheadlineusingCSS.Todothis,firstfindthecolorpropertyintheelement.stylesection;notethesquarecolorboxwithinthatpropertythatdisplaysasampleofthecurrentcolor.Clickonthisboxandchangethevaluebyselectinganewcolorfromthepop-upmenu,andthenpressEnter.
Yourheadlinenowappearsinthecoloryoupicked.(SeeFigure6-5.)
Iftheelement.stylesectionisblankandnocolorpropertyappears,youcanstilladditmanually.Todoso,clickonceintheelement.stylesection,andwhentheblinkingcursorappears,typecolor:purple.Theheadlinechangestopurple.
AswithHTML,youcanmodifyanywebsite’sCSSusingChrome’sInspectElementfeature,alsoknownasDeveloperTools.Mostmodernbrowsers,includingFirefox,Safari,andOpera,haveasimilarfeature.
Figure6-4:TheCSSrulesthatstyletheHuffingtonPostwebsite.
Figure6-5:ChangingtheCSSchangesthecoloroftheheadline.
CommonCSSTasksandSelectorsAlthoughCSSincludesover150properties,andmanyvaluesforeachproperty,onmodernwebsitesahandfulofCSSpropertiesandvaluesdothemajorityofthework.Intheprevioussection,whenyou“hacked”theCSSonalivewebsite,youchangedtheheadingcolor—acommontaskinCSS.OthercommontasksperformedwithCSSinclude:
Changingfontsize,style,fontfamily,anddecorationCustomizinglinksincludingcolor,backgroundcolor,andlinkstateAddingbackgroundimagesandformattingforegroundimages
Fontgymnastics:size,color,style,family,anddecorationCSSletsyoucontroltextinmanyHTMLelements.Themostcommontext-relatedCSSpropertiesandvaluesareshowninTable6-1.Idescribethesepropertiesandvaluesmorefullyinthesectionsthatfollow.
Table6-1CommonCSSPropertiesandValuesforStylingText
Propertyname
Possiblevalues Description
font-size
pixels(#px)
%
em(#em)
Specifiesthesizeoftextmeasuredeitherinpixels,asapercentageofthecontainingelement’sfontsize,orwithanemvaluewhichiscalculatedbydesiredpixelvaluedividedbycontainingelementfontsizeinpixels.Example:font-size:16px;
color
name
hexcode
rgbvalue
Changesthecolorofthetextspecifiedusingnames(color:blue;),hexadecimalcode(color:#0000FF;),orRGB(red,green,andblue)value(color:rgb(0,0,255);).
font-stylenormal
italicSetsfonttoappearinitalics(ornot).
font-weight
normal
boldSetsfonttoappearasbold(ornot).
font-family
fontname Setsthefonttypeface.Example:font-family:"serif";
text-decoration
none
underline
line-through
Setsfonttohaveanunderlineorstrikethrough(ornot).
Settingthefont-sizeAsinawordprocessor,youcansetthesizeofthefontyou’reusingwithCSS’sfont-sizeproperty.Youhaveafewoptionsforsettingthefontsize,andthemostcommonistousepixels,asinthefollowing:
p{font-size:16px;}
Inthisexample,Iusedthepselectortosizetheparagraphtextto16pixels.Onedisadvantageofusingpixelstosizeyourfontoccurswhenuserswhopreferalargefontsizeforreadabilityhavechangedtheirbrowsersettingstoa
defaultfontsizevaluethat’slargerthantheoneyouspecifyonyoursite.Inthesesituations,thefontsizespecifiedinthebrowsertakesprecedence,andthefontsonyoursitewillnotscaletoadjusttothesepreferences.
Percentage-sizingandemvalues,theotheroptionstosizeyourfonts,areconsideredmoreaccessibility-friendly.Thedefaultbrowserfont-sizeofnormaltextis16pixels.Withpercentage-sizingandemvalues,fontscanbesizedrelativetotheuser-specifieddefault.Forexample,theCSSforpercentage-sizinglookslikethis:
p{font-size:150%;}
Inthisexample,Iusedthepselectortosizetheparagraphtextto150%ofthedefaultsize.Ifthebrowser’sdefaultfontsizewassetat16pixels,thisparagraph’sfontwouldappearsizedat24pixels(150%of16).
Afont-sizeequalto1pxisequivalenttoonepixelonyourmonitor,sotheactualsizeofthetextdisplayedvariesaccordingtothesizeofthemonitor.Accordingly,forafixedfontsizeinpixels,thetextappearssmallerasyouincreasethescreenresolution.
SettingthecolorThecolorpropertysetsthecolorinoneofthreeways:
Name:147colorscanbereferencedbyname.Youcanreferencecommoncolors,suchasblack,blue,andred,alongwithuncommoncolors,suchasburlywood,lemonchiffon,thistle,andrebeccapurple.
RebeccaMeyer,thedaughterofprominentCSSstandardsauthorEricMeyer,passedawayin2014frombraincancerattheageofsix.Inresponse,theCSSstandardizationcommitteeapprovedaddingashadeofpurplecalledrebeccapurpletotheCSSspecificationinRebecca’shonor.AllmajorInternetbrowsershaveimplementedsupportforthecolor.
Hexcode:Colorscanbedefinedbycomponentpartsofred,green,andblue,andwhenusinghexadecimalcodeover16millioncolorscanbereferenced.Inthecodeexample,Isettheh1colorequalto#FF0000.Afterthehashtag,thefirsttwodigits(FF)referstotheredinthecolor,thenexttwodigits(00)referstothegreeninthecolor,andthefinaltwodigits(00)referstotheblueinthecolor.RGBvalue:Justlikehexcodes,RGBvaluesspecifythered,green,andbluecomponentpartsforover16millioncolors.RGBvaluesarethedecimalequivalenttohexadecimalvalues.
Don’tworryabouttryingtorememberhexcodesorRGBvalues.Youcaneasilyidentifycolorsusinganonlinecolorpickersuchastheoneatwww.w3schools.com/tags/ref_colorpicker.asp.
Thefollowingexampleshowsallthreetypesofcolorchanges:p{color:red}h1{color:#FF0000}li{color:rgb(255,0,0)}
liistheelementnameforalistiteminorderedorunorderedlists.
Allthreecolorsinthecodeexampleabovereferencethesameshadeofred.Forthefulllistofcolorsthatcanbereferencedbynameseehere:www.w3.org/TR/css3-color/#svg-color.
Settingthefont-styleandfont-weightThefont-stylepropertycansettexttoitalics,andthefont-weight
propertycansettexttobold.Foreachoftheseproperties,thedefaultisnormal,whichdoesn’tneedtobespecified.Intheexamplebelow,theparagraphisstyledsothefontappearsitalicizedandbold.Here’sanexampleofeach:
p{font-style:italics;font-weight:bold;}
Settingthefont-familyThefont-familypropertysetsthetypefaceusedfortext.Thepropertyissetequaltoonefont,ortoalistoffontsseparatedbycommas.Yourwebsitevisitorswillhaveavarietyofdifferentfontsinstalledontheircomputers,butthefont-familypropertydisplaysyourspecifiedfontonlyifthatfontisalreadyinstalledontheirsystem.
Thefont-familypropertycanbesetequaltotwotypesofvalues:
Fontname:SpecificfontnamessuchasTimesNewRoman,Arial,andCourier.Genericfontfamily:Modernbrowsersusuallydefineoneinstalledfontforeachgenericfontfamily.Thesefivegenericfontfamiliesinclude
serif(TimesNewRoman,Palantino)
sans-serif(Helvetica,Verdana)
monospace(Courier,AndaleMono)
cursive(ComicSans,Florence)
fantasy(Impact,Oldtown)
Whenusingfont-familyit’sbesttodefinetwoorthreespecificfontsfollowedbyagenericfontfamilyasafallbackincasethefontsyouspecifyaren’tinstalled,asinthefollowingexample:
p{font-family:"TimesNewRoman",Helvetica,serif;}
Inthisexample,theparagraph’sfontfamilyisdefinedasTimesNewRoman.
IfTimesNewRomanisn’tinstalledontheuser’scomputer,thebrowserthenusesHelvetica.IfHelveticaisnotinstalled,thebrowserwilluseanyavailablefontinthegenericseriffontfamily.
Whenusingafontnamewithmultiplewords(suchasTimesNewRoman)enclosethefontnameinquotes.
Settingthetext-decorationThetext-decorationpropertysetsanyfontunderliningorstrikethrough.Bydefault,thepropertyisequaltonone,whichdoesnothavetobespecified.Inthefollowingexample,anytextwithanh1headingisunderlinedwhereasanytextinsideaparagraphtagismadestrikethrough:
h1{text-decoration:underline;}p{text-decoration:line-through;}
CustomizinglinksIngeneral,browsersdisplaylinksasblueunderlinedtext.Originally,thisdefaultbehaviorminimizedtheconfusionbetweencontentonthepageandaninteractivelink.Today,almosteverywebsitestyleslinksinitsownway.Somewebsitesdon’tunderlinelinks;othersretaintheunderliningbutstylelinksincolorsotherthanblue,andsoon.
TheHTMLanchorelement(a)isusedtocreatelinks.Thetextbetweentheopeningandclosinganchortagisthelinkdescription,andtheURLsetinthehrefattributeistheaddressthebrowservisitswhenthelinkisclicked.
Theanchortaghasevolvedovertimeandtodayhasfourstates:
link:Alinkthatauserhasnotclickedorvisited.
visited:Alinkthatauserhasclickedorvisited.
hover:Alinkthattheuserhoversthemousecursoroverwithoutclicking.active:Alinktheuserhasbeguntoclickbuthasn’tyetreleasedthemousebutton.
CSScanstyleeachofthesefourstates,mostoftenbyusingthepropertiesandvaluesshowninTable6-2.
Table6-2CommonCSSPropertiesandValuesforStylingLinks
Propertyname
Possiblevalues Description
color
name
hexcode
rgbvalue
Linkcolorspecifiedusingnames(color:blue;),hexadecimalcode(color:#0000FF;),orRGBvalue(color:rgb(0,0,255);).
text-decoration
none
underlineSetslinktohaveanunderline(ornot).
Thefollowingexamplestyleslinksinawaythat’ssimilartothewaythey’restyledinarticlesatWikipedia,wherelinksappearbluebydefault,underlinedonmousehover,andorangewhenactive.AsshowninFigure6-6,thefirstlinktoChiefTechnologyOfficeroftheUnitedStatesappearsunderlinedasitwouldifmymousewashoveringoverit.Also,thelinktoGoogleappearsorangeasitwouldifactiveandmymousewasclickingit.
a:link{color:rgb(6,69,173);text-decoration:none;}a:visited{color:rgb(11,0,128)}a:hover{text-decoration:underline}a:active{color:rgb(250,167,0)}
Remembertoincludethecolonbetweentheaselectorandthelinkstate.
Althoughexplainingwhyisoutofthescopeofthisbook,CSSspecificationsinsistthatyoudefinethevariouslinkstatesintheordershownhere—link,visited,hover,andthenactive.However,itisacceptabletonotdefinealinkstate,aslongasthisorderispreserved.
Thevariouslinkstatesareknownaspseudo-classselectors.Pseudo-classselectorsaddakeywordtoCSSselectorsandallowyoutostyleaspecialstateoftheselectedelement.
Figure6-6:Wikipedia.orgpageshowinglink,visited,hover,andactivestates.
AddingbackgroundimagesandstylingforegroundimagesYoucanuseCSStoaddbackgroundimagesbehindHTMLelements.Mostcommonly,thebackground-imagepropertyisusedtoaddbackgroundimagestoindividualHTMLelementssuchasdiv,table,andp,or(when
appliedtothebodyelement)toentirewebpages.
Backgroundimageswithsmallerfilesizesloadmorequicklythanlargerimages.Thisisespeciallyimportantifyourvisitorscommonlybrowseyourwebsiteusingamobilephone,whichtypicallyhasaslowerdataconnection.
ThepropertiesandvaluesinTable6-3showtheoptionsforaddingbackgroundimages.
Table6-3CSSPropertiesandValuesforBackgroundImages
Propertyname Possiblevalues Description
background-image
url("URL") AddsabackgroundimagefromtheimagelinkspecifiedatURL.
background-size
auto
contain
cover
widthheight(#px,%)
Setsbackgroundsizeaccordingtothevalue:auto(defaultvalue)displaystheimageasoriginallysized.containscalestheimage’swidthandheightsothatitfitsinsideelement.coverscalestheimagesoelementbackgroundisnotvisible.Backgroundsizecanalsobesetbyspecifyingwidthandheightinpixelsorasapercentage.
background-position
keywordsposition(#px,%)
Positionsthebackgroundinelementusingkeywordsorexactposition.Keywordsarecomprisedofhorizontalkeywords(left,right,center),andverticalkeywords(top,center,andbottom).Theplacementofthebackgroundcanalsobeexactlydefinedusingpixelsorapercentagetodescribethehorizontalandverticalpositionrelativetotheelement.
background-repeat
repeat
repeat-x
repeat-y
no-repeat
Setsthebackgroundimagetotile,orrepeat,asfollows:horizontally(repeat-x)vertically(repeat-y)horizontallyandvertically(repeat)don’trepeatatall(no-repeat).
background-attachment
scroll
fixedSetsthebackgroundtoscrollwithothercontent(scroll),ortoremainfixed(fixed).
Settingthebackground-imageAsshowninthefollowingexample,thebackground-imagepropertycansetthebackgroundimagefortheentirewebpageoraspecificelement.
body{
background-image:url("http://upload.wikimedia.org/wikipedia/commons/e/e5/Chrysler_Building_Midtown_Manhattan_New_York_City_1932.jpg");}
Youcanfindbackgroundimagesatsitessuchasimages.google.com,www.flickr.com,orpublicdomainarchive.com.
Checkimagecopyrightinformationtoseeifyouhavepermissiontousetheimage,andcomplywithimage’slicensingterms,whichcanincludeattributingoridentifyingtheauthor.Additionally,directlylinkingtoimagesonotherserversiscalledhotlinking.Itispreferabletodownloadtheimage,andhostandlinktotheimageonyourownserver.
Ifyou’dpreferasingle-colorbackgroundinsteadofanimage,usethebackground-colorproperty.Thispropertyisdefinedinmuchthesamewayasthebackground-imageproperty.Justsetitequaltoacolorname,RGBvalue,orhexcode,asIdescribeearlierinthischapterinthesection“Settingthecolor.”
Settingthebackground-sizeByspecifyingexactdimensionsusingpixelsorpercentages,thebackground-sizepropertycanscalebackgroundimagestobesmallerorlarger,asneeded.Inaddition,thispropertyhasthreedimensionscommonlyusedonwebpages,asfollows(seeFigure6-7):
auto:Thisvaluemaintainstheoriginaldimensionsofanimage.
cover:ThisvaluescalesanimagesoalldimensionsaregreaterthanorequaltothesizeofthecontainerorHTMLelement.contain:ThisvaluescalesanimagesoalldimensionsarelessthanorequaltothesizeofthecontainerorHTMLelement.
Figure6-7:Settingthebackgroundsizetothreedifferentvalues.
Settingthebackground-positionThebackground-positionsetstheinitialpositionofthebackgroundimage.Thedefaultinitialpositionisinthetopleftcornerofthewebpageorspecificelement.Youchangethedefaultpositionbyspecifyingapairofkeywordorpositionvalues,asfollows:
Keywords:Thefirstkeyword(left,center,orright)representsthehorizontalposition,andthesecondkeyword(top,center,orbottom)representstheverticalposition.
Position:Thefirstpositionvaluerepresentsthehorizontalposition,andthesecondvaluerepresentsthevertical.Eachvalueisdefinedusingpixelsorpercentages,representingthedistancefromthetop-leftofthebrowserorthespecifiedelement.Forexample,background-position:centercenterisequaltobackground-position:50%50%.(SeeFigure6-8.)
Settingthebackground-repeatThebackground-repeatpropertysetsthedirectionthebackgroundwilltileasfollows:
repeat:Thisvalue(thedefault)repeatsthebackgroundimagebothhorizontallyandvertically.repeat-x:Thisvaluerepeatsthebackgroundimageonlyhorizontally.
repeat-y:Thisrepeatsthebackgroundimageonlyvertically.
no-repeat:Thisvaluepreventsthebackgroundfromrepeatingatall.
Figure6-8:Theinitialbackgroundimagepositionsspecifiedusingkeywordsorposition.
Settingthebackground-attachmentThebackground-attachmentpropertysetsthebackgroundimagetomove(ornot)whentheuserscrollsthroughcontentonthepage.Thepropertycanbesetto:
scroll:Thebackgroundimagemoveswhentheuserscrolls.
fixed:Thebackgroundimagedoesnotmovewhentheuserscrolls.
Thefollowingcodesegmentusesseveralofthepropertiesdiscussedearliertoaddabackgroundimagethatstretchesacrosstheentirewebpage,isalignedinthecenter,doesnotrepeat,anddoesnotmovewhentheuserscrolls.(SeeFigure6-9.)
body{background-image:url("http://upload.wikimedia.org/wikipedia/commons/thumb/a/a0/USMC-090807-M-8097K-022.jpg/640px-USMC-090807-M-8097K-022.jpg");background-size:cover;background-position:centercenter;background-repeat:no-repeat;background-attachment:fixed;
}
Figure6-9:Animagesetasthebackgroundforentirepage.
StylingMePrettyTheCSSrulesdiscussedinthischaptergiveyouatasteofafewcommonstylingpropertiesandvalues.Althoughyouaren’tlikelytoremembereverypropertyandvalue,withpracticethepropertyandvaluenameswillcometoyounaturally.Afteryouunderstandthebasicsyntax,thenextstepistoactuallyincorporateCSSintoyourwebpageandtryyourhandatstylingHTMLelements.
AddingCSStoyourHTMLTherearethreewaystoapplyCSStoawebsitetostyleHTMLelements:
In-lineCSS:CSScanbespecifiedwithinanHTMLfileonthesamelineastheHTMLelementitstyles.ThismethodrequiresplacingthestyleattributeinsidetheopeningHTMLtag.Generally,in-lineCSSistheleastpreferredwayofstylingawebsitebecausethestylingrulesarefrequentlyrepeated.Here’sanexampleofin-lineCSS:
<!DOCTYPEhtml><html><head><title>RecordIPOs</title></head><body><h1style="color:red;">AlibabaIPOexpectedtobe
biggestIPOofalltime</h1></body></html>
EmbeddedCSS:Withthisapproach,CSSappearswithintheHTMLfile,butseparatedfromtheHTMLtagsitmodifies.TheCSScodeappearswithintheHTMLfilebetweenanopeningandclosing<style>tag,whichitselfislocatedbetweenanopeningandclosing<head>tag.EmbeddedCSSisusuallyusedwhenstylingasingleHTMLpagedifferentlythantherestofyourwebsite.
Inthisexample,theembeddedCSSstylestheheaderred,justlikethein-lineCSSdoesabove.
<!DOCTYPEhtml><html><head><title>RecordIPOs</title><styletype="text/css">h1{color:red;}</style></head><body><h1>AlibabaIPOexpectedtobebiggestIPOofalltime</h1></body></html>
Separatestylesheets:CSScanbespecifiedinaseparatestylesheet—thatis,inaseparatefile.UsingaseparatestylesheetisthepreferredapproachtostoringyourCSSbecauseitmakesmaintainingtheHTMLfileeasierandallowsyoutoquicklymakechanges.IntheHTMLfile,the<link>tagisusedtorefertotheseparatestylesheet,andhasthreeattributes:
href:SpecifiestheCSSfilename.
rel:Shouldbesetequalto"stylesheet".
type:Shouldbesetequalto"text/css".
WiththreedifferentwaysofstylingHTMLelementswithCSS,allthreewayscouldbeusedwithcontradictorystyles.Forexample,sayyourin-lineCSSstylesh1elementsasred,whereasembeddedCSSstylesthemasblue,andaseparatestylesheetstylesthemasgreen.Toresolvetheseconflicts,in-lineCSShasthehighestpriorityandoverridesanyotherCSSrules.Ifnoin-lineCSSisspecified,thenembeddedCSShasthenexthighestpriority,andfinallyintheabsenceofin-lineorembeddedCSS,thestylesinaseparatestylesheetareused.Intheexample,withthepresenceofallthreestyles,theh1elementtextwouldappearredbecausein-lineCSShasthehighestpriorityandoverridestheembeddedCSSbluestyling,andtheseparateCSSgreenstyling.
ThefollowingexampleusesaseparateCSSstylesheettostyletheheaderred,asintheprevioustwoexamples:
CSS:style.cssh1{color:red;}
HTML:index.html<DOCTYPEhtml><html><head><title>RecordIPOs</title><linkhref="style.css"text="text/css"rel="stylesheet"></head><body><h1>AlibabaIPOexpectedtobebiggestIPOofalltime</h1></body></html>
BuildingyourfirstwebpagePracticeyourHTMLonlineusingtheCodecademywebsite.Codecademyisafreewebsitecreatedin2011toallowanyonetolearnhowtocoderightinthebrowser,withoutinstallingordownloadinganysoftware.Youcanpracticeallofthetags(andafewmore)discussedinthischapterbyfollowingthese
steps:
1. Openyourbrowser,gotowww.dummies.com/go/codingfd,andclickontheCodecademylink.
2. SignintoyourCodecademyaccount.
SigningupisdiscussedinChapter3.Creatinganaccountallowsyoutosaveyourprogressasyouwork,butit’soptional.
3. NavigatetoandclickonGetStartedwithHTML.4. Backgroundinformationispresentedintheupperleftportionofthe
site,andinstructionsarepresentedinthelowerleftportionofthesite.
5. Completetheinstructionsinthemaincodingwindow.Asyoutype,alivepreviewofyourcodeisgenerated.
6. Afteryouhavefinishedcompletingtheinstructions,clicktheSaveandSubmitCodebutton.
Ifyouhavefollowedtheinstructionscorrectly,agreencheckmarkappears,andyouproceedtothenextexercise.Ifanerrorexistsinyourcodeawarningappearswithasuggestedfix.Ifyourunintoaproblem,orhaveabugyoucannotfix,clickonthehint,usetheQ&AForums,ortweetmeat@nikhilgabrahamandincludehashtag#codingFD.
Chapter7NextStepswithCSS
InThisChapterFormattinglistsandtablesStylingwebpagesusingparentandchildselectorsNamingpiecesofcodeusingidandclass
UsingtheboxmodeltopositionHTMLelementsonthepage
Designisnotjustwhatitlookslikeandfeelslike.Designishowitworks.
—SteveJobsInthischapter,youcontinuebuildingontheCSSyoulearnedinthepreviouschapter.Sofar,theCSSrulesyou’veseenappliedtotheentirewebpage,butnowtheygetmorespecific.YoulearnhowtostyleseveralmoreHTMLelements,includinglists,tables,andforms,andhowtoselectandstylespecificpartsofawebpage,suchasthefirstparagraphinastoryorthelastrowofatable.Finally,youlearnhowprofessionalwebdevelopersuseCSSandtheboxmodeltocontroldowntothepixelthepositioningofelementsonthepage.UnderstandingtheboxmodelisnotnecessarytobuildourappinChapter10.
Beforedivingin,rememberthebigpicture:HTMLputscontentonthewebpage,andCSSfurtherstylesandpositionsthatcontent.Insteadoftryingtomemorizeeveryrule,usethischaptertounderstandCSSbasics.CSSselectorshavepropertiesandvaluesthatmodifyHTMLelements.Thereisnobetterwaytolearnthanbydoing,sofeelfreetoskipaheadtotheCodecademypracticelessonsattheendofthechapter.Then,usethischapterasareferencewhenyouhavequestionsaboutspecificelementsyouaretryingtostyle.
Styling(More)ElementsonYourPage
Inthissection,youdiscovercommonwaystostylelistsandtables.Inthepreviouschapter,theCSSpropertiesandrulesyoulearnedlikecolorandfont-familycanapplytoanyHTMLelementcontainingtext.Bycontrast,someoftheCSSshownhereisusedonlytostylelists,tables,andforms.
StylinglistsInChapter5youlearnedhowtocreateorderedlists,whichstartwithmarkerslikelettersornumbers,andunorderedlists,whichstartwithmarkerslikebulletpoints.Bydefault,listitemsinanorderedlistusenumbers(forexample,1,2,3),whereaslistitemsinunorderedlistsuseasolid-black-circle( ).
Thesedefaultsmaynotbeappropriateforallcircumstances.Infact,thetwomostcommontaskswhenstylingalistinclude:
Changingthemarkerusedtocreatealist:Forunorderedlists,likethisone,youcanuseasoliddisc,emptycircle,orsquarebulletpoint.Fororderedlists,youcanusenumbers,romannumerals(upperorlowercase),orcaseletters(upperorlower).Specifyinganimagetouseasthebulletpoint:Youcancreateyourownmarkerfororderedandunorderedlistsinsteadofusingthedefaultoption.Forexample,ifyoucreatedanunorderedbulletedlistforaburgerrestaurant,insteadofusingasolidcircleasabulletpointyoucoulduseacolorhamburgericonimage.
YoucanaccomplisheitherofthesetasksbyusingthepropertiesinTable7-1withanolorulselectortomodifythelisttype.
CSSselectorsusingpropertiesandrulesmodifyHTMLelementsbythesamename.Forexample,Figure7-1hasHTML<ul>tagsthatarereferredtoinCSSwiththeulselector,andstyledusingthepropertiesandrulesinTable7-1.
Table7-1CommonCSSPropertiesandValuesforStylingLists
Property Possible Description
Name Values
list-style-type
(unorderedlist)
disc
circle
square
none
Setsthemarkersusedtocreatelistitemsinanunorderedlisttodisc(⦁),circle(),square(◾ ),ornone.
list-style-type
(orderedlist)
decimal
upper-roman
lower-roman
upper-alpha
lower-alpha
Setsthemarkersusedtocreatelistitemsinanorderedlisttodecimal(1,2,3),uppercaseromannumerals(I,II,III),lowercaseromannumerals(i,ii,iii),uppercaseletters(A,B,C),orlowercaseletters(a,b,c).
list-style-image
url(“URL”) WhenURLisreplacedwiththeimagelinksetsanimageasthemarkerusedtocreatealistitem.
Manytextwebsitenavigationbarsarecreatedusingunorderedbulletedlistswiththemarkersettonone.YoucanseeanexampleintheCodecademyCSSPositioningcoursestartingwithexercise21.
CSSpropertiesandvaluesapplytoaCSSselectorandmodifyanHTMLelement.Inthefollowingexample,embeddedCSS(betweentheopeningandclosing<style>tags)andin-lineCSS(definedwiththestyleattributeintheHTML)isusedto:
Changethemarkerinanunorderedlisttoasquareusinglist-style-type
Changethemarkerinanorderedlisttouppercaseromannumeralsagainusinglist-style-type
Setacustommarkertoaniconusinglist-style-image
ThecodeforthisisshownbelowandinFigure7-1.Figure7-2showsthiscoderenderedinthebrowser.
<html><head><title>Figure7-1:Lists</title>
<style>ul{list-style-type:square;}
ol{list-style-type:upper-roman;}
li{font-size:27px;}</style></head><body>
<h1>Ridesharingstartups</h1><ul><li>Hailo:bookataxionyourphone</li><li>Lyft:requestapeertopeerride</li><listyle="list-style-image:url('car.png');">Uber:hireadriver</li></ul>
<h1>Foodstartups</h1><ol><li>Grubhub:ordertakeoutfoodonline</li><listyle="list-style-image:url('burger.png');">BlueApron:subscribetoweeklymealdelivery</li><li>Instacart:requestgroceriesdeliveredthesameday</li></ol></body></html>
Figure7-1:Embeddedandin-lineCSS.
Ifthecustomimageforyourmarkerislargerthanthetext,yourtextmaynotalignverticallywiththemarker.Tofixthis,youcaneitherincreasethefontsizeofeachlistitemusingfont-size,asshownintheexample,increasethemarginbetweeneachlistitemusingmargin,orsetlist-style-typetononeandsetabackgroundimageontheulelementusingbackground-image.
TherearethreewaystoapplyCSS—inlineCSSusingthestyleattribute,embeddedCSSusinganopeningandclosing<style>tag,andinaseparateCSSstylesheet.
Figure7-2:Orderedandunorderedlistsmodifiedtochangethemarkertype.
Designingtables
InChapter5,youfoundouthowtocreatebasictables.Bydefault,thewidthofthesetablesexpandstofitcontentinsidethetable,contentinindividualcellsisleftaligned,andnobordersaredisplayed.
Thesedefaultsmaynotbeappropriateforallcircumstances.Deprecated(unsupported)HTMLattributescanmodifythesedefaults,butatanytimebrowserscouldstoprecognizingtheseattributes,andanytablescreatedwiththeseattributeswoulddisplayincorrectly.Asasaferalternative,CSScanstyletableswithgreatercontrol.ThreecommontasksCSScanperformfortablesincludethefollowing:
Settingthewidthofatable,tablerow,orindividualtablecellwiththewidthproperty.
Aligningtextwithinthetablewiththetext-alignproperty.
Displayingborderswithinthetablewiththeborderproperty.(SeeTable7-2.)
Table7-2CommonCSSPropertiesandValuesforStylingTables
PropertyName
PossibleValues Description
widthpixels(#px)%
Widthoftablemeasuredeitherinpixelson-screenorasapercentageofthebrowserwindoworcontainertag.
text-align
left
right
center
justify
Positionoftextrelativetothetableaccordingtothevalueoftheattribute.Forexample,text-align=“center”positionsthetextinthecenterofthetablecell.
border
width
style
color
Definesthreepropertiesinone—border-width,border-style,andborder-color.Thevaluesmustbespecifiedinthisorder:Width(pixel),style(none,dotted,dashed,solid),andcolor(name,hexadecimalcode,RBGvalue).Forexample,border:1pxsolidred.
Inthefollowingexample,thetableiswiderthanthetextinanycell,thetextineachcelliscentered,andthetableborderisappliedtoheadercells:
<html><head><title>Figure7-2:Tables</title><style>table{
width:700px;}
table,td{text-align:center;border:1pxsolidblack;border-collapse:collapse;}
</style></head><body><table><caption>Desktopbrowsermarketshare(August2014)</caption><tr><th>Source</th><th>Chrome</th><th>IE</th><th>Firefox</th><th>Safari</th><th>Other</th></tr><tr><td>StatCounter</td><td>50%</td><td>22%</td><td>19%</td><td>5%</td><td>4%</td></tr><tr><td>W3Counter</td><td>38%</td><td>21%</td><td>16%</td><td>16%</td><td>9%</td></tr></table></body></html>
TheHTMLtag<caption>andtheCSSpropertyborder-collapsefurtherstylethetablebelow.The<caption>tagaddsatitletothetable.Althoughyoucancreateasimilareffectusingthe<h1>tag,<caption>associatesthetitlewiththetable.TheCSSborder-collapsepropertycanhaveavalueofseparateorcollapse.Theseparatevaluerenderseachborderseparately(refertoFigure5-9),whereascollapsedrawsasingleborderwhenpossible(seeFigure7-3).
Figure7-3:Tablewithwidth,textalignment,andbordermodifiedusingCSS.
SelectingElementstoStyleCurrently,theCSSyouhaveseenstyleseveryHTMLelementthatmatchestheCSSselector.Forexample,inFigure7-3thetableandtdselectorshaveatext-alignpropertythatcenteredtextineverytablecell.Dependingonthecontent,youmaywanttoonlycentertextintheheaderrow,butleft-aligntextinsubsequentrows.Twowaystoaccomplishthisinclude:
StylingspecificHTMLelementsbasedonpositiontootherelements.NamingHTMLelements,andonlystylingelementsbyname.
StylingspecificelementsWhenstylingspecificelements,itishelpfultovisualizetheHTMLcodeasafamilytreewithparents,children,andsiblings.Inthefollowingcodeexample(alsoshowninFigure7-4),thetreestartswiththehtmlelement,whichhastwochildrenheadandbody.Theheadhasachildelementcalledtitle.Thebodyhash1,ul,andpelementsaschildren.Finally,
theulelementhaslielementsaschildren,andthepelementhasaelementsaschildren.Figure7-5showshowthefollowingcodeappearsinthebrowser,andFigure7-6showsadepictionofthefollowingcodeusingthetreemetaphor.NotethatFigure7-6showseachrelationshiponce.Forexample,inthecodebelowthereisanaelementinsideeachofthreelielements,andFigure7-6showsthisulliarelationshiponce.
<html><head><title>Figure7-3:DOM</title></head><body>
<h1>ParodyTechTwitterAccounts</h1><ul><li><ahref="http://twitter.com/BoredElonMusk">BoredElonMusk</a></li><li><ahref="http://twitter.com/VinodColeslaw">VinodColeslaw</a></li><li><ahref="http://twitter.com/Horse_ebooks">horseebooks</a></li></ul>
<h1>ParodyNon-TechTwitterAccounts</h1><p><ahref="http://twitter.com/SeinfeldToday">ModernSeinfeld</a></p><p><ahref="http://twitter.com/Lord_Voldemort7">Lord_Voldemort7</a></p>
</body></html>
BoredElonMuskisaparodyofElonMusk,thefounderofPayPal,Tesla,andSpaceX.VinodColeslawisaparodyofVinodKhosla,the
SunMicrosystemsco-founderandventurecapitalist.HorseebooksisaspambotthatbecameanInternetphenomenon.
Figure7-4:Stylingafamilytreeofelements.
Figure7-5:ParodyTechandNon-TechTwitteraccounts(browserview).
Figure7-6:ParodyTechandNon-TechTwitteraccount(HTMLtreeorDocumentObjectModelview).
TheHTMLtreeiscalledtheDOMordocumentobjectmodel.
Childselector
TheParodyNon-TechTwitteraccountanchortagsareimmediatechildrenoftheparagraphtags.IfyouwantedtostylejusttheParodyNon-TechTwitteraccounts,youcanusethechildselector,whichselectstheimmediatechildrenofaspecifiedelement.Achildselectoriscreatedbyfirstlistingtheparentselector,thenagreater-thansign(>),andfinallythechildselector.
Inthefollowingexample,theanchortagsthatareimmediatechildrenoftheparagraphtagsareselected,andthosehyperlinksarestyledwitharedfontcolorandwithoutanyunderline.TheParodyTechTwitteraccountsarenotstyledbecausetheyaredirectchildrenofthelistitemtag.(SeeFigure7-7.)
p>a{color:red;text-decoration:none;}
Figure7-7:ChildselectorusedtostyletheParodyNon-TechTwitteraccounts.
Ifyouusejusttheaselectorhere,allthelinksonthepagewouldbestyledinsteadofjustaselection.
DescendantselectorTheParodyTechTwitteraccountanchortagsaredescendants,orlocatedwithin,theunorderedlist.IfyouwantedtostylejusttheParodyTechTwitteraccounts,youcanusethedescendantselector,whichselectsnotjustimmediatechildrenofaspecifiedelementbutallelementsnestedwithinthespecifiedelement.Adescendantselectoriscreatedbyfirstlistingtheparentselector,aspace,andfinallythedescendantselectoryouwanttotarget.
Inthefollowingexample,asshowninFigure7-8,theanchortagswhicharedescendantsoftheunorderedlistareselected,andthosehyperlinksarestyledwithabluefontcolorandarecrossedout.TheParodyNon-TechTwitteraccountsarenotstyledbecausetheyarenotdescendantsofanunorderedlist.
ula{color:blue;text-decoration:line-through;}
Figure7-8:ChildselectorusedtostyletheParodyTechTwitteraccounts.
Interestedinstylingjustthefirstanchortagwithinalist,liketheModernSeinfeldTwitteraccount,orthesecondlistitem,liketheVinodColeslawTwitteraccount?Gotow3schools.comandreadmoreaboutthefirst-child(www.w3schools.com/cssref/sel_firstchild.asp),andnth-childselectors(www.w3schools.com/cssref/sel_nth-child.asp).
NamingHTMLelementsTheotherwayofstylingspecificelementsinCSSistonameyourHTMLelements.Younameyourcodebyusingeithertheidorclassattribute,andthenstyleyourcodebyreferringtotheidorclassselector.
NamingyourcodeusingtheidattributeUsetheidattributetostyleonespecificelementonyourwebpage.Theid
attributecannameanyHTMLelement,andisalwaysplacedintheopeningHTMLtag.Additionally,eachelementcanhaveonlyoneidattributevalue,andtheattributevaluemustappearonlyoncewithintheHTMLfile.AfteryoudefinetheattributeintheHTMLfile,yourefertotheHTMLelementinyourCSSbywritingahashtag(#)followedbytheattributevalue.Usingtheidattribute,thefollowingcodestylestheModernSeinfeldTwitterlinkthecolorredwithayellowbackground:
HTML:<p><ahref="http://twitter.com/SeinfeldToday"id="jerry">ModernSeinfeld</a></p>
CSS:#jerry{color:red;background-color:yellow;}
NamingyourcodeusingtheclassattributeUsetheclassattributetostylemultipleelementsonyourwebpage.TheclassattributecannameanyHTMLelement,andisalwaysplacedintheopeningHTMLtag.TheattributevalueneednotbeuniquewithintheHTMLfile.AfteryoudefinetheattributeintheHTMLfile,yourefertotheHTMLelementbywritingaperiod(.)followedbytheattributevalue.Usingtheclassattribute,thefollowingcodestylesalltheParodyTechTwitteraccountlinksthecolorredwithnounderline:
HTML:<ul><li><ahref="http://twitter.com/BoredElonMusk"class="tech">BoredElonMusk</a></li><li><ahref="http://twitter.com/VinodColeslaw"class="tech">VinodColeslaw</a></li><li><ahref="http://twitter.com/Horse_ebooks"
class="tech">Horseebooks</a></li></ul>
CSS:.tech{color:red;text-decoration:none;}
Proactivelyuseasearchengine,suchasGoogle,tosearchforadditionalCSSeffects.Forexample,ifyouwantedtoincreasethespacingbetweeneachlistitem,openyourbrowserandsearchforlistitemlinespacingcss.Linksappearinginthetoptenresultsshouldinclude:
www.w3schools.com:Abeginnertutorialsite.
www.stackoverflow.com:Adiscussionboardforexperienceddevelopers.www.mozilla.org:AreferenceguideinitiallycreatedbythefoundationthatmaintainstheFirefoxbrowser,andnowmaintainedbyacommunityofdevelopers.
Eachofthesesitesisagoodfirstplacetostart,andyoushouldlookforanswersthatincludeexamplecode.
AligningandLayingOutYourElements
CSSnotonlyallowscontrolovertheformattingofHTMLelements,italsoallowscontrolovertheplacementoftheseelementsonthepage,knownaspagelayout.Historically,developersusedHTMLtablestocreatepagelayouts.HTMLtablepagelayoutsweretedioustocreate,andrequiredthatdeveloperswriteagreatdealofcodetoensureconsistencyacrossbrowsers.CSSeliminatedtheneedtousetablestocreatelayouts,helpedreducecode
bloat,andincreasedcontrolofpagelayouts.
OrganizingdataonthepageBeforedivingintoanycode,let’sreviewinFigure7-9someofthebasicwayswecanstructurethepageandthecontentonit.Layoutshaveevolvedovertime,withsomelayoutsworkingwellondesktopcomputersbutnotdisplayingoptimallyontabletormobiledevices.
Alwaysaskyourselfhowyourintendedlayoutwillappearondesktop,tablet,andmobiledevices.
Hundredsofdifferentlayoutsexist,andafewselectedpagelayoutsappearherealongwithexamplewebsites:
Leftandrightnavigationtoolbarsarenotusuallyseenonmobiledevices.Topnavigationtoolbarsareusedbothondesktopandmobiledevices,andbottomnavigationtoolbarsaremostcommononmobiledevices.
Figure7-9:Verticalandhorizontalnavigationlayouts.
TheexamplesinFigure7-10showrealwebsiteswiththeselayouts:
Figure7-10:Useofleftandrightnavigationtoolbaronw3schools.com(left)andhunterwalk.com(right).
Verticalnavigationaidsreaderunderstandingwhenhierarchyorrelationshipexistsbetweennavigationaltopics.Inthew3schools.comexample,HTML,JavaScript,ServerSide,andXMLrelatetooneanother,andunderneatheachtopicheadingarerelatedsub-topics.
Horizontalormenunavigation,asshowninFigure7-11,helpsreadernavigationwithweakordisparaterelationshipsbetweennavigationaltopics.IntheeBayexample,theMotors,Fashion,andElectronicsmenuitemshavedifferentproductsandappealtodifferentaudiences.
Figure7-11:Useoftopandbottomnavigationtoolbaronebay.com(left)andmoma.org(right).
Don’tspendtoomuchtimeworryingaboutwhatlayouttopick.Youcanalwayspickone,observewhetheryourvisitorscannavigateyourwebsitequicklyandeasily,andchangethelayoutifnecessary.
ShapingthedivThepagelayoutsabovearecollectionsofelementsgroupedtogether.Theseelementsaregroupedtogetherusingrectangularcontainerscreatedwithanopeningandclosing<div>tag,andallofthelayoutsabovecanbecreatedwiththese<div>tags.Byitself,the<div>tagdoesnotrenderanythingonthescreen,butinsteadservesasacontainerforcontentofanytypelikeHTMLheadings,lists,tables,orimages.Toseethe<div>taginaction,takealookattheCodecademy.comhomepageinFigure7-12.
Noticehowthepagecanbedividedintothreeparts—thenavigationheader,themiddlevideotestimonial,andthenadditionaltextusertestimonials.<div>tagsareusedtooutlinethesemajorcontentareas,andadditionalnested<div>tagswithineachpartareusedtogroupcontentlikeimagesandtext.
Figure7-12:Codecademy.comhomepagewithvisiblebordersforthe<div>tags.
Inthefollowingexample,asshowninFigure7-13,HTMLcodeisusedtocreatetwocontainersusing<div>tags,theidattributenameseachdiv,andCSSsizesandcolorsthediv:
HTML:<divid="first"></div><divid="second"></div>
CSS:div{height:100px;width:100px;border:2pxsolidpurple;}
#first{background-color:red;}
#second{background-color:blue;}
Figure7-13:TwoboxescreatedwithHTML<div>tagandstyledusingCSS.
UnderstandingtheboxmodelJustaswecreatedboxeswiththe<div>tagsabove,CSScreatesaboxaroundeachandeverysingleelementonthepage,eventext.Figure7-14showstheboxmodelforanimagethatsays“Thisisanelement.”Theseboxesmaynotalwaysbevisible,butarecomprisedoffourparts:
content:HTMLtagthatisrenderedinthebrowser
padding:Optionalspacingbetweencontentandtheborder
border:Markstheedgeofthepadding,andvariesinwidthandvisibilitymargin:Transparentoptionalspacingsurroundingtheborder
Figure7-14:Boxmodelforimgelement.
UsingtheChromebrowser,navigatetoyourfavoritenewswebsite,thenright-clickanimageandinthecontextmenuchooseInspectElement.Ontherightsideofthescreenyouseethreetabs;clicktheComputedtab.Theboxmodelisdisplayedfortheimageyouright-clicked,showingthecontentdimensions,andthendimensionsforthepadding,border,andmargin.
Thepadding,border,andmarginareCSSproperties,andthevalueisusuallyexpressedinpixels.Inthefollowingcode,showninFigure7-15,paddingandmarginsareaddedtoseparateeachdiv.
div{height:100px;width:100px;border:1pxsolidblack;padding:10px;margin:10px;}
PositioningtheboxesNowthatyouunderstandhowtogroupelementsusingHTML,andhowCSSviewselements,thefinalpieceistopositiontheseelementsonthepage.Varioustechniquescanbeusedforpagelayouts,andacomprehensive
overviewofeachtechniqueisoutofthescopeofthisbook.However,onetechniquetocreatethelayoutsshowninFigure7-16istousethefloatandclearproperties(asdescribedinTable7-3).
Figure7-15:Paddingandmarginaddedtoseparateeachdiv.
Table7-3SelectCSSPropertiesandValuesforPageLayouts
PropertyName
PossibleValues Description
float
left
right
none
Sendsanelementtotheleftorrightofthecontaineritisin.Thenonevaluespecifiestheelementshouldnotfloat.
clear
left
right
both
none
Specifieswhichsideofanelementtonothaveotherfloatingelements.
Ifthewidthofanelementisspecified,thefloatpropertyallowselementsthatwouldnormallyappearonseparatelinestoappearnexttoeachother,suchasnavigationtoolbarsandamaincontentwindow.Theclearpropertyisusedtopreventanyotherelementsfromfloatingononeorbothsidesofcurrentelement,andthepropertyiscommonlysettobothtoplacewebpagefootersbelowotherelements.
Thefollowingexamplecodeuses<div>tags,float,andcleartocreateasimpleleftnavigationlayout.(SeeFigure7-16.)Typically,aftergroupingyourcontentusing<div>tags,younameeach<div>tagusingclassoridattributes,andthenstylethedivinCSS.Thereisalotofcodebelow,solet’sbreakitdownintopieces:
TheCSSisembeddedbetweentheopeningandclosing<style>tag,andtheHTMLisbetweentheopeningandclosing<body>tags.
Betweentheopeningandclosing<body>tag,using<div>tags,thepageisdividedintofourpartswithheader,navigationbar,content,andfooter.Thenavigationmenuiscreatedwithanunorderedlist,whichisleft-aligned,withnomarker.CSSstylessize,color,andaligneach<div>tag.
CSSproperties,float,andclear,areusedtoplacetheleftnavigationlayouttotheleft,andthefooterbelowtheotherelements.
<!DOCTYPEhtml><html><head><title>Figure7-14:Layout</title><style>#header{background-color:#FF8C8C;border:1pxsolidblack;padding:5px;margin:5px;text-align:center;}
#navbar{background-color:#00E0FF;height:200px;width:100px;float:left;border:1pxsolidblack;padding:5px;margin:5px;text-align:left;
}
#content{background-color:#EEEEEE;height:200px;width:412px;float:left;border:1pxsolidblack;padding:5px;margin:5px;text-align:center;}
#footer{background-color:#FFBD47;clear:both;text-align:center;border:1pxsolidblack;padding:5px;margin:5px;}
ul{list-style-type:none;line-height:25px;padding:0px;}
</style></head><body><divid="header"><h1>Nik'sTapasRestaurant</h1></div>
<divid="navbar"><ul><li>Aboutus</li><li>Reservations</li><li>Menus</li><li>Gallery</li><li>Events</li><li>Catering</li><li>Press</li></ul></div>
<divid="content"><imgsrc="food.jpg"alt="Nik'sTapas"></div>
<divid="footer">Copyright©Nik'sTapas</div></body></html>
Figure7-16:Leftnavigationwebpagelayoutcreatedusing<div>tags.
WritingMoreAdvancedCSSPracticeyourCSSonlineusingtheCodecademywebsite.Codecademyisafreewebsitecreatedin2011toallowanyonetolearnhowtocoderightinthebrowser,withoutinstallingordownloadinganysoftware.Practiceallofthetags(andafewmore)thatyoulearnedinthischapterbyfollowingthesesteps:
1. Openyourbrowser,gotowww.dummies.com/go/codingfd,andclickontheCodecademylink.
2. SignintoyourCodecademyaccount.
SigningupisdiscussedinChapter3.Creatinganaccountallowsyoutosaveyourprogressasyouwork,butit’soptional.
3. NavigatetoandclickonCSS:AnOverview,CSSSelectors,andCSSPositioningtopracticeCSSstylingandpositioning.
4. Backgroundinformationispresentedintheupperleftportionofthesite,andinstructionsarepresentedinthelowerleftportionofthe
site.5. Completetheinstructionsinthemaincodingwindow.Asyoutype,a
livepreviewofyourcodeisgenerated.6. Afteryouhavefinishedcompletingtheinstructions,clicktheSave
andSubmitCodebutton.
Ifyouhavefollowedtheinstructionscorrectly,agreencheckmarkappears,andyouproceedtothenextexercise.Ifanerrorexistsinyourcodeawarningappearswithasuggestedfix.Ifyourunintoaproblem,orhaveabugyoucannotfix,clickonthehint,usetheQ&AForums,ortweetmeat@nikhilgabrahamandincludehashtag#codingFD.
Chapter8WorkingFasterwithTwitter
BootstrapInThisChapter
UnderstandingwhatTwitterBootstrapdoesViewinglayoutscreatedwithTwitterBootstrapCreatingwebpageelementsusingTwitterBootstrap
Speed,itseemstome,providestheonegenuinelymodernpleasure.—AldousHuxley
TwitterBootstrapisafreetoolkitthatallowsuserstocreatewebpagesquicklyandwithgreatconsistency.In2011,twoTwitterdevelopers,MarkOttoandJacobThornton,createdthetoolkitforinternaluseatTwitter,andsoonafterreleasedittothegeneralpublic.BeforeBootstrap,developerswouldcreatecommonwebpagefeaturesoverandoveragainandeachtimeslightlydifferently,leadingtoincreasedtimespentonmaintenance.Bootstraphasbecomeoneofthemostpopulartoolsusedincreatingwebsites,andisusedbyNASAandNewsweekfortheirwebsites.WithabasicunderstandingofHTMLandCSS,youcanuseandcustomizeBootstraplayoutsandelementsforyourownprojects.
Inthischapter,youdiscoverwhatBootstrapdoesandhowtouseit.YoualsodiscoverthevariouslayoutsandelementsthatyoucanquicklyandeasilycreatewhenusingBootstrap.
FiguringOutWhatBootstrapDoesImagineyouaretheonlinelayoutdeveloperforTheWashingtonPost,responsibleforcodingthefrontpageoftheprintnewspaper(seeFigure8-1)intoadigitalwebsiteversion.Thenewspaperconsistentlyusesthesamefontsizeandtypefaceforthemainheadline,captions,andbylines.Similarly,
thereareasetnumberoflayoutstochoosefrom,usuallywiththemainheadlineatthetopofthepageaccompaniedbyaphoto.
Figure8-1:ThefrontpageofTheWashingtonPost(June7,2013).
EverydayyoucouldwriteyourCSScodefromscratch,definingfonttypeface,sizes,paragraphlayouts,andthelike.However,giventhatthenewspaperfollowsalargelydefinedformat,itwouldbeeasiertodefinethisstylingaheadoftimeinyourCSSfilewithclassnames,andwhennecessaryrefertothestylingyouwantbyname.Atitscore,thisishowBootstrapfunctions.
BootstrapisacollectionofstandardizedprewrittenHTML,CSS,andJavaScriptcodethatyoucanreferenceusingclassnames(forarefresher,seeChapter7)andthenfurthercustomize.Bootstrapallowsyoutocreateandgivesyou:
Layouts:Defineyourwebpagecontentandelementsinagridpattern.Components:Useexistingbuttons,menus,andiconsthathavebeentestedonhundredsofmillionsofusers.Responsiveness:Afancywordforwhetheryoursitewillworkonmobilephonesandtabletsinadditiontodesktopcomputers.Ordinarily,youwouldwriteadditionalcodesoyourwebsiteappearsproperlyonthese
differentscreensizes,butBootstrapcodeisalreadyoptimizedtodothisforyou,asshowninFigure8-2.Cross-browsercompatibility:Chrome,Firefox,Safari,InternetExplorer,andotherbrowsersallvaryinthewaytheyrendercertainHTMLelementsandCSSproperties.Bootstrapcodeisoptimizedsoyourwebpageappearsconsistentlynomatterthebrowserused.
Figure8-2:TheAngryBirdsStarWarspageoptimizedfordesktop,tablet,andmobileusingBootstrap.
InstallingBootstrapInstallandaddBootstraptoyourHTMLfilebyfollowingthesetwosteps:
1. Includethislineofcodebetweenyouropeningandclosing<head>tag:
<linkrel="stylesheet"href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
The<link>tagreferstoversion3.2.0oftheBootstrapCSSfilehostedontheInternet,soyoumustbeconnectedtotheInternetforthismethodtowork.
2. IncludeboththeselinesofcodeimmediatelybeforeyourclosingHTML</body>tag.
<!--jQuery(neededforBootstrap'sJavaScriptplugins)-->
<scriptsrc="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><!--BootstrapJavascriptpluginfile--><scriptsrc="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
Thefirst<script>tagreferencesaJavaScriptlibrarycalledjQuery.JavaScriptiscoveredinChapter9.AlthoughjQueryisnotcoveredinthisbook,atahighlevel,jQuerysimplifiestasksperformedusingJavaScript.Thesecond<script>tagreferencesBootstrapJavaScriptplugins,includinganimatedeffectssuchasdrop-downmenus.IfyourwebsitedoesnotuseanyanimatedeffectsorBootstrapJavaScriptplugins,youdon’tneedtoincludethisfile.
Bootstrapisfreetouseforpersonalandcommercialpurposes,butdoesrequireincludingtheBootstraplicenseandcopyrightnotice.
IfyouwillnothavereliableaccesstoanInternetconnection,youcanalsodownloadandlocallyhosttheBootstrapCSSandJavaScriptfiles.Todothis,afterunzippingtheBootstrapfile,usethe<link>and<script>tagstolinktothelocalversionofyourfile.Visitwww.getbootstrap.com/getting-started/todownloadthefiles,andtoaccessadditionalinstructionsandexamples.
UnderstandingtheLayoutOptionsBootstrapallowsyoutoquicklyandeasilylayoutcontentonthepageusingagridsystem.Youhavethreeoptionswhenusingthisgridsystem:
Codeyourself:Afteryoulearnhowthegridisorganized,youcanwritecodetocreateanylayoutyouwish.CodewithaBootstrapeditor:Insteadofwritingcodeinatexteditor,draganddropcomponentsandelementstogenerateBootstrapcode.Youcanthendownloadandusethiscode.Codewithaprebuilttheme:DownloadfreeBootstrapthemesorbuyathemewherethewebsitehasalreadybeencreated,andyoufillinyour
owncontent.
LininguponthegridsystemBootstrapdividesthescreenintoagridsystemof12equally-sizedcolumns.Thesecolumnsfollowafewrules:
Columnsmustsumtoawidthof12columns.Youcanuseonecolumnthatis12columnswide,12columnsthatareeachonecolumnwide,oranythinginbetween.Columnscancontaincontentorspaces.Forexample,youcouldhavea4-column-widecolumn,aspaceof4columns,andanother4-column-widecolumn.Unlessyouspecifyotherwise,thesecolumnswillautomaticallystackintoasinglecolumnonsmallerbrowsersizesorscreenslikemobiledevices,andexpandhorizontallyonlargerbrowsersizesorscreenslikelaptopanddesktopscreens.SeeFigure8-3.
Figure8-3:SampleBootstraplayouts.
Nowthatyouhaveasenseforhowtheselayoutsappearonthescreen,letustakealookatexamplecodeusedtogeneratetheselayouts.Tocreateanylayout,followthesesteps:
1. Createa<div>tagwiththeattributeclass="container".
2. Insidethefirst<div>tag,createanothernested<div>tagwiththeattributeclass="row".
3. Foreachrowyouwanttocreate,createanother<div>tagwiththeattributeclass="col-md-X".SetXequaltothenumberofcolumnsyouwanttherowtospan.
Forexample,tohavearowspan4columns,write<divclass="col-md-4">.Themdtargetsthecolumnwidthfordesktops,andIshowyouhowtotargetotherdeviceslaterinthissection.
Youmustinclude<divclass="container">atthebeginningofyourpage,andhaveaclosing</div>tagoryourpagewillnotrenderproperly.
Thefollowingcode,asshowninFigure8-4,createsasimplethree-columncenteredlayout:
<divclass="container"><!--Examplerowofcolumns--><divclass="row"><divclass="col-md-4"><h2>Heading</h2><p>Loremipsumdolorsitamet,consecteturadipisicingelit,seddoeiusmodtemporincididuntutlaboreetdoloremagnaaliqua.Utenimadminimveniam,quisnostrudexercitationullamcolaborisnisiutaliquipexeacommodoconsequat.</p></div><divclass="col-md-4"><h2>Heading</h2><p>Loremipsumdolorsitamet,consecteturadipisicingelit,seddoeiusmodtemporincididuntutlaboreetdoloremagnaaliqua.Utenimadminimveniam,quisnostrudexercitationullamcolaborisnisiutaliquipexeacommodoconsequat.</p></div><divclass="col-md-4"><h2>Heading</h2><p>Loremipsumdolorsitamet,consecteturadipisicingelit,seddoeiusmodtemporincididuntutlaboreetdoloremagnaaliqua.Utenimadminimveniam,quisnostrudexercitationullamcolaborisnisiutaliquipexeacommodoconsequat.</p></div>
</div></div>
Figure8-4:Bootstrapthree-columnlayoutwithdesktop(left)andmobile(right)versions.
Toseeanotherexample,gototheCodecademysite,andresizethebrowserwindow.Youwillnoticethatasyoumakethebrowserwindowsmaller,thecolumnswillautomaticallystackontopononeanothertobereadable.Also,thecolumnsareautomaticallycentered.WithoutBootstrap,youwouldneedmorecodetoachievethesesameeffects.
TheLoremipsumtextyouseeaboveiscommonlyusedtocreatefillertext.Althoughthewordsdon’tmeananything,thequotationoriginatesfromafirst-centuryBCLatintextbyCicero.Youcangeneratefillertextwhencreatingyourownwebsitesbyusingwww.lipsum.orgorwww.socialgoodipsum.com.
DragginganddroppingtoawebsiteAfterlookingatthecodeabove,youmaywantaneveneasierwaytogeneratethecodewithouthavingtotypeityourself.Bootstrapeditorsallowyoutodraganddropcomponentstocreatealayout,andafterwhichtheeditorwillgenerateBootstrapcodeforyouruse.
Bootstrapeditorsyoucanuseincludethefollowing:
Layoutit.com:FreeonlineBootstrapeditor(asshowninFigure8-5)thatallowsyoutodraganddropcomponentsandthendownloadthesourcecode.Jetstrap.com:PaidonlinedraganddropBootstrapeditor.
Pingendo.com:FreedownloadabledraganddropBootstrapeditor.Bootply.com:FreeonlineBootstrapeditorwithbuilt-intemplatestomodify.
Thesesitesarefree,andmaystopworkingwithoutnotice.YoucanfindadditionaloptionsbyusinganysearchenginetosearchforBootstrapeditors.
Figure8-5:Layoutit.cominterfacewithdraganddropBootstrapcomponents.
UsingpredefinedtemplatesSitesexistwithready-to-useBootstrapthemes;allyouneedtodoisaddyourowncontent.Ofcourse,youcanalsomodifythethemeifyouwish.SomeoftheseBootstrapthemewebsitesare:
Blacktie.co:FreeBootstrapthemes(showninFigure8-6),allcreatedbyonedesigner.Bootstrapzero.com:Collectionoffree,open-sourceBootstraptemplates.Bootswatch.comandbootsnipp.com:Includespre-builtBootstrapcomponentsthatyoucanassembleforyourownsite.Wrapbootstrap.com:Bootstraptemplatesavailableforpurchase.
Bootstrapthemesmaybeavailableforfree,butfollowthelicensingterms.Theauthormayrequireattribution,emailregistration,oratweet.
Figure8-6:OnepageBootstraptemplatefromblacktie.co.
Adaptinglayoutformobile,tablet,anddesktopOnsmallerscreensBootstrapwillautomaticallystackthecolumnsyoucreateforyourwebsite.However,youcanexercisemorecontrolthanjustrelyingonthedefaultbehavioroverhowthesecolumnsappear.Therearefourdevicescreensizesyoucantarget–phones,tablets,desktops,andlargedesktops.AsshowninTable8-1,Bootstrapusesadifferentclassprefixtotargeteachdevice.
BasedonTable8-1,ifyouwantedyourwebsitetohavetwoequalsized
columnsontablets,desktops,andlargedesktopsyouwouldusethecol-sm-classnameasfollows:
<divclass="container"><divclass="row"><divclass="col-sm-6">Column1</div><divclass="col-sm-6">Column2</div></div></div>
Afterviewingyourcodeonallthreedevices,youdecidethatondesktopsyoupreferunequalinsteadofequalcolumnssuchthattheleftcolumnishalfthesizeoftherightcolumn.Youtargetdesktopdevicesusingthecol-md-classnameandaddittotheclassnameimmediatelyaftercol-sm-:
<divclass="container"><divclass="row"><divclass="col-sm-6col-md-4">Column1</div><divclass="col-sm-6col-md-8">Column2</div></div></div>
Someelements,suchasthe<div>tagabove,canhavemultipleclasses.Thisallowsyoutoaddmultipleeffects,suchaschangingthewayacolumnisdisplayed,totheelement.Todefinemultipleclasses,usetheclassattributeandsetitequaltoeachclass;separateeachclasswithaspace.Foranexample,refertotheprecedingcode:Thethird<div>elementhastwoclasses,col-sm-6andcol-md-4.
Finally,youdecidethatonlargedesktopscreensyouwanttheleftcolumntobetwocolumnswide.Youtargetlargedesktopscreensusingthecol-lg-classname,asshowninFigure8-7,andaddtoyourexistingclassattributevalues:
<divclass="container"><divclass="row"><divclass="col-sm-6col-md-4col-lg-2">Column1</div><divclass="col-sm-6col-md-8col-lg-10">Column2</div></div></div>
Figure8-7:Atwo-columnsitedisplayedontablet,desktop,andlargedesktop.
CodingBasicWebPageElementsInadditiontopurelayouts,Bootstrapcanalsocreatewebpagecomponentsfoundonalmosteverywebsite.Thethoughthereisthesameaswhenworkingwithlayouts—insteadofrecreatingthewheeleverytimebydesigningyourownbuttonortoolbar,itwouldbebettertousepre-builtcode,whichhasalreadybeentestedacrossmultiplebrowsersanddevices.
Thefollowingexamplesshowhowtoquicklycreatecommonwebcomponents.
DesigningbuttonsButtonsareabasicelementonmanywebpages,butusuallycanbedifficulttosetupandstyle.AsshowninTable8-2,buttonscanhavevarioustypesandsizes.
Table8-2BootstrapCodeforCreatingButtons
Attribute Classprefix Description
Buttontype
btn-defaultbtn-primarybtn-successbtn-danger
StandardbuttontypewithhovereffectBluebuttonwithhovereffectGreenbuttonwithhovereffectRedbuttonwithhovereffect
Buttonsize
btn-lgbtn-defaultbtn-sm LargebuttonsizeDefaultbuttonsizeSmallbuttonsize
Tocreateabutton,writethefollowingHTML:
BeginwiththebuttonHTMLelement.
Intheopening<button>tagincludetype="button".
Includetheclassattribute,withthebtnclassattributevalue,andaddadditionalclassprefixesbasedontheeffectyouwant.Toaddadditionalstyles,continueaddingtheclassprefixnameintotheHTMLclassattribute.
AsshowninFigure8-8,thefollowingcodecombinesbothbuttontypeandbuttonsize:
<p><buttontype="button"class="btnbtn-primarybtn-lg">Largeprimarybutton</button><buttontype="button"class="btnbtn-defaultbtn-lg">Largedefaultbutton</button></p><p><buttontype="button"class="btnbtn-success">DefaultSuccessbutton</button><buttontype="button"class="btnbtn-default">Defaultdefaultbutton</button></p><p><buttontype="button"class="btnbtn-dangerbtn-sm">Smalldangerbutton</button><buttontype="button"class="btnbtn-defaultbtn-sm">Smalldefaultbutton</button></p>
Foradditionalbuttontype,buttonsize,andotherbuttonoptionsseehttp://getbootstrap.com/css/#buttons.
Figure8-8:Bootstrapbuttontypesandsizes.
NavigatingwithtoolbarsWebpageswithmultiplepagesorviewsusuallyhaveoneormoretoolbarstohelpuserswithnavigation.SometoolbaroptionsareshowninTable8-3.
Table8-3BootstrapCodeforCreatingNavigationToolbars
Attribute ClassPrefix Description
Toolbartype nav-tabsnav-pills TabbednavigationtoolbarPill,orsolidbuttonnavigationtoolbar
Toolbarbuttontype
dropdowncaretdropdown-menu
MarksbuttonortabasdropdownmenuDown-arrowdropdownmenuiconDropdownmenuitems
Tocreateapillorsolidbuttonnavigationtoolbar,writethefollowingHTML:
Beginanunorderedlistusingtheulelement.
Intheopening<ul>tag,includeclass="navnav-pills".
Createbuttonsusingthe<li>tag.Includeclass="active"inoneopening<li>tagtodesignatewhichtabonthemaintoolbarshouldappearasvisuallyhighlightedwhenthemousehoversoverthebutton.Tocreateadrop-downmenu,nestanunorderedlist.Seethecodenextto“More”withclassprefixes"dropdown","caret",and"dropdown-menu".Youcanlinktootherwebpagesinyourdrop-downmenubyusingthe<a>tag.
Thefollowingcode,asshowninFigure8-9,createsatoolbarusingBootstrap:
<ulclass="navnav-pills"><liclass="active"><ahref="timeline.html">Timeline</a>
</li><li><ahref="about.html">About</a></li><li><ahref="photos.html">Photos</a></li><li><ahref="friends.html">Friends</a></li><liclass="dropdown"><aclass="dropdown-toggle"data-toggle="dropdown"href="13_9781118951309-ch08.xhtml#">More<spanclass="caret"></span></a><ulclass="dropdown-menu"><li><ahref="places.html">Places</a></li><li><ahref="sports.html">Sports</a></li><li><ahref="music.html">Music</a></li></ul></li></ul>
Figure8-9:Bootstraptoolbarwithdrop-downmenus.
Thedropdown-toggleclassandthedata-toggle="dropdown"attributeandvalueworktogethertoadddropdownmenustoelementslikelinks.Foradditionaltoolbaroptions,seehttp://getbootstrap.com/components/#nav.
AddingiconsIconsarefrequentlyusedwithbuttonstohelpconveysometypeofaction.Forexample,youremailprogramlikelyusesabuttonwithatrashcanicontodeleteemails.Iconsquicklycommunicateasuggestedactiontouserswithoutmuchexplanation.
Theseiconsarecalledglyphs,andwww.glyphicons.com
providestheglyphsusedinBootstrap.
Bootstrapsupportsmorethan200glyphs,whichyoucanaddtobuttonsortoolbarsusingthe<span>tag.AsshowninFigure8-10,theexamplecodebelowcreatesthreebuttonswithastar,paperclip,andtrashcanglyph.
<buttontype="button"class="btnbtn-default">Star<spanclass="glyphiconglyphicon-star"></star></button><buttontype="button"class="btnbtn-default">Attach<spanclass="glyphiconglyphicon-paperclip"></star></button><buttontype="button"class="btnbtn-default">Trash<spanclass="glyphiconglyphicon-trash"></star></button>
Figure8-10:Bootstrapbuttonswithicons
ForthenamesofalltheBootstrapglyphs,seewww.getbootstrap.com/components/#glyphicons.
BuildtheAirbnbHomePagePracticeBootstraponlineusingtheCodecademywebsite.Codecademyisafreewebsitecreatedin2011toallowanyonetolearnhowtocoderightinthebrowser,withoutinstallingordownloadinganysoftware.Practiceallofthetags(andafewmore)thatyoulearnedinthischapterbyfollowingthesesteps:
1. Openyourbrowser,gotowww.dummies.com/go/codingfd,andclickonthelinktoCodecademy.
2. SignintoyourCodecademyaccount.
SigningupisdiscussedinChapter3.Creatinganaccountallowsyoutosaveyourprogressasyouwork,butit’soptional.
3. NavigatetoandclickonMakeaWebsitetopracticeBootstrap.4. Backgroundinformationispresented,andinstructionsarepresented
onthesite.5. Completetheinstructionsinthemaincodingwindow.6. Afteryouhavefinishedcompletingtheinstructions,clicktheGotIt
orSaveandSubmitCodebutton.
Ifyouhavefollowedtheinstructionscorrectly,agreencheckmarkappearsandyouproceedtothenextexercise.Ifanerrorexistsinyourcodeawarningappearswithasuggestedfix.Ifyourunintoaproblem,orhaveabugyoucannotfix,clickonthehint,usetheQ&AForum,ortweetmeat@nikhilgabrahamandincludehashtag#codingFD.
Chapter9AddinginJavaScript
InThisChapterUnderstandingJavaScriptbasicsandstructureCodingwithvariables,conditionalstatements,andfunctionsLearningaboutAPIbasicsandstructureViewinganAPIrequestandresponse
Thebestteacherisveryinteractive.—BillGates
JavaScript,oneofthemostpopularandversatileprogramminglanguagesontheInternet,addsinteractivitytowebsites.YouhaveprobablyseenJavaScriptinactionandnotevenrealizedit,perhapswhileclickingbuttonsthatchangecolor,viewingimagegallerieswiththumbnailpreviews,oranalyzingchartsthatdisplaycustomizeddatabasedonyourinput.ThesewebsitefeaturesandmorecanbecreatedandcustomizedusingJavaScript.
JavaScriptisanextremelypowerfulprogramminglanguage,andthisentirebookcouldhavebeendevotedtothetopic.Inthischapter,youlearnJavaScriptbasics,includinghowtowriteJavaScriptcodetoperformbasictasks,accessdatausinganAPI,andprogramfasterusingaframework.
WhatDoesJavaScriptDo?JavaScriptcreatesandmodifieswebpageelements,andworkswiththeexistingwebpageHTMLandCSStoachievetheseeffects.WhenyouvisitawebpagewithJavaScript,yourbrowserdownloadstheJavaScriptcodeandrunsitclient-side,onyourmachine.JavaScriptcanperformtaskstodoanyofthefollowing:
ControlwebpageappearanceandlayoutbychangingHTMLattributes
andCSSstyles.Easilycreatewebpageelementslikedatepickers,asshowninFigure9-1,anddrop-downmenus.Takeuserinputinforms,andcheckforerrorsbeforesubmission.Displayandvisualizedatausingcomplexchartsandgraphs.Importandanalyzedatafromotherwebsites.
Figure9-1:JavaScriptcancreatethedatepickerfoundoneverytravelwebsite.
JavaScriptisdifferentfromanotherprogramminglanguagecalledJava.In1996,BrendanEich,atthetimeaNetscapeengineer,createdJavaScript,whichwasoriginallycalledLiveScript.Aspartofamarketingdecision,LiveScriptwasrenamedtoJavaScripttotryandbenefitfromthereputationofthen-popularJava.
JavaScriptwascreatedalmost20yearsago,andthelanguagehascontinuedtoevolvesincethen.Inthelastdecade,itsmostimportantinnovationhasalloweddeveloperstoaddcontenttowebpageswithoutrequiringtheusertoreloadthepage.Thistechnique,calledAJAX(asynchronousJavaScript),probablysoundstrivial,buthasledtothecreationofcutting-edgebrowserexperiencessuchasGmail(showninFigure9-2).
BeforeAJAX,thebrowserwoulddisplaynewdataonawebpageonlyafterwaitingfortheentirewebpagetoreload.However,thissloweddownthe
userexperience,especiallywhenviewingwebpageswhichhadfrequentrealtimeupdateslikewebpageswithnewsstories,sportsupdates,andstockinformation.JavaScript,specificallyAJAX,createdawayforyourbrowsertocommunicatewithaserverinthebackground,andtoupdateyourcurrentwebpagewiththisnewinformation.
Figure9-2:GmailusesAJAX,whichletsusersreadnewemailswithoutreloadingthewebpage.
HereisaneasywaytothinkaboutAJAX:Imagineyouareatacoffeeshop,andjustorderedacoffeeafterwaitinginareallylongline.BeforeasynchronousJavaScript,youhadtowaitpatientlyatthecoffeebaruntilyoureceivedyourcoffeebeforedoinganythingelse.WithasynchronousJavaScript,youcanreadthenewspaper,findatable,phoneafriend,anddomultipleothertasksuntilthebaristacallsyournamealertingyouthatyourcoffeeisready.
UnderstandingJavaScriptStructureJavaScripthasadifferentstructureandformatfromHTMLandCSS.JavaScriptallowsyoutodomorethanpositionandstyletextonawebpage—withJavaScript,youcanstorenumbersandtextforlateruse,decidewhatcodetorunbasedonconditionswithinyourprogram,andevennamepiecesofyourcodesoyoucaneasilyreferencethemlater.AswithHTMLandCSS,JavaScripthasspecialkeywordsandsyntaxthatallowthecomputerto
recognizewhatyouaretryingtodo.UnlikeHTMLandCSS,however,JavaScriptisintolerantofsyntaxmistakes.IfyouforgettocloseanHTMLtag,ortoincludeaclosingcurlybraceinCSS,yourcodemaystillrunandyourbrowserwilltryitsbesttodisplayyourcode.WhencodinginJavaScript,ontheotherhand,forgettingasinglequoteorparenthesiscancauseyourentireprogramtofailtorunatall.
HTMLappliesaneffectbetweenopeningandclosingtags—<h1>Thisisaheader</strong>.CSSusesthesameHTMLelementandhaspropertiesandvaluesbetweenopeningandclosingcurlybraces—h1{color:red;}.
UsingSemicolons,Quotes,Parentheses,andBraces
ThecodebelowillustratesthecommonpunctuationusedinJavaScript—semicolons,quotes,parentheses,andbraces(alsocalledcurlybrackets):
varage=22;varplanet="Earth";if(age>=18){console.log("Youareanadult");console.log("Youareover18");
}else{console.log("Youarenotanadult");console.log("Youarenotover18");}
GeneralrulesofthumbtoknowwhileprogramminginJavaScriptinclude:
SemicolonsseparateJavaScriptstatements.Quotesenclosetextcharactersorstrings(sequencesofcharacters).Anyopeningquotemusthaveaclosingquote.
Parenthesesareusedtomodifycommandswithadditionalinformationcalledarguments.Anyopeningparenthesismusthaveaclosingparenthesis.BracesgroupJavaScriptstatementsintoblockssotheyexecutetogether.Anyopeningbracemusthaveaclosingbrace.
Thesesyntaxrulescanfeelarbitrary,andmaybedifficulttorememberinitially.Withsomepractice,however,theseruleswillfeellikesecondnaturetoyou.
CodingCommonJavaScriptTasksJavaScriptcanbeusedtoperformmanytasks,fromsimplevariableassignmentstocomplexdatavisualizations.Thefollowingtasks,hereexplainedwithinaJavaScriptcontext,arecoreprogrammingconceptsthathaven’tchangedinthelasttwentyyearsandwon’tchangeinthenexttwenty.They’reapplicabletoanyprogramminglanguage.Finally,I’velistedinstructionsonhowtoperformthesetasks,butifyoupreferyoucanalsopracticetheseskillsrightawaybyjumpingaheadtothe“WritingYourFirstJavaScriptProgram”section,laterinthischapter.
StoringdatawithvariablesVariables,likethoseinalgebra,arekeywordsusedtostoredatavaluesforlateruse.Thoughthedatastoredinavariablemaychange,thevariablenameremainsthesame.Thinkofavariablelikeagymlocker—whatyoustoreinthelockerchanges,butthelockernumberalwaysstaysthesame.Thevariablenameusuallystartswithaletter,andTable9-1listssometypesofdataJavaScriptvariablescanstore.
Foralistofrulesonvariablenamesseethe“JavaScriptVariables”sectionatwww.w3schools.com/js/js_variables.asp.
Table9-1DataStoredbyaVariable
DataType Description Examples
Numbers Positiveornegativenumberswithorwithoutdecimals 156–101.96
Strings Printablecharacters HollyNovakSeñor
Boolean Valuecaneitherbetrueorfalse. truefalse
Thefirsttimeyouuseavariablename,youusethewordvartodeclarethevariablename.Then,youcanoptionallyassignavaluetovariableusingtheequalssign.Inthefollowingcodeexample,Ideclarethreevariablesandassignvaluestothosevariables:
varmyName="Nik";varpizzaCost=10;vartotalCost=pizzaCost*2;
Programmerssayyouhavedeclaredavariablewhenyoufirstdefineitusingthevarkeyword.“Declaring”avariabletellsthecomputertoreservespaceinmemoryandtopermanentlystorevaluesusingthevariablename.Viewthesevaluesbyusingtheconsole.logstatement.Forexample,afterrunningtheprecedingexamplecode,runningstatementconsole.log(totalCost)returnsthevalue20.
Afterdeclaringavariable,youchangeitsvaluebyreferringtojustthevariablenameandusingtheequalssign,asshowninthefollowingexamples:
myName="Steve";pizzaCost=15;
Variablenamesarecasesensitive,sowhenreferringtoavariableinyourprogramrememberthatMyNameisadifferentvariablefrommyname.Ingeneral,it’sagoodideatogiveyourvariableanamethatdescribesthedatabeingstored.
Makingdecisionswithif-elsestatementsAfteryouhavestoreddatainavariable,itiscommontocomparethevariable’svaluetoothervariablevaluesortoafixedvalue,andthentomakeadecisionbasedontheoutcomeofthecomparison.InJavaScript,these
comparisonsaredoneusingaconditionalstatement.Theif-elsestatementisatypeofconditional.Itsgeneralsyntaxisasfollows:
if(condition){statement1toexecuteifconditionistrue}else{statement2toexecuteifconditionisfalse}
Inthisstatement,theifisfollowedbyaspace,andaconditionenclosedinparenthesesevaluatestotrueorfalse.Iftheconditionistrue,thenstatement1,locatedbetweenthefirstsetofcurlybrackets,isexecuted.IftheconditionisfalseandifIincludetheelse,whichisoptional,thenstatement2,locatedbetweenthesecondsetofcurlybrackets,isexecuted.Notethatwhentheelseisnotincludedandtheconditionisfalse,theconditionalstatementsimplyends.
Noticetherearenoparenthesesaftertheelse—theelselinehasnocondition.JavaScriptexecutesthestatementafterelseonlywhentheprecedingconditionsarefalse.
Theconditioninanif-elsestatementisacomparisonofvaluesusingoperators,andcommonoperatorsaredescribedinTable9-2.
Hereisasimpleifstatement,withouttheelse:
varcarSpeed=70;if(carSpeed>55){alert("Youareoverthespeedlimit!");}
InthisstatementIdeclareavariablecalledcarSpeedandsetitequalto70.ThenanifstatementwithaconditioncompareswhetherthevalueinthevariablecarSpeedisgreaterthan55.Iftheconditionistrue,analert,whichisapop-upbox,states“Youareoverthespeedlimit!”(SeeFigure9-3.)Inthiscase,thevalueofcarSpeedis70,whichisgreaterthan55,sotheconditionistrueandthealertisdisplayed.IfthefirstlineofcodeinsteadwasvarcarSpeed=40;thentheconditionisfalsebecause40islessthan55,andnoalertwouldbedisplayed.
Figure9-3:Thealertpop-upbox.
Letusexpandtheifstatementbyaddingelsetocreateanif-else,asshowninthiscode:
varcarSpeed=40;if(carSpeed>55){alert("Youareoverthespeedlimit!");}else{alert("Youareunderthespeedlimit!");}
Inadditiontotheelse,Iaddedanalertstatementinsidethecurlybracketsfollowingtheelse,andsetcarSpeedequalto40.Whenthisif-elsestatementexecutes,carSpeedisequalto40,whichislessthan55,sotheconditionisfalse,andbecausetheelsehasbeenadded,analertappearsstating“Youareunderthespeedlimit!”IfthefirstlineofcodeinsteadwasvarcarSpeed=70;asbefore,thentheconditionistrue,because70isgreaterthan55,andthefirstalertwouldbedisplayed.
Ourcurrentif-elsestatementallowsustotestforonecondition,andtoshowdifferentresultsdependingonwhethertheconditionistrueorfalse.Totestfortwoormoreconditions,youcanaddoneormoreelseifstatementsaftertheoriginalifstatement.Thegeneralsyntaxforthisisasfollows:
if(condition1){statement1toexecuteifcondition1istrue}elseif(condition2){statement2toexecuteifcondition2istrue}else{statement3toexecuteifallpreviousconditionsarefalse}
Theif-elseiswrittenasbefore,andtheelseifisfollowedbyaspace,andthenaconditionenclosedinparenthesesthatevaluatestoeithertrueorfalse.Ifcondition1istrue,thenstatement1,locatedbetweenthefirstsetofcurlybrackets,isexecuted.Ifthecondition1isfalse,thencondition2isevaluatedandisfoundtobeeithertrueorfalse.Ifcondition2istrue,thenstatement2,locatedbetweenthesecondsetofcurlybrackets,isexecuted.Atthispoint,additionalelseifstatementscouldbeaddedtotestadditionalconditions.Onlywhenallifandelseifconditionsarefalse,andanelseisincluded,isstatement3executed.Onlyonestatementisexecutedinablockofcode,afterwhichtheremainingstatementsareignoredandthenextblockofcodeisexecuted.
Whenwritingtheif-else,youmusthaveoneandonlyoneifstatement,and,ifyousochoose,oneandonlyoneelsestatement.Theelseifisoptional,canbeusedmultipletimeswithinasingleif-elsestatement,andmustcomeaftertheoriginalifstatementandbeforetheelse.Youcannothaveanelseiforanelsebyitself,withoutaprecedingifstatement.
Hereisanotherexampleelseifstatement:
varcarSpeed=40;if(carSpeed>55){alert("Youareoverthespeedlimit!");}elseif(carSpeed===55){alert("Youareatthespeedlimit!");}
Whenthisifstatementexecutes,carSpeedisequalto40,whichislessthan55,sotheconditionisfalse,andthentheelseifconditionisevaluated.ThevalueofcarSpeedisnotexactlyequalto55sothisconditionisalsofalse,andnoalertofanykindisshown,andthestatementends.IfthefirstlineofcodewereinsteadvarcarSpeed=55;thenthefirstconditionisfalse,because55isnotgreaterthan55.Thentheelseifconditionisevaluated,andbecause55isexactlyequalto55,thesecondalertisdisplayed,stating“Youareatthespeedlimit!”
Lookcarefullyatthecodeabove—-whensettingthevalueofavariable,oneequalssignisused,butwhencomparingwhethertwovaluesareequal,thenthreeequalssigns(===)areused.
Asafinalexample,hereisanif-elsestatementwithanelseifstatement:
varcarSpeed=40;if(carSpeed>55){alert("Youareoverthespeedlimit!");}elseif(carSpeed===55){alert("Youareatthespeedlimit!");}else{alert("Youareunderthespeedlimit!");}
AsthediagraminFigure9-4shows,twoconditions,whichappearinthefigureasdiamonds,areevaluatedinsequence.Inthisexample,thecarSpeedisequalto40,sothetwoconditionsarefalse,andthestatementaftertheelseisexecuted,showinganalertthatsays“Youareunderthe
speedlimit!”HerecarSpeedisinitiallysetto40,butdependingontheinitialcarSpeedvariablevalue,anyoneofthethreealertscouldbedisplayed.
Figure9-4:If-elsewithanelseifstatement.
Theconditionisalwaysevaluatedfirst,andeveryconditionmusteitherbetrueorfalse.Independentfromtheconditionisthestatementthatexecutesiftheconditionistrue.
WorkingwithstringandnumbermethodsThemostbasicdatatypes,usuallystoredinvariables,arestringsandnumbers.Programmersoftenneedtomanipulatestringsandnumberstoperformbasictaskssuchasthefollowing:
Determiningthelengthofastring,asforapassword.Selectingpart(orsubstring)ofastring,aswhenchoosingthefirstnameinastringthatincludesthefirstandlastname.Roundinganumbertofixednumbersofdecimalpoints,aswhentakingasubtotalinanonlineshoppingcart,calculatingthetax,roundingthetaxtotwodecimalpoints,andaddingthetaxtothesubtotal.
ThesetasksaresocommonthatJavaScriptincludesshortcutscalledmethods(italicizedabove)thatmakeperformingtasksliketheseeasier.Thegeneralsyntaxtoperformthesetasksistofollowtheaffectedvariable’snameorvaluewithaperiodandthenameofthemethod,asfollowsforvaluesandvariables:
value.method;variable.method;
Table9-3showsexamplesofJavaScriptmethodsforthebasictasksdiscussedabove.Examplesincludemethodsappliedtovalues,suchasstrings,andtovariables.
Whenusingastring,orassigningavariabletoavaluethatisastring,alwaysenclosethestringinquotes.
The.toFixedand.lengthmethodsarerelativelystraightforward,butthe.substringmethodcanbealittleconfusing.Thestartingandendingpositionsusedin.substring(start,end)donotreferenceactualcharacters,butinsteadreferencethespacebetweeneachcharacter.Figure9-5showshowthestartandendpositionworks.Thestatement"Inbox".substring(2,5)startsatposition2,whichisbetween"n"and"b",andendsatposition5whichisafterthe"x".
Figure9-5:The.substringmethodreferencespositionsthatarebetweencharactersinastring.
ForalistofadditionalstringandnumbermethodsseeW3Schoolswww.w3schools.com/js/js_number_methods.aspandwww.w3schools.com/js/js_string_methods.asp.
AlertingusersandpromptingthemforinputDisplayingmessagestotheuserandcollectinginputarethebeginningsoftheinteractivitythatJavaScriptprovides.Althoughmoresophisticatedtechniquesexisttoday,thealert()methodandprompt()methodareeasywaystoshowapop-upboxwithamessage,andprompttheuserforinput.
Thesyntaxforcreatinganalertorapromptistowritethemethodwithtextinquotesplacedinsidetheparentheseslikeso:
alert("Youhavemail");prompt("Whatdoyouwantfordinner?");
Figure9-6showsthealertpop-upboxcreatedbythealert()method,andthepromptforuserinputcreatedbytheprompt()method.
Figure9-6:AJavaScriptalertpop-upboxandauserprompt.
Namingcodewithfunctions
FunctionsareawayofgroupingJavaScriptstatements,andnamingthatgroupofstatementsforeasyreferencewithafunctionname.Thesestatementsaretypicallygroupedtogetherbecausetheyachieveaspecificcodinggoal.Youcanusethestatementsrepeatedlybyjustwritingthefunctionnameinsteadofhavingtowritethestatementsoverandoveragain.Functionspreventrepetitionandmakeyourcodeeasiertomaintain.
WhenIwasyoungereverySaturdaymorningmymotherwouldtellmetobrushmyteeth,foldthelaundry,vacuummyroom,andmowthelawn.Eventually,mymothertiredofrepeatingthesamelistoverandoveragain,wrotethelistofchoresonpaper,titledit“Saturdaychores,”andputitonthefridge.Afunctionnamesagroupofstatements,justlike“Saturdaychores”wasthenameformylistofchores.
Functionsaredefinedonceusingthewordfunction,followedbyafunctionname,andthenasetofstatementsinsidecurlybrackets.Thisiscalledafunctiondeclaration.Thestatementsinthefunctionareexecutedonlywhenthefunctioniscalledbyname.Inthefollowingexample,Ihavedeclaredafunctioncalledgreetingthatasksforyournameusingtheprompt()method,returnsthenameyouenteredstoringitinavariablecalledname,anddisplaysamessagewiththenamevariableusingthealert()method:
functiongreeting(){varname=prompt("Whatisyourname?");alert("Welcometothiswebsite"+name);}
greeting();greeting();
Beneaththefunctiondeclaration,Ihavecalledthefunctiontwice,andsoIwilltriggertwopromptsformyname,whicharestoredinthevariablename,andtwomessageswelcomingthevalueinthevariablenametothiswebsite.
The“+”operatorisusedtoconcatenate(combine)stringswithotherstrings,values,orvariables.
Functionscantakeinputs,calledparameters,tohelpthefunctionrun,and
canreturnavaluewhenthefunctioniscomplete.Afterwritingmylistofchores,eachSaturdaymorningmymotherwouldsay“Nik,dotheSaturdaychores,”andwhenmybrotherwasoldenoughshewouldsay“Neel,dotheSaturdaychores.”Ifthelistofchoresisthefunctiondeclaration,and“Saturdaychores”isthefunctionname,then“Nik”and“Neel”aretheparameters.Finally,afterIwasfinished,Iwouldletmymomknowthechoreswerecomplete,muchasafunctionreturnsvalues.
Inthefollowingexample,Ihavedeclaredafunctioncalledamountdue,whichtakespriceandquantityasparameters.Thefunction,whencalled,calculatesthesubtotal,addsthetaxdue,andthenreturnsthetotal.Thefunctionamountdue(10,3)returns31.5.
functionamountdue(price,quantity){varsubtotal=price*quantity;vartax=1.05;vartotal=subtotal*tax;returntotal;}
alert("Theamountdueis$"+amountdue(10,3));
Everyopeningparenthesishasaclosingparenthesis,everyopeningcurlybrackethasaclosingcurlybracket,andeveryopeningdoublequotehasaclosingdoublequote.Canyoufindalltheopeningandclosingpairsintheexampleabove?
AddingJavaScripttothewebpageThetwowaystoaddJavaScripttothewebpageare:
EmbedJavaScriptcodeinanHTMLfileusingthescripttag.
LinktoaseparateJavaScriptfilefromtheHTMLfileusingthescripttag.
ToembedJavaScriptcodeinanHTMLfile,useanopeningandclosing<script>tag,andwriteyourJavaScriptstatementsbetweenthetwotags,asshowninthefollowingexample:
<!DOCTYPEhtml><html><head><title>EmbeddedJavaScript</title><script>alert("ThisisembeddedJavaScript");</script></head><body><h1>ExampleofembeddedJavaScript</h1></body></html>
The<script>tagcanbeplacedinsidetheopeningandclosing<head>tag,asshownabove,orinsidetheopeningandclosing<body>tag.Therearesomeperformanceadvantageswhenchoosingoneapproachovertheother,andyoucanreadmoreathttp://stackoverflow.com/questions/436411/where-is-the-best-place-to-put-script-tags-in-html-markup.
The<script>tagisalsousedwhenlinkingtoaseparateJavaScriptfile,whichistherecommendedapproach.The<script>tagincludes:
Atypeattribute,whichforJavaScriptisalwayssetequalto"text/javascript"
Asrcattribute,whichissetequaltothelocationoftheJavaScriptfile.
<!DOCTYPEhtml><html><head><title>LinkingtoaseparateJavaScriptfile</title><scripttype="text/javascript"src="script.js"></script></head><body><h1>LinkingtoaseparateJavaScriptfile</h1></body>
</html>
The<script>taghasanopeningandclosingtag,whetherthecodeisembeddedbetweenthetagsorlinkedtoseparatefileusingthesrcattribute.
WritingYourFirstJavaScriptProgram
PracticeyourJavaScriptonlineusingtheCodecademywebsite.Codecademyisafreewebsitecreatedin2011toallowanyonetolearnhowtocoderightinthebrowser,withoutinstallingordownloadinganysoftware.Practiceallofthetags(andafewmore)thatyoulearnedinthischapterbyfollowingthesesteps:
1. Openyourbrowser,gotowww.dummies.com/go/codingfd,andclickonthelinktoCodecademy.
2. SignintoyourCodecademyaccount.
SigningupisdiscussedinChapter3.Creatinganaccountallowsyoutosaveyourprogressasyouwork,butit’soptional.
3. NavigatetoandclickonGettingStartedwithProgramming.4. Backgroundinformationispresentedintheupperleftportionofthe
site,andinstructionsarepresentedinthelowerleftportionofthesite.
5. Completetheinstructionsinthemaincodingwindow.6. Afteryouhavefinishedcompletingtheinstructions,clicktheSave
andSubmitCodebutton.
Ifyouhavefollowedtheinstructionscorrectly,agreencheckmarkappearsandyouproceedtothenextexercise.Ifanerrorexistsinyourcodeawarningappearswithasuggestedfix.Ifyourunintoaproblem,orhaveabugyoucannotfix,clickonthehint,usetheQ&AForums,or
tweetmeat@nikhilgabrahamandincludehashtag#codingFD.
WorkingwithAPIsAlthoughAPIs(applicationprogramminginterfaces)haveexistedfordecades,thetermhasbecomepopularoverthelastfewyearsaswehearmoreconversationandpromotionaroundtheiruse.UsetheFacebookAPI!Whydoesn’tCraigslisthaveanAPI?Stripe’sentirebusinessistoallowdeveloperstoacceptpaymentsonlineusingitspaymentsAPI.
ManypeopleusethetermAPI,butfewunderstanditsmeaning.ThissectionwillhelpclarifywhatAPIsdoandhowtheycanbeused.
WhatdoAPIsdo?AnAPIallowsProgramAtoaccessselectfunctionsofanotherseparateProgramB.ProgramBgrantsaccessbyallowingProgramAtomakeadatarequestinastructured,predictable,documentedway,andProgramBrespondstothisdatarequestwithastructured,predictable,documentedresponse,asfollows(seeFigure9-7):
It’sstructuredbecausethefieldsintherequestandthedataintheresponsefollowaneasy-to-readstandardizedformat.Forexample,theYahooWeatherAPIdataresponseincludestheseselectedstructureddatafields:
"location":{"city":"NewYork","region":"NY"},"units":{"temperature":"F"},"forecast":{"date":"29Oct2014","high":"68","low":"48","text":"PMShowers"}
SeethefullYahooWeatherAPIresponsebyvisitinghttp://developer.yahoo.com/weather/.
It’spredictablebecausethefieldsthatmustbeincludedandcanbeincludedintherequestarepre-specified,andtheresponsetoasuccessfulrequestwillalwaysincludethesamefieldtypes.It’sdocumentedbecausetheAPIisexplainedindetail.Anychangesusuallyarecommunicatedthroughthewebsite,socialmedia,email,andevenaftertheAPIchanges,thereisoftenaperiodofbackwardcompatibilitywhentheoldAPIrequestswillreceivearesponse.Forexample,whenGoogleMapsissuedversion3oftheirAPI,version2stilloperatedforacertaingraceperiod.
Figure9-7:AnAPIallowstwoseparateprogramstotalktoeachother.
AboveyousawaweatherAPIresponse,sowhatwouldyouincludeinarequesttoaweatherAPI?Thefollowingfieldsarelikelyimportanttoinclude:
Location,whichcanpotentiallybespecifiedbyusingzipcode,cityandstate,currentlocationinlatitudeandlongitudecoordinates,orIPaddress.Relevanttimeperiod,whichcouldincludetheinstant,daily,threeday,weekly,or10-dayforecast.Unitsfortemperature(FahrenheitorCelsius)andprecipitation(inchesorcentimeters).
Thesefieldsinourrequestjustspecifythedesiredtypeanddataformat.TheactualweatherdatawouldbesentaftertheAPIknowsyourdatapreferences.
Canyouthinkofanyotherfactorstoconsiderwhenmakingtherequest?Hereisoneclue—imagineyouworkforAlRokeronNBC’sTodayTVshow,andyouareresponsibleforupdatingtheweatherontheshow’swebsitefor1millionvisitorseachmorning.Meanwhile,Ihaveawebsite,NikWeather,whichaverages10dailyvisitorswhochecktheweatherthere.TheTodaywebsiteandmywebsitebothmakearequesttothesameweatherAPIatthesametime.Whoshouldreceivetheirdatafirst?Itseemsintuitivethattheneedsof1millionvisitorsontheTodaywebsiteshouldoutweightheneedsofmywebsite’s10visitors.AnAPIcanprioritizewhichrequesttoservefirst,whentherequestincludesanAPIkey.AnAPIkeyisauniquevalue,usuallyalongalpha-numericstring,whichidentifiestherequestorandisincludedintheAPIrequest.DependingonyouragreementwiththeAPIprovider,yourAPIkeycanentitleyoutoreceiveprioritizedresponses,additionaldata,orextrasupport.
Canyouthinkofanyotherfactorstoconsiderwhenmakingtherequest?Hereisanotherclue—isthereanydifferenceinworkingwithweatherdataversusfinancialdata?Theotherfactortokeepinmindisfrequencyofdatarequestsandupdates.APIswillgenerallylimitthenumberoftimesyoucanrequestdata.InthecaseofaweatherAPI,maybetherequestlimitisonceeveryminute.Relatedtohowoftenyoucanrequestthedataishowoftenthedataisrefreshed.Therearetwoconsiderations—howoftentheunderlyingdatachanges,andhowoftentheAPIproviderupdatesthedata.Forexample,exceptinextremecircumstancestheweathergenerallychangesevery15minutes.OurspecificweatherAPIprovidermayupdateitsweatherdataevery30minutes.Therefore,youwouldonlysendanAPIrequestonceevery30minutes,becausesendingmorefrequentrequestswouldn’tresultinupdateddata.Bycontrast,financialdatasuchasstockpricesandmanypublicAPIs,whichchangemultipletimespersecond,allowonerequestpersecond.
ScrapingdatawithoutanAPIIntheabsenceofanAPI,thosewhowantdatafromathird-partywebsitecreateprocessestobrowsethewebsite,searchandcopydata,andstoreitforlateruse.Thismethodofdataretrievaliscommonlyreferredtoasscreenscrapingorwebscraping.Theseprocesses,whichvaryinsophisticationfromsimpletocomplex,include:
Peoplemanuallycopyingandpastingdatafromwebsitesintoa
database:Crowdsourcedwebsites,suchaswww.retailmenot.comrecentlylistedontheNASDAQstockexchange,obtainsomedatainthisway.Codesnippetswrittentofindandcopydatathatmatchpre-setpatterns:Thepre-setpatternsarealsocalledregularexpressions,whichmatchcharacterandstringcombinations,andcanbewrittenusingweblanguageslikeJavaScriptorPython.Automatedsoftwaretoolswhichallowyoutopointandclickthefieldsyouwanttoretrievefromawebsite:Forexample,www.kimonolabs.comisonepoint-and-clicksolution,andwhenFIFAWorldCup2014lackedastructuredAPI,kimonolabs.comextracteddata,suchasscores,andmadeiteasilyaccessible.
Theadvantageofscreenscrapingisthatthedataislikelytobeavailableandwithlessrestrictionsbecauseitiscontentthatregularuserssee.IfanAPIfails,itmaygounnoticedanddependingonthesitetaketimetofix.Bycontrast,themainwebsitefailingisusuallyatoppriorityitem,andfixedassoonaspossible.Additionally,companiesmayenforcelimitsondataretrievedfromtheAPIthatarerarelyseenandhardertoenforcewhenscreenscraping.
Thedisadvantageofscreenscrapingisthatthecodewrittentocapturedatafromawebsitemustbepreciseandcanbreakeasily.Forexample,astockpriceisonawebpageinthesecondparagraph,onthethirdline,andisthefourthword.Thescreenscrapingcodeisprogrammedtoextractthestockpricefromthatlocation,butunexpectedlythewebsitechangesitslayoutsothestockpriceisnowinthefifthparagraph.Suddenly,thedataisinaccurate.Additionally,theremaybelegalconcernswithextractingdatainthisway,especiallyifthewebsitetermsandconditionsprohibitscreenscraping.Inoneexample,Craigslisttermsandconditionsprohibiteddataextractionthroughscreenscraping,andafterlitigationacourtbannedacompanywhichaccessedCraigslistdatausingthistechnique.
ResearchingandchoosinganAPIForanyparticulardatatasktheremaybemultipleAPIsthatcanprovideyouwiththedatayouseek.ThefollowingaresomefactorstoconsiderwhenselectinganAPIforuseinyourprograms:
Dataavailability:MakeawishlistoffieldsyouwanttousewiththeAPI,andcompareittofieldsactuallyofferedbyvariousAPIproviders.Dataquality:BenchmarkhowvariousAPIprovidersgatherdata,andthefrequencywithwhichthedataisrefreshed.Sitereliability:Measuresiteuptimebecauseregardlessofhowgoodthedatamaybe,thewebsiteneedstostayonlinetoprovideAPIdata.Sitereliabilityisamajorfactorinindustrieslikefinanceandhealthcare.Documentation:ReviewtheAPIdocumentationforreadingeaseanddetailsoyoucaneasilyunderstandtheAPIfeaturesandlimitationsbeforeyoubegin.Support:Callsupporttoseeresponsetimesandcustomersupportknowledgeability.Somethingwillgowrongandwhenitdoesyouwanttobewellsupportedtoquicklydiagnoseandsolveanyissues.Cost:ManyAPIsprovidefreeaccessbelowacertainrequestthreshold.InvestigatecoststructuresifyouexceedthoselevelssoyoucanproperlybudgetforaccesstoyourAPI.
UsingJavaScriptLibrariesAJavaScriptlibraryispre-writtenJavaScriptcodethatmakesthedevelopmentprocesseasier.Thelibraryincludescodeforcommontasksthathasalreadybeentestedandimplementedbyothers.Tousethecodeforthesecommontasks,youonlyneedtocallthefunctionormethodasdefinedinthelibrary.TwoofthemostpopularJavaScriptlibrariesarejQueryandD3.js.
jQueryjQueryusesJavaScriptcodetoanimatewebpagesbymodifyingCSSonthepage,andtoprovidealibraryofcommonlyusedfunctions.AlthoughyoucouldwriteJavaScriptcodetoaccomplishanyjQueryeffect,jQuery’sbiggestadvantageiscompletingtasksbywritingfewerlinesofcode.AsthemostpopularJavaScriptlibrarytoday,jQueryisusedonthemajorityoftop10,000mostvisitedwebsites.Figure9-8showsaphotogallerywithjQuerytransitionimageeffects.
D3.js
D3.jsisaJavaScriptlibraryforvisualizingdata.JustlikewithjQuery,similareffectscouldbeachievedusingJavaScript,butonlyafterwritingmanymorelinesofcode.Thelibraryisparticularlyadeptatshowingdataacrossmultipledimensions,andcreatinginteractivevisualizationsofdatasets.ThecreatorofD3.jsiscurrentlyemployedatTheNewYorkTimes,whichextensivelyusesD3.jstocreatechartsandgraphsforonlinearticles.Figure9-9isaninteractivechartshowingtechnologycompanyIPOvalueandperformanceovertime.
Figure9-8:PhotogallerywithjQuerytransitionimageeffectstriggeredbynavigationarrows.
Figure9-9:AnIPOchartshowingthevaluationoftheFacebookIPOrelativetoothertechnologyIPOs.
SearchingforVideoswithYouTube’sAPI
PracticeaccessingAPIsusingtheCodecademywebsite.Codecademyisafreewebsitecreatedin2011toallowanyonetolearnhowtocoderightinthebrowser,withoutinstallingordownloadinganysoftware.Practiceallofthetags(andafewmore)thatyoulearnedinthischapterbyfollowingthesesteps:
1. Openyourbrowser,gotowww.dummies.com/go/codingfd,andclickonthelinktoCodecademy.
2. SignintoyourCodecademyaccount.
SigningupisdiscussedinChapter3.Creatinganaccountallowsyoutosaveyourprogressasyouwork,butit’soptional.
3. NavigatetoandclickonHowtouseAPIswithJavaScript,andthenSearchingforYouTubeVideos.
4. Backgroundinformationispresentedintheupperleftportionofthesite,andinstructionsarepresentedinthelowerleftportionofthesite.
5. Completetheinstructionsinthemaincodingwindow.6. Afteryouhavefinishedcompletingtheinstructions,clicktheSave
andSubmitCodebutton.
Ifyouhavefollowedtheinstructionscorrectly,agreencheckmarkappearsandyouproceedtothenextexercise.Ifanerrorexistsinyourcodeawarningappearswithasuggestedfix.Ifyourunintoaproblem,orhaveabugyoucannotfix,clickonthehint,usetheQ&AForums,ortweetmeat@nikhilgabrahamandincludehashtag#codingFD.
PartIIIPuttingTogetheraWeb
Application
Toseehowtobuildyourownappusinggeolocation,checkoutwww.dummies.com/extras/coding.
Inthispart…Plantobringyourfirstwebapplicationtolife.Meetthepeoplewhohelpbuildwebapplications.Researcheachcomponentofyourfirstwebapplication.Buildyourwebapplicationwithoffersbasedonlocation.Debugtheerrorsinyourfirstwebapplication.
Chapter10BuildingYourOwnApp
InThisChapterCompletingacasestudyusinganappUnderstandingtheprocessofcreatinganapptosolveaproblemDiscoveringthevariouspeoplethathelpcreateanapp
Ifyouhaveadream,youcanspendalifetime…gettingreadyforit.Whatyoushouldbedoingisgettingstarted.
—DrewHoustonIfyouhaveread(orskimmed)thepreviouschaptersyounowhaveenoughHTML,CSS,andJavaScriptknowledgetowriteyourownwebapplication.Toreview,HTMLputscontentonthewebpage,CSSstylesthatcontent,andJavaScriptallowsforinteractionwiththatcontent.
Youmayfeellikeyoudon’thaveenoughcodingknowledgetocreateanapp,butIpromisethatyoudo.Besides,theonlywaytoknowforcertainistogetstartedandtry.Inthischapter,youcometobetterunderstandtheappyouaregoingtobuild,andthebasicstepstocreatethatapp.Developersoftenbeginwithjusttheinformationpresentedinthischapterandareexpectedtocreateaprototype.Afterreadingthischapterthinkabouthowyouwouldbuildtheapp,andthenrefertochaptersthatfollowformoredetailsoneachstep.
BuildingaLocation-BasedOfferAppTechnologycanprovidedevelopers(likeyou)oneofthemostvaluablepiecesofinformationaboutyourusers—theircurrentlocation.Withmobiledevices,suchascellphonesandtablets,youcanevenfindauser’slocationwhentheyareon-the-go.Althoughyoulikelyhaveusedanapptoretrievethetime,weather,orevendrivingdirections,youmayneverhavereceivedanofferonyourphonetocomeintoastorewhilewalkingdownthestreetordrivinginacar.ImaginepassingbyaMexicanrestaurantduringlunchtime
andreceivinganofferforafreetaco.I’mhungry,solet’sgetstarted!
UnderstandingthesituationThefollowingisafictitiouscasestudy.Anyresemblancetorealcompaniesoreventsiscoincidental.
TheMcDuck’sCorporationisoneofthelargestfastfoodrestaurantsintheworld,specializinginsellinghamburgersinarestaurantcalledMcDuck’s.Thecompanyhas35,000oftheserestaurantswhichserve6.5millionburgerseverydayto70millionpeopleinover100countries.InSeptember2014,McDuck’sexperienceditsworstsalesdeclineinoveradecade.Aftermanymeetings,theexecutiveteamdecidedthatthekeytoimprovingsaleswouldbeincreasingrestaurantfoottraffic.“Ourrestaurantexperience,withburgervisualsandfrench-fryaromas,isthebestintheindustry—onceacustomercomesinitisaguaranteedsale,”saysMcDuck’sCEODuckCorleone.Topromoterestaurantvisits,McDuck’swantsawebapplicationsocustomerscancheck-intotheirfavoritestore,andreceiveanofferorcouponiftheyareclosetoarestaurant.“Givingcustomerswhoare5or10minutesawayfromarestaurantanextranudgemayresultinavisit.Evenifcustomersusethisappwhileattherestaurant,thiswillallowustomaintainarelationshipwiththemlongaftertheyhaveleft,”saysCorleone.
TheMcDuckCorporationwantstorunapilottobetterunderstandwhetherlocationbasedofferswillincreasesales.Yourtaskisto:
Createanappthatwillprovewhetherlocationbasedoffersareeffective.LimittheapptoworkonjustoneMcDuck’sstoreofyourchoice.Obtainthelocationofcustomersusingtheapp.Showofferstothosecustomerswhoarefiveortenminutesfromthestore.
McDuck’scurrentlyhasawebsiteandamobileapp,butbothonlyshowmenuandstorelocationinformation.Ifthispilotissuccessful,McDuck’swillincorporateyourcodeintoitswebsiteandmobileapp.
PlottingyournextstepsNowthatyouunderstandMcDuck’srequest,youlikelyhavemanyquestions:
Whatwilltheapplooklike?WhatprogramminglanguageswillIusetocreatetheapp?HowwillIwritecodetolocateauser’spresentlocation?WhatofferwillIshowtoauserwhois5to10minutesaway?
Thesearenaturalquestionstoask,andtomakesureyouareaskingallthenecessaryquestionsupfrontinanorganizedwayyouwillfollowastandarddevelopmentprocess.
FollowinganAppDevelopmentProcess
Buildinganappcantakeaslittletimeasanhouroraslongasdecades.Formoststartups,thedevelopmentprocessesfortheinitialproductprototypeaveragesoneortwomonthstocomplete,whereasenterprisedevelopmentprocessesforcommercialgradesoftwaretakessixmonthstoafewyearstocomplete,dependingontheindustryandtheproject’scomplexity.Abriefoverviewoftheentireprocessisdescribedhere,andtheneachstepiscoveredinadditionaldetailasyoubuildtheappforMcDuck’s.
Anappcanbeasoftwareprogramthatrunsondesktopormobiledevices.
Thefourstepsyouwillfollowwhenbuildingyourappare:
PlanninganddiscoveryofapprequirementsResearchingoftechnologyneededtobuildtheapp,anddesigningtheapplookandfeelCodingyourappusingaprogramminglanguageDebuggingandtestingyourcodewhenitbehavesdifferentlythanyouintended
Intotal,youshouldplantospendbetweentwotofivehoursbuildingthisapp.AsshowninFigure10-1,planningandresearchalonewilltakemorethan
halfyourtime,especiallyifthisisthefirsttimeyouarebuildinganapp.Youmightbesurprisedtolearnthatactuallywritingcodewilltakearelativelysmallamountoftime,withtherestofyourtimespentdebuggingyourcodetocorrectsyntaxandlogicerrors.
Appdevelopmentprocesseshavedifferentnames,andthetwobiggestprocessesarecalledwaterfallandagile.Waterfallisasetofsequentialstepsfollowedtocreateaprogram,whereasagileisasetofiterativestepsfollowedtocreateaprogram.AdditionaldiscussioncanbefoundinChapter3.
Figure10-1:Timeallocatedtocompletethefourstepsintheappdevelopmentprocess.
PlanningYourFirstWebApplicationYouoryourclienthasawebappidea,andplanningistheprocessofputtingthoseideasdownonpaper.Documentingallthefeaturesthatwillgointotheappissoimportant,becauseasthecartooninFigure10-2showsforwebdevelopment,andincomputersciencegenerally,itcanbedifficulttounderstandupfrontwhatfeaturesaretechnicallyeasyversusdifficulttoimplement.
Theplanningphasealsofacilitatesanupfrontconversationaroundtime,projectscope,andbudget,whereacommonsayingisto“picktwooutofthe
three.”Insomesituations,suchaswithprojectsforfinancecompanies,timelinesandprojectscopemaybelegallymandatedortiedtoabigclient,andcannotbechanged,andsoadditionalbudgetmayneedtosetasidetomeetboth.Inothersituations,suchasprojectsforsmallstartups,resourcesarescarcesoit’smorecommontoadjusttheprojectscopeorextendthetimelinethantoincreasetheproject’sbudget.Beforewritinganycode,itwillbehelpfultounderstandwhichdimensionscanbeflexedandwhicharefixed.
Finally,althoughyouwilllikelyplaymultiplerolesinthecreationofthiswebapp,inreallifeteamsofpeoplehelpbringtolifethewebappsyouuseeveryday.Youwillseetherolespeopleplay,andhoweveryoneworkstogether.
Figure10-2:Itcanbedifficulttoseparatetechnicallyeasyanddifficultprojects.
ExploringtheOverallProcessThepurposeoftheplanningphaseisto:
Understandtheclientgoals:Someclientsmaywanttobethefirsttoenteranindustrywithanapp,evenifitmeanssacrificingquality.Other
clientsmayrequirethehigheststandardsofquality,reliability,andstability.Similarly,someothersmayprioritizeretainingexistingcustomers,whileotherswanttoattractnewcustomers.Allthesemotivationsaffecttheproductdesignandimplementationinbigandsmallways.
Ifyouareadeveloperinalargecompany,yourclientisusuallynottheenduserbutwhoeverinyourinternalteammustgreenlighttheappbeforeitisreleasedtothepublic.Atmanycompanies,suchasGoogle,Yahoo,andFacebook,mostprojectsdonotpassinternalreviewandareneverreleasedtothepublic.
Documentproductandfeaturerequests:Clientsusuallyhaveanoverallproductvision,alistoftaskstheusermustbeabletocompletewiththeapp.Often,clientshavefeaturesinmindthatwouldhelpaccomplishthosetasks.Agreeondeliverablesandatimeline:Almosteveryclientwillimagineamuchbiggerproductthanyouhavetimetobuild.Foradeveloper,itisextremelyimportanttounderstandwhatfeaturesareabsolutelynecessaryandmustbebuilt,andwhatfeaturesare“nicetohave”ifthereistimeremainingattheendoftheproject.Ifeveryfeatureisa“musthave”youneedtoeitherpushtheclienttoprioritizesomething,ormakesureyouhavegivenyourselfenoughtime.
Estimatingthetimetocompletesoftwareprojectsisoneofthemostdifficultprojectmanagementtasks.Thereisgreatervariabilityanduncertaintythanphysicalconstructionprojects,likebuildingahouse,orintellectualprojects,likewritingamemo.Themostexperienceddevelopersattheworld’sbestsoftwarecompaniesroutinelymissestimates,sodon’tfeelbadifcompletiontakeslongerthanyouthink.Yourestimationskillwillimprovewithtimeandpractice.
Afterseparatingthenecessaryfeaturesfromthe“nicetohave,”youshoulddecidewhichfeaturesareeasyandwhicharecomplex.Without
previousexperiencethismightseemdifficult,butthinkaboutwhetherotherapplicationshavesimilarfunctionality.Youshouldalsotrysearchingthewebforforumposts,orproductsthathavethefeature.Ifnoproductimplementsthefeature,andallonlinediscussionportraythetaskasdifficultitwouldbeworthwhileagreeingup-frontonanalternative.
Discusstoolsandsoftwareyouwillusetocompletetheproject,andyouruserswillusetoconsumetheproject:Takethetimetounderstandyourclientanduser’sworkflowtoavoidsurprisesfromincompatiblesoftware.Websoftwareusuallyworksacrossavarietyofdevices,butolderoperatingsystemsandbrowserscancauseproblems.Definingatthestartoftheprojectexactlywhichbrowserversionsyouwillsupport(suchasInternetExplorer9andlater),andwhichdevices(suchasdesktopandiPhoneonly)willsavedevelopmentandtestingtime.Usually,thesedecisionsarebasedonhowmanyexistingusersareonthoseplatforms,andmanyorganizationswillsupportabrowserversionifusedbyasubstantialamountoftheuserbase—usuallyatleastfivepercent.
Browserincompatibilitiesaredecreasingasthelatestdesktopandmobilebrowsersupdatesthemselves,andarenoweasiertokeepup-to-date.
MeetingthePeopleWhoBringaWebApptoLife
Youwillbeabletocompletetheappinthisbookbyyourself,buttheappsyoubuildatworkoruseeveryday,likeGoogleMapsorInstagram,arecreatedbyteamsofpeople.Teamsforasingleproductcanvaryinsize,reachingupwardsof50people,andeachpersonplaysaspecificroleacrossareaslikedesign,development,productmanagement,andtesting.Insmallercompanies,thesamepersonmayperformmultipleroles,whileatlargercompaniestherolesbecomemorespecializedandindividualpeopleperformeachrole.
CreatingwithdesignersBeforeanycodehasbeenwritten,designersworktocreatethesitelookandfeelthroughlayout,visuals,andinteractions.Designersanswersimplequestionslike“shouldthenavigationalmenubeatthetopofthepageorthebottom?”tomorecomplexquestionslike“howcanweconveyasenseofsimplicity,creativity,andplayfulness?”Ingeneral,designersanswerthesetypesofquestionsbyinterviewingusers,creatingmanydesignsofthesameproductidea,andthenmakingafinaldecisionbychoosingonedesign.Gooddesigncangreatlyincreaseadoptionofaproductoruseofsite,andproductslikeApple’siPhoneandAirbnb.com.(SeeFigure10-3.)
Whenbuildingawebsiteorapp,youmaydecideyouneedadesigner,butkeepinmindwithindesigntherearemultiplerolesthatdesignersplay.Thefollowingrolesarecomplementary,andmayallbedonebyonepersonorbyseparatepeople:
Userinterface(UI)anduserexperience(UX)designersdealprimarilywith“lookandfeel”andwithlayout.Whenyoubrowseawebsite,forexampleAmazon,youmaynoticethatacrossallpagesthenavigationmenus,andcontentareinthesameplace,anduseidenticalorverysimilarfont,buttons,inputboxes,andimages.TheUI/UXdesignerthinksabouttheorderinwhichscreensaredisplayedtotheuser,alongwithwhereandhowtheuserclicks,enterstext,andotherwiseinteractswiththewebsite.IfyoueavesdroppedonUI/UXdesigners,youmayhearconversationlike,“hispageistoobusywithtoomanycalltoactions.Ourusersdon’tmakethismanydecisionsanywhereelseonthesite.Let’ssimplifythelayoutbyhavingjustasingleBuybuttonsoanyonecanorderinjustoneclick.”Visualdesignersdealprimarilywithcreatingthefinalgraphicsusedonawebsite,andistherolemostcloselyassociatedwith“designer”.Thevisualdesignercreatesfinalversionsoficons,logos,buttons,typography,images.Forexample,lookatyourInternetbrowser—thebrowsericon,theBack,Reload,andBookmarkbuttonsareallcreatedbyavisualdesigner,andanyoneusingthebrowserforthefirsttimewillknowwhattheiconsmeanwithoutexplanation.Ifyoueavesdroppedonvisualdesigners,youmayhearconversationlike,“Thecolorcontrastontheseiconsistoolighttobereadable,andifincludingtextwiththeicon,let’s
center-alignthetextbelowtheiconinsteadofaboveit.”Interactiondesignersdealprimarilywithinteractionsandanimationsbasedonuserinputandsituation.Initially,interactiondesignwerelimitedtokeyboardandmouseinteractions,buttodaytouchsensorsonmobiledeviceshavecreatedmanymorepotentialuserinteractions.Theinteractiondesignerthinksabouthowtousethebestinteractionsotheuserisabletocompleteataskaseasilyaspossible.Forexample,thinkabouthowyoucheckyouremailonyourmobilephone.Formanyyears,thetraditionalinteractionwastoseealistofmessages,clickonamessage,andthenclickonabuttontoreply,flag,folder,ordeletethemessage.In2013,interactiondesignersrethoughttheemailappinteraction,andcreatedaninteractionsouserscouldswipetheirfingerleftorrighttodeleteorreplytoemailmessagesinsteadofhavingtoclickthroughmultiplemenus.Ifyoueavesdroppedoninteractiondesigners,youmayhearconversationlike,“Whileusersarenavigatingwithourmapsapp,insteadoflettingusknowtheyarelostbyclickingorswiping,maybetheycanshakethephoneandweinstantlyhavealocationspecialistcallthem.”
Figure10-3:JonathanIve,SVPofDesignatApple,iscreditedforApple’sdesignsuccesses.
Ifcreatinganappwaslikemakingamovie,designerswouldbe
screenwriters.
Codingwithfront-andback-enddevelopersAfterthedesigniscomplete,thefront-endandback-enddevelopersmakethosedesignsareality.Front-enddevelopers,suchasMarkOttoandJacobThornton(seeFigure10-4),codeinHTML,CSS,andJavaScript,andconvertthedesignintoauserinterface.Thesedeveloperswritethesamecodethatyouhavebeenlearningthroughoutthisbook,andensurethewebsitelooksconsistentacrossdevices(desktop,laptop,andmobile),browsers(Chrome,Firefox,Safari,andsoon),andoperatingsystems(Windows,Mac,andsoon).Allthesefactors,especiallyincreasedadoptionofmobiledevice,resultinthousandsofcombinationsthatmustbecodedforandtestedbecauseeverydevice,browser,andoperatingsystemrendersHTMLandCSSdifferently.
Figure10-4:MarkOttoandJacobThorntoncreatedBootstrap,themostpopularfront-endframework.
Ifcreatinganappwaslikemakingamovie,front-enddeveloperswouldbethestarringactors.
Back-enddeveloperssuchasYukihiroMatsumoto(seeFigure10-5)addfunctionalitytotheuserinterfacecreatedbythefront-enddevelopers.Back-enddevelopersensureeverythingthat’snotvisibletotheuserandbehindthescenesisinplacefortheproducttoworkasexpected.Back-enddevelopersuseserver-sidelanguageslikePython,PHP,andRubytoaddlogicaroundwhatcontenttoshow,when,andtowhom.Inaddition,theyusedatabasestostoreuserdata,andcreateserverstoserveallofthiscodetotheusers.
Ifcreatinganappwaslikemakingamovie,back-enddeveloperswouldbethecinematographers,stuntcoordinators,makeupartists,andsetdesigners.
Figure10-5:YukihiroMatsumotocreatedRuby,apopularserver-sidelanguageusedtocreatewebsites.
ManagingwithproductmanagersProductmanagershelpdefinetheproducttobebuilt,andmanagetheproductdevelopmentprocess.Whenengineeringteamsaresmall(suchasfifteenpeopleorless)communication,roles,andaccountabilityareeasilymanagedinternallywithoutmuchformaloversight.Asengineeringteamsgrows,theoverheadofeveryonecommunicatingwitheachotheralsogrows,andwithoutsomeprocesscanbecomeunmanageable,leadingtomiscommunicationandmisseddeadlines.Productmanagersservetolessenthecommunicationoverhead,andwhenissuesariseasproductsarebeingbuiltdecidewhethertoextendtimelines,cutscope,oraddmoreresourcestotheteam.Productmanagersareoftenformerengineers,whohaveanaturaladvantageinhelpingsolvetechnicalchallengesthatarise,butnon-technicalpeoplearealsoassumingtherolewithsuccess.Usually,noengineersreporttotheproductmanager,causingsometocommentthatproductmanagershave“alloftheresponsibility,andnoneoftheauthority.”OneproductmanagerwieldinggreatresponsibilityandauthorityisSundarPichai,whooriginallywasaproductmanagerfortheGoogletoolbar,andrecentlywasappointedtooverseemanyofGoogle’sproducts,includingsearch,Android,Chrome,maps,ads,andGoogle+.(SeeFigure10-6.)
Figure10-6:SundarPichaioverseesalmosteverymajorGoogleproduct.
TestingwithqualityassuranceTestingisthefinalstepofthejourneyafteranapporwebsitehasbeenbuilt.Asaresultofthemanyhandsthathelpedwithproduction,thenewlycreatedproductwillinevitablyhavebugs.Listsaremadeofallthecoreappusertasksandflows,andhumantestersalongwithautomatedprogramsgothroughthelistoverandoveragainondifferentbrowsers,devices,andoperatingsystemstofinderrors.Testerscompilethenewlydiscoveredbugs,andsendthembacktothedevelopers,whoprioritizewhichbugstosquashfirst.Trade-offsarealwaysmadebetweenhowmanyusersareaffectedbyabug,thetimeittakestofixthebug,andthetimeleftuntiltheproductmustbereleased.Themostimportantbugsarefixedimmediately,andminorbugsarescheduledtobefixedwithupdatesorlaterreleased.Today,companiesalsorelyonfeedbacksystemsandcollecterrorreportsfromusers,withfeedbackformsandinsomecasesthroughautomatedreporting.
Chapter11ResearchingYourFirstWeb
ApplicationInThisChapter
Dividinganappintosmallerpieces,orstepsUsingcodefromvarioussourcestoperformthosestepsCreatingappdesignsbyreviewingandimprovinguponexisting
solutions
Ifweknewwhatitwasweweredoing,itwouldnotbecalledresearch.—AlbertEinstein
Withthebasicrequirementsdefined,thenextstepisresearchinghowtobuildtheapplication.Appsconsistoftwomainparts:functionalityandform(design).Foreachoftheseparts,youmust:
Dividetheappintosteps:Althoughit’sgoodpracticetodivideanythingyouaregoingtobuildintosteps,divingappsintomanageablepiecesisanabsolutenecessityforlargesoftwareprojectswithmanypeopleworkingacrossmultipleteams.Researcheachstep:Whendoingyourresearch,thefirstquestiontoaskiswhetheryoumustbuildasolutionyourselforuseanexistingsolutionbuiltbysomeoneelse.Buildingyourownsolutionusuallyisthebestwaytodirectlyaddressyourneed,butittakestime,whereasimplementingsomeoneelse’ssolutionisfastbutmayonlymeetpartofyourneeds.Chooseasolutionforeachstep:Youshouldhaveallthesolutionsselectedbeforewritinganycode.Foreachstep,decidewhetheryouarewritingyourowncode,orusingpre-builtcode.Ifyouarenotwritingthecodeyourself,compareafewoptionssoyoucanpickonewithconfidence.
DividingtheAppintoStepsThebiggestchallengewithdividinganappintostepsisknowinghowbigorsmalltomakeeachstep.Thekeyistomakesureeachstepisdiscreteandindependent.Totestwhetheryouhavetherightnumberofsteps,askyourselfifsomeoneelsecouldsolveandcompletethestepwithminimalguidance.
Findingyourapp’sfunctionalityRecallthatMcDuck’swantstopromoterestaurantvisitsbyusingawebapplicationthatsendscustomersanofferorcouponifthey’reclosetoarestaurant.Tomakethisjobeasier,youaretocreatetheappforcustomersvisitingjustonestore.
Yourfirstmoveistobreakdownthisappintostepsneededfortheapptofunction.Thesestepsshouldnotbetoospecific:Thinkoftheminbroadterms,asifyouwereexplainingtheprocesstoakindergartner.Withapenandpaper,writedownthesestepsinorder.Don’tworryaboutwhethereachstepiscorrect,asyourskillwillimprovewithpracticeandtime.Tohelpyoustart,herearesomeclues:
AssumetheMcDuck’sappactivateswhenthecustomerpressesabuttonintheapptocheck-intoastore.Whenthebuttonispressed,whatarethetwolocationsthattheappmustbeawareof?Whentheappisawareofthesetwolocations,whatcalculationinvolvingthesetwolocationsmustthecomputermake?Aftercomputingthiscalculation,whateffectwillthecomputershow?
Filloutyourlistnow,anddon’tcontinuereadinguntilyou’vecompletedit.
Findingyourapp’sfunctionality:MyversionThefollowingismyversionofthestepsneededtomaketheappfunctionaccordingtoMcDuck’sspecifications.Mystepsmaydifferfromyours,ofcourse,andthisvariationiscompletelyfine.Theimportantlessonhereisthatyouunderstandwhyeachofthesestepsisnecessaryfortheapptowork:
1. Thecustomerpressesabuttonontheapp.
Theinstructionsabovesaidtoinitiatetheappwiththepressofabutton.Thatbeingsaid,therearetwootheroptionsforlaunchingtheapp:
Executingthestepscontinuouslyinthebackground,regularlycheckingthecustomer’slocation.Currently,thistechniqueplacesaheavydrainonthebattery,andisnotusuallyrecommended.Executingthestepsonlywhenthecustomeropenstheapp.
2. Afterthebuttonispressed,findthecustomer’scurrentlocation.
Thecustomer’slocationisoneofthetwolocationsyouneedtoidentify.Thecustomer’scurrentlocationisnotfixed,anditchanges,forexample,whenthecustomeriswalkingordriving.
3. FindthefixedlocationofaMcDuck’sstore.
TheMcDuck’srestaurantlocationistheotherlocationyouneedtoidentify.Becausethisisapilot,youonlyneedtoidentifythelocationforoneMcDuck’srestaurant,afixedlocationthatwillnotchange.Hypothetically,assumingthatthepilotissuccessfulandthatMcDuck’swantstoimplementthisappforusersvisitingall35,000restaurants,you’dhavetotrackmanymorerestaurantlocations.Additionally,inalargerrolloutthelocationswouldneedtobeupdatedregularly,asnewrestaurantsopen,andasexistingrestaurantsmoveorclose.
4. Calculatethedistancebetweenthecustomer’scurrentlocationandtheMcDuck’srestaurant,andnamethisdistanceCustomerDistance.
ThisstepcalculateshowfarawaythecustomerisfromtheMcDuck’srestaurant.Onecomplexitytobeawareof—butnottoworryaboutrightnow—isthedirectioninwhichthecustomerismoving.AlthoughMcDuck’sdidnotspecifywhethertheywanttodisplayofferstocustomersheadingbothtowardandawayfromtheirstore,thismaybeaquestionworthaskinganyway.
5. ConvertfivetotenminutesofcustomertravelintoadistancecalledThresholdDistance.
McDuck’sCEODuckCorleonewantstotargetcustomerswhoarefivetotenminutesawayfromthestore.Distance,inthissense,canbemeasuredinbothtimeandinunitsofdistancesuchasmiles.Forconsistency,however,plantoconverttimeintodistance—translatethosefivetotenminutesintomiles.Thenumberofmilestraveledinthistimewillvarybycommonmodeoftransportationandbylocation,becausefivetotenminutesoftravelinNewYorkCitywon’tgetyouasfarasfivetotenminutesoftravelinHouston,Texas.
6. IftheCustomerDistanceislessthantheThresholdDistance,thenshowanoffertothecustomer.
FollowingMcDuck’sspecifications,theappshouldattractcustomerstocometothestore,andsotheapponlyshowsofferstocustomerswhoareclosetotherestaurant.Anothercomplexitytobeawareof—butnottoworryaboutrightnow—isthattheCustomerDistancecanchangequickly.CustomerstravelingbycarcouldeasilybeoutsidetheThresholdDistanceoneminuteandinsideitthenext.Figure11-1showsthecustomerswewanttotarget,relativetoafixedrestaurantlocation.
Figure11-1:Customerswewanttotargetbasedonafixedrestaurantlocation.
Manysoftwarelogicmistakeshappenatthisstage,becausetheprogrammerforgetstoincludeastep.Takeyourtimereviewingthese
stepsandunderstandingwhyeachstepisessential,andwhythislistofstepsistheminimumnecessarytooperatetheapp.
Findingyourapp’sformAfteryousettleonwhattheappwilldo,youmustfindthebestwaytopresentthisfunctionalitytousers.Therearemanywaysthatuserscaninteractwithyourapp’sfunctionality,sopickingouttherightapproachcanbetricky.Designinganappcanbefunandrewarding,butit’shardwork.Afterthefirstiterationofanapp’sdesign,developersareoftendisappointed:Userswillrarelyusetheproductasintendedandwillfindmanypartsoftheappconfusing.Thisisnatural—especiallybecauseatthisstageyou’reoftencreatingsomethingorhavingtheuserdosomethingthathasn’tbeendonebefore.Youronlychoiceistokeeptrying,tokeeptesting,modifying,andcreatingnewdesignsuntilyourappiseasyforeveryonetouse.AlthoughtheiPodisahardwareproduct,theapproachAppletooktoperfectitisbasicallythesame.Figure11-2showshowthedesigncanchangeovertime,withthebuttonlayoutchangingfromtheoriginalclick-wheeltoindividualhorizontalbuttons,andfinallybacktotheclick-wheelagain.
Figure11-2:Apple’siPoddesignchangesovermultipleproductreleases.
Thefollowinglistdescribesabasicdesignprocesstocreatethelookandfeelofyourapp:
1. Definethemaingoalsofyourapp.
Ifyouwereataparty,andyouhadtoexplainwhatyourappdidinonesentence,whatwoulditbe?Someappshelpyouhailataxi,reserveatableatarestaurant,orbookaflight.Famously,thegoalfortheiPodwas1,000songsinyourpocketaccessiblewithinthreeclicks,whichhelpedcreateaneasytouseuserinterface.Anexplicitlydefinedgoalwillserveasyournorthstar,helpingyoutoresolvequestionsandforcingyoutokeeptrying.
2. Breakthesegoalsintotasks.
Eachgoalisthesumofmanytasks,andlistingthemwillhelpyoudesigntheshortestpathtocompletingeachtaskandultimatelythegoal.Forinstance,ifyourapp’sgoalisforausertobookaflight,thentheappwilllikelyneedtorecorddesiredflyingtimesanddestinations,searchandselectflightsdepartingduringthosetimes,recordpersonalandpaymentinformation,presentseatsforselection,andconfirmpaymentoftheflight.Sometimesdesignerswillsegmenttasksbyuserpersona,anothernameforthepersoncompletingthetask.Forexample,thisappmaybeusedbybusinessandleisuretravelers.Leisuretravelersmayneedtodoheavysearchingandpickflightsbasedonprice,whilebusinesstravelersmostlyrebookcompletedflightsandpickflightsbasedonschedule.
3. Researchtheflowsandinteractionsnecessarytoaccomplishthesetasks.
Forexample,ourflightapprequirestheusertoselectdatesandtimes.Oneimmediatequestioniswhetherthedateandtimeshouldbetwoseparatefieldsoronefield,andonadifferentorsamescreenasthedestination.Trytosketchwhatfeelsintuitiveforyou,andresearchhowothershavesolvedthisproblem.YoucanuseGoogletofindothertravelapps,listallthevariousdesigns,andeitherpickorimproveuponthedesignyoulikebest.Figure11-3showstwodifferentapproachestoflightsearch.Similarly,youcanalsousedesign-centricsites,suchaswww.dribbble.com,tosearchdesignerportfoliosforfeaturesandcommentary.
Figure11-3:DifferentdesignsforflightreservationfromHipmunk.comandUnitedAirlines.
4. Createbasicdesigns,calledwireframes,andcollectfeedback.
Wireframes,asshowninFigure11-4,arelowfidelitywebsitedrawingswhichshowstructurallyhowsitecontentandinterfaceinteract.Wireframesaresimpletocreate,butshouldhaveenoughdetailtoelicitfeedbackfromothers.Manywireframetoolsuseasimplealmostpencil-likedrawingtohelpanyoneprovidingcommentstofocusonthestructuralandbiggerpicturedesign,insteadofsmallerdetailslikebuttoncolorsorborderthicknesses.Feedbackatthisstagetorefinedesignissoimportantbecausethefirstwireframelikelydoesnotaddressusers’mainconcernsandovercomplicatesthetasksauserneedstodo.
Withmobiledevicesincreasinginpopularityrelativetodesktopdevices,remembertocreatemobileanddesktopversionsofyourwireframes.
Figure11-4:Awireframeforanemailclient.
5. Createmock-upsandcollectmorefeedback.(SeeFigure11-5.)
Afteryouhavefinishedtalkingtoyourclientandtousers,itistimetocreatemock-ups,whicharehighfidelitywebsitepreviews.Thesedesignshaveallthedetailsadeveloperneedstocreatethewebsiteincludingfinallayout,colors,images,logos,andsequencesofscreenstoshowwhentheuserinteractswiththewebpage.Aftercreatingamock-up,plantocollectmorefeedback.
Figure11-5:Amock-upforanemailclient.
Collectingfeedbackateverystageofthedesignprocessmightseemunnecessary,butitismucheasiertoexploredifferentdesignsandmakechangesbeforeanycodehasbeenwritten.
6. Sendthefinalfiletothedevelopers.
Afterthemock-uphasbeencreatedandapproved,youtypicallysendafinalimagefiletothedeveloper.AlthoughthisfilecouldbeinanyimagefileformatlikePNGorJPG,themostpopularfileformatusedby
designersisPSD,createdusingAdobePhotoshop.
Findingyourapp’sform:TheMcDuck’sOfferAppdesignInthissectionyoufollowthedesignprocessdescribedintheprevioussectiontocreateasimpledesignfortheMcDuck’sOfferapp.Aspartofthedesign,youshoulddothefollowingthings:
1. Definethemaingoalsofyourapp.
ThemaingoalforMcDuck’sistouseofferstoattractcustomerstorestaurants.
2. Breakthesegoalsintotasks.
Customersneedtoviewtheoffer,navigatetothestore,andusetheoffer.
3. Researchtheflowsandinteractionsneededtoaccomplishthesetasks.
Becausethisisthefirstiterationoftheapp,let’sfocusonjustallowingthecustomertoviewtheoffer.
OnefunctionthatMcDuck’sdidnotspecifyistheabilitytosavesingle-usecouponsandtosharegeneral-usecoupons.However,whenlookingatotherapps,liketheonesinFigure11-6,theneedforthisbecomesmoreobvious.Also,somesimilarappsallowthecustomertospendmoneytobuycoupons—maybethisfunctionalityshouldbeaddedaswell.ThesequestionswouldbegreattopresenttoMcDuck’slater.
Figure11-6:Exampleflowfromdealsandofferappscurrentlyinthemarket.
TheappsinFigure11-6alsoalldisplayvarious“calltoaction”buttonstotheuserbeforedisplayingthedeal.Someappsasktheusertocheck-into
alocation,otherappsasktheusertopurchasethecoupon,andstillothersshowacollectionofnewortrendingcouponstoday.
Fornow,andtokeepthingssimple,let’sassumethatourMcDuck’sapphasabuttonthatallowscustomerstocheck-intotheirfavoriteMcDuck’slocation,andwhenclickedwithinthetargetdistancetheappdisplaysageneral-usecouponthatcustomersreceiveforfree.
4. Createbasicdesigns,calledwireframes,andcollectfeedback.
Asampledesignfortheapp,basedonthelookandfeelofotherapps,appearsinFigure11-7.
Figure11-7:AsamplewireframefortheMcDuck’sofferapp.
5. Createmock-upsandcollectmorefeedback.
Ordinarily,youwouldcreatemock-ups,whicharemorepolisheddesignswithrealimages,fromthewireframesandpresentthemtocustomersforfeedback.Inthiscase,however,theappissimpleenoughthatyoucanjuststartcoding.
IdentifyingResearchSourcesNowthatyouknowwhatyourappwilldo,youcanfocusonhowyourappwilldoit.Afterbreakingdownyourappintosteps,yougoovereachsteptodeterminehowtoaccomplishit.Formorecomplicatedapps,developersfirstdecidewhichofthesetwomethodsisthebestwaytocompleteeachstep:
Buildingcodefromscratch:Thisisthebestoptionifthefunctionalityinaparticularstepisuniqueorstrategicallyimportant,anareaofstrengthfortheapp,andexistingsolutionsareexpensiveornon-existent.Withthisoption,youanddeveloperswithinthecompanywritethecode.Buyingorusingapre-existingsolution:Thisisthebestoptionifthefunctionalityinaparticularstepiscommon,non-coretechnicalareafortheapp,andexistingsolutionsarecompetitivelypriced.Withthisoption,youanddevelopersworkingontheappusecodewrittenbyexternalthirdpartydevelopers.
Onecompanythatrecentlymadethisdecision—publiclyandpainfully—isApplewithitsMapsproduct.In2012,afteryearsofusingGoogleMapsonitsmobiledevices,Appledecidedtointroduceitsownmapsapplicationthatithadbeendevelopingfortwoyears.AlthoughtheMapsproductApplebuiltinternallyturnedouttoinitiallybeafailure,Appledecidedtobuilditsownmappingapplicationbecauseitviewedmappingcapabilitiesasstrategicallyimportantandbecauseturn-by-turnnavigationsolutionswerenotavailableinthesolutionprovidedbyGoogle.
Whetheryou’rebuildingorbuying,researchisyournextstep.Herearesomesourcestoconsiderwhenresearching:
Searchengines:UseGoogle.comoranothersearchenginetotypeinwhatyouaretryingtoaccomplishwitheachstep.Onechallengecanbediscoveringhowthetaskyou’retryingtoachieveisreferredtobyprogrammers.Forinstance,ifIwanttofindmycurrentlocation,Imightentershowmylocationinanappintoasearchengine,butthisresultsinalistoflocation-sharingapps.Afterreadingafewofthetoptenresults,Iseethatlocation-trackingisalsoreferredtoasgeolocation.WhenIsearchagainforgeolocationthetopresultsincludemanyexamplesofcodethatshowsmycurrentlocation.
Formoregenericsearchesforcodeexamples,tryincludingthenameofthecomputerlanguageandthewordsyntax.Forexample,ifyouwanttoinsertanimageonawebpage,searchforimagehtmlsyntaxtofindcodeexamples.
Priorcommercialandopen-sourceapps:Examininghowothersbuilttheirappscangiveyouideasonhowtoimproveuponwhatalreadyexists,andinsightintopushingexistingtechnologytothelimittoachieveaninterestingeffect.Forinstance,sayyouwantedtobuildamobileappthatrecognizedTVadsfromthe“audiofingerprint”ofthoseadsanddirectedviewerstoaproductpageonamobiledevice.Tocreatethisapp,youcouldbuildyourownaudiofingerprintingtechnology,whichwouldlikelytakemonthsorlongertobuild,oryoucouldpartnerwithShazam,acommercialapplication,orEchoprint,anopen-sourcemusicfingerprintingservice.Eitherappcanrecorda10to20-secondaudiosample,createadigitalfingerprintafterovercomingbackgroundnoiseandpoormicrophonequality,comparethefingerprinttolargeaudiodatabase,andthenreturnidentificationinformationfortheaudiosample.Industrynewsandblogs:Traditionalnewspapers,liketheWallStreetJournal,andtechblogs,likeTechCrunch.com,reportonthelatestinnovationsintechnology.Regularlyreadingorsearchingthroughthesesitesisagoodwaytofindotherswhohavelaunchedappsinyourspace.APIdirectories:YoucaneasilysearchthousandsofAPIsforthefunctionalityyouneedtoimplement.Forexample,ifyouwerecreatinganappthatusedfacerecognitioninsteadofapassword,youcouldsearchforfacedetectionAPIsanduseanAPIyoufindinsteadoftryingtobuildafacedetectionalgorithmfromscratch.PopularAPIdirectoriesincludewww.programmableweb.comandwww.mashape.com.
AsdiscussedinChapter9,APIsareawayforyoutorequestandreceivedatafromotherprogramsinastructured,predictable,documentedway.
User-generatedcodingwebsites:Developersindifferentcompaniesfrequentlyfacethesamequestionsonhowtoimplementfunctionalityforfeatures.Communitiesofdevelopersonlinetalkaboutsharedproblemsandcontributecodesoanyonecanseehowtheseproblemshavebeensolvedinthepast.Youcanparticipateindeveloperconversationandseethecodeotherdevelopershavewrittenbyusingwww.stackoverflow.comandwww.github.com.
ResearchingtheStepsintheMcDuck’sOfferApp
ToimplementthefunctionalityintheMcDuck’sOfferapp,youbrokedowntheappintosixstepsusingplainEnglish.Now,researchhowyoucanconvertthosestepsintocodeusingtheresourceslistedintheprevioussection.YourappwillrequireHTMLtoputcontentonthepage,CSStostylethatcontent,andJavaScriptforthemoreinteractiveeffects.Doyourbesttoresearcheachofthestepsonyourown,writedowntheanswers,andthenlookoverthesuggestedcodeinthenextsection:
“Thecustomerpressesabuttonontheapp”:Thiscodecreatesabuttonthattriggerseverysubsequentstep.Creatingabuttononawebpageisaverycommontask,sotonarrowdowntheresultssearchforhtmlbuttontag.Reviewsomeofthelinksinthetop10searchresults,andthenwritedowntheHTMLtagsyntaxtocreateabuttonthatsays“McDuck’sCheck-in.”
Inyoursearchresults,siteslikew3schools.comaredesignedforbeginners,andwillincludeexamplecodeandsimpleexplanations.
“Afterthebuttonispressed,findthecustomer’scurrentlocation:”Inweblingo,findingauser’slocationiscalledgeolocation.IwillprovideyouwithJavaScriptgeolocationcode,alongwithanexplanationforhowitworksandwhereIfoundit.TotriggerthisJavaScriptcode,youneedtoaddanattributetotheHTMLbuttontagtocallaJavaScriptfunctionnamedgetlocation().
AsdescribedinChapter4,HTMLattributesareinsertedintheopeningHTMLtag.
SearchforhtmlbuttonjavascriptbuttononclicktofindouthowtoinserttheonclickattributetoyourbuttonHTMLcode.Reviewthesearch
results,andthenwritedowntheHTMLsyntaxforyourbuttoncode.
“FindthefixedlocationofaMcDuck’sstore:”You’llneedareal-worldaddresstoserveastheMcDuck’sstore.Useamappingapplicationlikemaps.google.comtofindthestreetaddressofaburgerrestaurantnearyou.Computerstypicallyrepresentphysicaladdressesusinglatitudeandlongitudenumbersinsteadofstreetaddresses.Youcansearchforwebsitesthatconvertstreetaddressesintolatitudeandlongitudenumbers,orifyou’reusingGoogleMaps,youcanfindthenumbersintheURL,asshowninFigure11-8.Thefirstnumberafterthe@signanduptothecommaisthelatitude,andthesecondnumberbetweenthetwocommasisthelongitude.Figure11-8showsaMcDonald’sstoreinNewYorkCity,andthelatitudeis40.7410344,andthelongitudeis–73.9880763.
Figure11-8:LatitudeandlongitudeofaMcDonald’sinNewYorkCity.
Trackdownthelatitudeandlongitudenumbersfortheburgerrestaurantofyourchoice,uptosevendecimalplaces,andwritethemdownonapieceofpaper.
Includeanegativesignifyouseeone,andallsevendecimal
placesforthegreatestaccuracy.
“Calculatethedistancebetweenthecustomer’scurrentlocationandtheMcDuck’srestaurant,andnamethisdistanceCustomerDistance”:Latitudeandlongitudearecoordinatesthatrepresentalocationonasphere.ThedistancealongthesurfaceofthespherebetweentwosetsoflatitudeandlongitudecoordinatesiscalculatedusingtheHaversineformula.YoucanfindaJavaScriptversionoftheformulaatstackoverflow.com/questions/27928/how-do-i-calculate-distance-between-two-latitude-longitude-points.ThisistheformulayouwillusetocalculatedistancewhencreatingtheMcDuck’sapp,andIwillincludethiscodeforyou.
Don’tgetboggeddowninthedetailsofhowtheHaversineformulaworks.Abstractionisanimportantconcepttorememberwhenprogramming,andthisbasicallymeansthataslongasyouunderstandtheinputstoasystem,andtheoutputs,youdon’treallyneedtounderstandthesystemitself,muchasyoudon’tneedtounderstandthemechanicsoftheinternalcombustionengineinordertodriveacar.
“ConvertfivetotenminutesofcustomertravelintoadistancecalledThresholdDistance”:Usingthemostcommonmethodoftransportationinyourcurrentcity,writedownthenumberofmilesyoucouldyoutravel,onaverage,infivetotenminutes.“IftheCustomerDistanceislessthantheThresholdDistancethenshowanoffertothecustomer”:Thetwopiecestoresearchforthissteparetheconditionalstatementthatdecideswhentoshowtheoffertotheconsumer,andtheactualoffer:
Theconditionalstatement:ThisiswritteninJavaScriptusinganif-elsestatement.Ifthecustomeriswithinthethresholddistance,thenitshowstheoffer;otherwise(else)itshowsanothermessage.Toreviewtheif-elsesyntax,searchGoogleoranothersearchengineforJavaScriptif-elsestatementsyntax(orrefertoChapter9toreviewthecoverageoftheif-elsestatement
syntaxthere).Theoffertoshowtotheconsumer:TheeasiestwaytoshowanofferistousetheJavaScriptalert().SearchforJavaScriptalertsyntax.
Afteryou’veconductedyoursearches,writedownyourif-elsestatementwithatextalert()forafreeburgerifthecustomeriswithintheThresholdDistance,andatextalert()notifyingthecustomertheyhavecheckedin.
Whenyouhavetheif-elsestatementworking,youcanreplacethetextalert()withanimage.Searchhttp://images.google.comforaburgercouponimage.Afteryoufindtheimage,left-clickonitfromtheimagegridinthesearchresults,andleft-clickagainonViewImagebutton.WhentheimageloadsthedirectlinktotheimagewillbeintheURLaddressbarinthebrowser.ThecodetoinserttheimageisshowninChapter4.
ChoosingaSolutionforEachStepWithyourresearchfinished,it’stimetofindthebestsolution.Ifmultiplesolutionsexistforeachstep,younowneedtochooseone.Tohelpyouchoose,weigheachofyourmultiplesolutionsacrossavarietyoffactors,suchasthese:
Functionality:Willthecodeyouwriteorpre-builtsolutionyoufounddoeverythingyouneed?Documentation:Istheredocumentationforthepre-builtsolution,likeinstructionsoramanual,thatiswellwrittenwithexamples?Communityandsupport:Ifsomethinggoeswrongwhilewritingyourcode,isthereacommunityyoucanturntoforhelp?Similarly,doesthepre-builtsolutionhavesupportoptionsyoucanturntoifneeded?Easeofimplementation:Isimplementationassimpleascopyingafewlinesofcode?Orisamorecomplexsetuporaninstallationofother
supportingsoftwarenecessary?Price:Everysolutionhasaprice,whetheritisthetimespentcodingyourownsolutionorthemoneypaidforsomeoneelse’spre-builtcode.Thinkcarefullyaboutwhetheryourtimeormoneyismoreimportanttoyouatthisstage.
ThefollowingaresuggestedsolutionsforthepreviousMcDuck’sOfferappresearchquestions.Youranswersmayvary,sorevieweachanswertoseewhereyourcodediffersfrommine:
“Thecustomerpressesabuttonontheapp”:TheHTMLtagsyntaxtocreateabuttonthatsays“McDuck’sCheck-in”is:
<button>McDuck'sCheck-in</button>
ThesyntaxforanHTMLbuttonisavailableherewww.w3schools.com/tags/tag_button.asp.
“Afterthebuttonispressed,findthecustomer’scurrentlocation”:TheHTMLsyntaxforyourbuttoncodeis:
<buttononclick="getLocation()">McDuck'sCheck-in</button>
ThesyntaxforcallingaJavaScriptfunctionbypressingabuttonisavailableherewww.w3schools.com/jsref/event_onclick.asp.
“FindthefixedlocationofaMcDuck’sstore”:IpickedaMcDonald’sstoreinNewYorkCitynearMadisonSquareParkwhoselatitudeis40.7410344andlongitudeis–73.9880763.Thelatitudeandlongitudeforyourrestaurant,ofcourse,willlikelydiffer.“Calculatethedistancebetweenthecustomer’scurrentlocationandtheMcDuck’srestaurant,andnamethisdistanceCustomerDistance”:ThefollowingistheactualcodefortheHaversineformula,
usedtocalculatethedistancebetweentwolocationcoordinates,foundonStackoverflowatstackoverflow.com/questions/27928/how-do-i-calculate-distance-between-two-latitude-longitude-points,Imodifiedthiscodeslightlysothatitreturnedmilesinsteadofkilometers:
functiongetDistanceFromLatLonInKm(lat1,lon1,lat2,lon2){varR=6371;//RadiusoftheearthinkmvardLat=deg2rad(lat2-lat1);//deg2radbelowvardLon=deg2rad(lon2-lon1);vara=Math.sin(dLat/2)*Math.sin(dLat/2)+Math.cos(deg2rad(lat1))*Math.cos(deg2rad(lat2))*Math.sin(dLon/2)*Math.sin(dLon/2);varc=2*Math.atan2(Math.sqrt(a),Math.sqrt(1-a));vard=R*c*0.621371;//Distanceinmilesreturnd;}
functiondeg2rad(deg){returndeg*(Math.PI/180);}
Anexplanationofhowthisformulaworksisoutsidethescopeofthisbook,butmakesureyouunderstandtheformula’sinputs(latitudeandlongitude)andtheoutput(distancebetweentwopointsinmiles).
“ConvertfivetotenminutesofcustomertravelintoadistancecalledThresholdDistance”:InNewYorkCity,peopleusuallywalk,sotravelingforfivetotenminuteswouldtakeyou0.5miles,whichismyThresholdDistance.“IftheCustomerDistanceislessthantheThresholdDistance,thendisplayanoffertothecustomer”:Thesyntaxfortheif-elsestatementwiththetwotextalert()methodsis:
If(distance<0.5){alert("Yougetafreeburger");}else{alert("Thanksforcheckingin!");}
ThesyntaxforaJavaScriptif-elsestatementisavailableatwww.w3schools.com/js/js_if_else.asp.
Chapter12CodingandDebuggingYourFirst
WebApplicationInThisChapter
Reviewingcodetoseepre-existingfunctionalityWritingcodebyfollowingstepstocreateyourappDebuggingyourcodebylookingforcommonsyntaxerrors
Talkischeap.Showmethecode.—LinusTorvalds
Itmaynotfeellikeit,butyou’vealreadydonethemajorityofworktowardcreatingyourfirstwebapplication.Youpainfullybrokedownyourappintosteps,andresearchedeachsteptodeterminefunctionalityanddesign.AsLinusTorvalds,creatoroftheLinuxoperatorsystem,said,“Talkischeap.”Solet’sstartactuallycoding.
GettingReadytoCodeBeforeyoustartcoding,doafewhousekeepingitems.First,ensurethatyouaredoingallofthefollowing:
UsingtheChomebrowser:DownloadandinstallthelatestversionofChome,asitoffersthemostsupportforthelatestHTMLstandards,andisavailablefordownloadatwww.google.com/chrome/browser.
Workingonadesktoporlaptopcomputer:Althoughitispossibletocodeonamobiledevice,itcanbemoredifficultandalllayoutsmaynotappearproperly.Rememberingtoindentyourcodetomakeiteasiertoread:Onemainsourceofmistakesisforgettingtocloseatagorcurlybrace,and
indentingyourcodewillmakespottingtheseerrorseasier.Rememberingtoenablelocationservicesonyourbrowserandcomputer:ToenablelocationserviceswithinChrome,clickonthesettingsicon(3horizontallinesonthetoprightofthebrowser),andclickonSettings.ThenclickontheSettingstab,andatthebottomofthescreenclickon“ShowAdvancedsettings…”UnderthePrivacymenuheading,clickon“Contentsettings…”andscrolldowntoLocationandmakesurethat“Askwhenasitetriestotrackyourphysicallocation”isselected.Youcanreadmoreheresupport.google.com/chrome/answer/142065.
ToenablelocationservicesonaPCnoadditionalsettingisnecessary,butonaMacusingOSXMountainLionorlater,fromtheApplemenuchooseSystemPreferences,thenclickontheSecurity&Privacyicon,andclickthePrivacytab.Clickthepadlockicononthelowerleft,andselectLocationServices,andcheckEnableLocationServices.Youcanreadmoreheresupport.apple.com/en-us/ht5403.
Finally,youneedtosetupyourdevelopmentenvironment.ToemulateadevelopmentenvironmentwithoutinstructionalcontentuseCodepen.io.Codepen.iooffersafreestand-alonedevelopmentenvironment,andmakesiteasytoshareyourcode.OpenthisURLininyourbrowser:codepen.io/nabraham/pen/ExnsA.
CodingYourFirstWebApplicationWiththeCodepen.ioURLloaded,letusreviewthedevelopmentenvironment,thepre-writtencode,andthecodingstepsforyoutofollow.
DevelopmentenvironmentTheCodepen.iodevelopmentenvironment,asshowninFigure12-1,hasthreecodingpanels,oneeachforHTML,CSS,andJavaScript.Thereisalsoapreviewpanetoseetheliveresultsofyourcode.Usingthebuttonatthebottomofthescreen,youcanhideanycodingpanelyouaren’tusing,andthelayoutofthecodingpanelscanbechanged.
SigningupforaCodepen.ioaccountiscompletelyoptional,andallowsyou
toforkorsavethecodeyouhavewritten,andshareitwithothers.
Figure12-1:TheCodepen.iodevelopmentenvironment.
Pre-writtencodeTheCodepen.iodevelopmentenvironmentincludessomepre-writtenHTML,CSS,andJavaScriptcodefortheMcDuck’sapp.Thepre-writtencodeincludescodeyouhaveseeninpreviouschapters,andnewcodethatisexplainedbelow:
HTML:TheHTMLcodefortheMcDuck’sappisbelow,andincludesTwosections:anopeningandclosing<head>tag,andanopeningandclosing<body>tag.
Insidethe<body>tagsare<h1>tagstocreateaheadingand<div>tags.
Additional<div>tagstodisplaymessagescreatedintheJavaScriptfile.The<div>tagisacontainerthatcanholdcontentofanytype.Thefirst<div>tagisusedtodisplayyourcurrentlongitudeandlatitude.Thesecond<div>tagcanbeusedtodisplayadditionalcontenttotheuser.InstructionstoinserttheHTMLbuttonandonclickattributecode,whichyouresearchedinpreviouschapters.
Here’stheHTMLcode:
<!DOCTYPEhtml><html><head><title>McDuck'sApp</title></head><body><h1>McDuck'sLocalOffers</h1><!--1.CreateaHTMLbuttonthatwhenclickedcallstheJavaScriptgetLocation()function-->
<!--Twocontainers,calleddivs,usedtoshowmessagestouser-->
<divid="geodisplay"></div><divid="effect"></div>
</body></html>
CSS:TheCSScodefortheMcDuck’sappisbelow,andincludes:Selectorsforthebody,heading,andparagraphtags.Propertiesandvaluesthatsetthetextalignment,backgroundcolor,fontfamily,fontcolor,andfontsize.
Onceyourappisfunctioning,styletheappbyaddingaMcDuck’scolorschemeandbackgroundimagelogo.
Here’stheCSS:
body{text-align:center;background:white;}
h1,h2,h3,p{font-family:Sans-Serif;color:black;}
p{font-size:1em;}
JavaScript:TheJavaScriptcodefortheMcDuck’sappisbelow.Thispre-writtencodeisalittlecomplex,becauseitcalculatesthecurrentlocationoftheuserusingtheHTMLGeolocationAPI.InthissectionIreviewthecodeatahighlevelsoyoucanunderstandhowitworksandwhereitcamefrom.
TheGeolocationAPIistheproductofbillionsofdollarsofresearchandisavailabletoyouforfree.Themostrecentbrowserssupportgeolocation,thoughsomeolderbrowsersdonot.Atabasiclevel,codeiswrittentoaskwhetherthebrowsersupportstheGeolocationAPI,and,ifyes,toreturnthecurrentlocationoftheuser.Whencalled,theGeolocationAPIbalancesanumberofdatainputstodeterminetheuser’scurrentlocation.ThesedatainputsincludeGPS,wirelessnetworkconnectionstrength,celltowerandsignalstrength,andIPaddress.
Withthisinmind,let’slookattheJavaScriptcode.TheJavaScriptcodeincludestwofunctions,asfollows:
ThegetLocation()function:Thisfunctiondetermineswhetherthebrowsersupportsgeolocation.Itdoesthisbyusinganifstatementandnavigator.geolocation,whichisrecognizedbythebrowseraspartoftheGeolocationAPIandwhichreturnsatruevalueifgeolocationissupported.
HereisthegetLocation()function:
functiongetLocation(){if(navigator.geolocation){navigator.geolocation.getCurrentPosition(showLocation);}}
TheshowLocation()function:Whenthebrowsersupportsgeolocation,thenextstepistocalltheshowlocationfunction,whichcalculatesanddisplaystheuser’slocation.
AndhereistheshowLocation()function:
functionshowLocation(position){
//2.Hardcodeyourstorelocationonline12and13,andupdatethecommenttoreflectyourMcDuck'srestaurantaddress//Nik'sapt@Perry&W4thSt(changetoyourrestaurantlocation)
varmcduckslat=40.735383;varmcduckslon=-74.002994;
//currentlocationvarcurrentpositionlat=position.coords.latitude;varcurrentpositionlon=position.coords.longitude;
//calculatethedistancebetweencurrentlocationandMcDuck'slocationvardistance=getDistanceFromLatLonInMiles(mcduckslat,mcduckslon,currentpositionlat,currentpositionlon);//Displaysthelocationusing.innerHTMLpropertyandthelat&longcoordinatesforyourcurrentlocationdocument.getElementById("geodisplay").innerHTML="Latitude:"+currentpositionlat+"<br>Longitude:"+currentpositionlon;
}//haversinedistanceformulaTherestomittedforbrevitybecauseit'sshowninapreviouschapter
TheshowLocation()functionperformsthefollowingtasks:
AssignstheMcDucklongitudeandlatitudetomduckslatandmcduckslon(Lines12and13ofthecode).
Assignsthelongitudeandlatitudeofthecustomer’scurrentlocationtocurrentpositionlatandcurrentpositionlon(Lines16and17ofthecode).
Calculatesthedistanceinmilesbetweenthosetwopointsand
assignsthatdistancetoavariablecalleddistance(Line20ofthecode).TheHaversineformulacalculatesthedistancebetweentwopointsonasphere,inthiscasetheearth,andthecodeisshownonlinebutomittedhereforbrevity.Afterthebuttonisclicked,thegetElementByIDand.innerHTMLmethodsdisplaythecustomer’scurrentlongitudeandlatitudeinanHTMLtagnamed"geodisplay"usingtheidattribute.
JavaScriptfunctionsarecase-sensitive,sogetLocation()differsfromgetlocation().TheletterLisuppercaseinthefirstfunction,andlowercaseinthesecondfunction.Similarly,showLocation()differsfromshowlocation()forthesamereason.
CodingstepsforyoutofollowWithsomeofthecodealreadywritten,andwithresearchinthepreviouschapter,followthesestepstoinsertthecode:
1. InserttheHTMLbuttoncodebelowwithonclickattributecallingthegetLocation()functionafterline8intheHTMLfile.
<buttononclick="getLocation()">McDuck'sCheck-in</button>
Afteryouinsertthiscode,pressthebutton.Ifyourlocationsettingsareenabledandyouinsertedthecodeproperly,youwillseeadialogboxaskingforyourpermissiontoshareyourcomputer’slocation.AsshowninFigure12-2,lookatthetopofyourbrowserwindowandclickAllow.
Figure12-2:Thebrowserasksforyourpermissionbeforesharingyourlocation.
2. Updatelines12and13intheJavaScriptfilewiththelatitudeandlongitudeoftherestaurantnearyouservingastheMcDuck’sstore.
Afteryouhaveupdatedthelocation,makesuretochangethecommentinline10toreflecttheaddressofyourrestaurant(insteadofmyapartment).
3. Addanalertthatdisplaysthedistancebetweenyourlocationandtherestaurant.
Thedistancevariablestoresthemilesfromyourcurrentlocationtotherestaurant.Makearoughestimate—oruseamapforgreaterprecision—ofyourcurrentdistancefromtherestaurantyoupicked.Thenusinganalert,showthedistancebyinsertingthiscodebelowinline23.
alert(distance);
Ifthedistanceinthealertislargerorsmallerthanyouexpected,youlikelyenteredinincorrectvaluesforthelatitudeorlongitude.Ifthedistancematchesyourestimate,inserttwoslashes("//")beforethealertandcommentitout.
4. Writeanif-elsestatementonline26toshowanalertifyouarewithinyourthresholddistancetotherestaurant.
Mycode,basedonahalf-milethresholddistance,isdisplayedbelow—yoursmayvarydependingonyouralerttextandthresholddistance.(SeeFigure12-3.)
if(distance<0.5){alert("Yougetafreeburger");}else{alert("Thanksforcheckingin!");}
Figure12-3:TheMcDuck’sappdisplayinganoffertocometothestore.
Whenyourapplogicisworking,youcanchangealert("Yougetafreeburger");toanactualpictureofacouponorburger.Todoso,replacetheentirelinethealertisonwiththefollowingcode:
document.getElementById("effect").innerHTML="<imgsrc='http://www.image.com/image.jpg'>";
ReplacetheURLaftersrcandwithinthesinglequotestoyourownimageURL.Besuretokeepthedoublequotationmarksafterthefirstequalssignandbeforethesemi-colon,andthesinglequotationmarks
afterthesecondequalssignandbeforetherightanglebracket.
5. (Optional)Whentheappisworking,changethetextcolorsandinsertbackgroundimagestomaketheapplookmoreprofessional.
Usehex-valuesorcolornames,asdiscussedinChapter6,tochangethetextandbackgroundcolors.Additionally,youcaninsertabackgroundimage,asyoudidintheCodecademyAboutYouexercise,usingthefollowingcode(seeFigure12-4):
background-image:url("http://www.image.com/image.jpg");
Figure12-4:ThecompletedMcDuck’sappwithstyledcontentdisplayinganimagetotheuser.
DebuggingYourAppWhencodingyourapp,youwillalmostinevitablywritecodethatdoesnotbehaveasyouintended.HTMLandCSSarerelativelyforgiving,withthebrowserevengoingsofarastoinserttagssothepagerendersproperly.However,JavaScriptisn’tsoforgiving,andthesmallesterror,suchasamissingquotationmark,cancausethepagetonotrenderproperly.
Errorsinwebapplicationscanconsistofsyntaxerrors,logicerrors,anddisplayerrors.Giventhatweworkedthroughthelogictogether,themostlikelyculpritcausingerrorsinyourcodewillbesyntaxrelated.Herearesomecommonerrorstocheckwhendebuggingyourcode:
Openingandclosingtags:InHTML,everyopeningtaghasaclosingtag,andyoualwaysclosethemostrecentlyopenedtagfirst.Rightandleftanglebrackets:InHTML,everyleftanglebracket<hasarightanglebracket>.
Rightandleftcurlybrackets:InCSSandJavaScript,everyleftcurlybracketmusthavearightcurlybracket.Itcanbeeasytoaccidentallydeleteitorforgettoincludeit.Indentation:Indentyourcodeanduseplentyoftabsandreturnstomakeyourcodeasreadableaspossible.Properindentationwillmakeiteasierforyoutoidentifymissingtags,anglebrackets,andcurlybrackets.Misspelledstatements:Tagsinanylanguagecanbemisspelled,orspelledcorrectlybutnotpartofthespecification.Forexample,inHTML,<imgscr="image.jpg">isincorrectbecausescrshouldreallybesrcfortheimagetorenderproperly.Similarly,inCSSfont-colorlookslikeitisspelledcorrectlybutnosuchpropertyexists.Thecorrectpropertytosetfontcolorisjustcolor.
Keeptheseerrorsinmindwhendebugging—theymaynotsolveallyourproblems,buttheyshouldsolvemanyofthem.Ifyouhavetriedthestepsaboveandstillcannotdebugyourcode,tweetmeat@nikhilgabrahamandincludethe#codingFDhashtagandyourCodepen.ioURLinyourtweet.
PartIVDevelopingYourCodingSkills
Further
SeehowtoprograminRubyandPythonatwww.dummies.com/extras/coding.
Inthispart…LearnbasicprogrammingtasksinRuby.UseRubywriteasimpleprogramtoformattext.ReviewPythonphilosophyandbasiccommands.UsePythonwriteasimpleprogramtocalculatetips.
Chapter13GettingFamiliarwithRuby
InThisChapterUnderstandingRubyprinciplesandstyleAssigningvariablesandusingifstatements
Manipulatingstringsforconsistencyandformatting
IhopeRubyhelpseveryprogrammerbeproductive,enjoyprogramming,andbehappy.ThatistheprimarypurposeofRubylanguage.
—YukihiroMatsumoto,creatorofRubyRubyisaserver-sidelanguagecreatedbyYukihiro“Matz”Matsumoto,adeveloperwhowaslookingforaneasy-to-usescriptinglanguage.MatsumotohadexperienceprogramminginotherlanguageslikePerlandPython,and,unsatisfiedwithboth,createdRuby.WhendesigningRuby,Matsumoto’sexplicitgoalwasto“makeprogrammershappy”,andhecreatedthelanguagesoprogrammerscouldeasilylearnitanduseit.Itworked.TodayRuby,andparticularlyRubyworkingwithaRubyframeworkcalledRails,isthemostpopularwayforstartupsandcompaniestoquicklycreateprototypesandlaunchwebsitesontheInternet.
Inthischapter,youlearnRubybasics,includingitsdesignphilosophy;howtowriteRubycodetoperformbasictasks;andstepstocreateyourfirstRubyprogram.
WhatDoesRubyDo?Rubyisageneralpurposeprogramminglanguagetypicallyusedforwebdevelopment.Untilnow,theHTML,CSS,andJavaScriptyouhavelearnedinthepreviouschaptershasnotallowedforstoringdataaftertheuserhasnavigatedawayfromthepageorclosedthebrowser.Rubymakesiteasyto
storethisdata,andcreate,update,store,andretrieveitinadatabase.Forexample,imagineIwantedtocreateasocialnetworkingwebsitelikeTwitter.ThecontentIwriteinatweetisstoredinacentraldatabase.Icanexitmybrowser,andturnoffmycomputer,butifIcomebacktothewebsitelatermytweetsarestillaccessibletome.Additionally,ifotherssearchformeorkeywordsinthetweetsIhavewritten,thissamecentraldatabaseisqueried,andanymatchesaredisplayed.Rubydevelopersfrequentlyperformtaskslikestoringinformationinadatabase,andaRubyframeworkcalledRailsspeedsupdevelopmentbyincludingpre-builtcode,templates,andeasywaystoperformthesetasks.Forthesereasons,websitesfrequentlyuseRubyandRailstogether.
AwebsiteusingtheRailsframeworkisreferredtoasbeingbuiltwithRailsor“RubyonRails”.
Twitter’swebsitewasoneofthemosttraffickedwebsitestouseRubyonRails,anduntil2010usedRubycodeforitssearchandmessagingproducts.OtherwebsitescurrentlyusingRubyonRailsinclude:
E-commercewebsitessuchasthoseonthewww.shopify.complatform,includingTheChiveryandBlackMilkClothing.Musicwebsitessuchaswww.soundcloud.com.
Socialnetworkingsitessuchaswww.yammer.com.
Newswebsitessuchaswww.bloomberg.com.
Asshownabove,RubyandRailscancreateavarietyofwebsites.WhileRailsemphasizesproductivity,allowingdeveloperstoquicklywritecodeandtestprototypes,somedeveloperscriticizeRubyandRailsfornotbeingscalable,anduseasevidenceTwitterrewritingtheircodetostopusingRailsformanycorefeatures.WhileIcannotresolvetheproductivity-scalabilitydebateforyouhere,IcansaythatRailscanadequatelyhandlemillionsofvisitorspermonth,andnomatterthelanguageused,significantworkmustbedonetoscaleawebsitetoproperlyhandletensorhundredsofmillionsofvisitorsamonth.
ConfirmtheprogramminglanguageusedbytheseoranymajorwebsitewithBuiltWithavailableatwww.builtwith.com.Afterenteringthewebsiteaddressinthesearchbar,lookundertheFrameworkssectionforRubyonRails.
DefiningRubyStructureRubyhasitsownsetofdesignprinciplesthatguidehowtherestofthelanguageisstructured.Allthelanguagesyouhavelearnedsofarhavetheirownconventions,likethecurlybracesinJavaScriptoropeningandclosingtagsinHTML,andRubyisnodifferentwithconventionsofitsown.ThedesignprinciplesinRubyexplainhowRubytriestobedifferentfromtheprogramminglanguagesthatcamebeforeit.WiththesedesignprinciplesinmindyouwillthenseewhatRubycodelookslike,understandRuby’sstyle,andlearnthespecialkeywordsandsyntaxthatallowthecomputertorecognizewhatyouaretryingtodo.UnlikeHTMLandCSS,andsimilartoJavaScript,Rubycanbeparticularaboutsyntaxandmisspellingakeywordorforgettinganecessarycharacterwillresultintheprogramnotrunning.
UnderstandingtheprinciplesofRubyRubyhasafewdesignprinciplestomakeprogramminginthelanguagelessstressfulandmorefunforprogrammersofotherprogramminglanguages.Thesedesignprinciplesare:
Principleofconciseness:Ingeneral,shortandconcisecodeisneededtocreateprograms.TheinitialsetofstepstorunaprogramwritteninEnglishisoftenreferredtoaspseudo-code.Rubyisdesignedsoaslittleadditionaleffortisneededtotranslatepseudo-codeintoactualcode.EvenexistingRubycommandscanbemademoreconcise.Forexample,Ruby’sifstatementcanbewritteninthreelinesorjustone.
Principleofconsistency:Asmallsetofrulesgovernstheentirelanguage.Sometimesthisprincipleinreferredtoastheprincipleofleastastonishmentorprincipleofleastsurprise.Ingeneral,ifyouarefamiliarwithanotherprogramminglanguage,thewayRubybehavesshouldfeelintuitiveforyou.Forexample,inJavaScriptwhenworkingwithstring
methods,youcanchainthemtogetherlikeso
"alphabet".toUpperCase().concat("Soup")
ThisJavaScriptstatementreturns“ALPHABETSoup”byfirstmakingthestring“alphabet”uppercaseusingthe.toUpperCase()method,andthenconcatenating“soup”to“ALPHABET”.Similarly,theRubystatementbelowchainstogethermethodsjustasyouwouldexpect,alsoreturning“ALPHABETSoup”.
"alphabet".upcase.concat("Soup")
Principleofflexibility:Therearemultiplewaystoaccomplishthesamething,andevenbuilt-incommandscanbechanged.Forexample,whenwritinganif-elsestatementyoucanusethewordsifandelse,butyoucanalsoaccomplishthetaskwithasingle“?”.Thefollowingcodebothperformthesametask.
Version1:
if3>4puts"theconditionistrue"elseputs"theconditionisfalse"end
Version2:
puts3>4?"theconditionisfalse":"theconditionistrue"
StylingandspacingRubygenerallyuseslesspunctuationthanotherprogramminglanguagesyoumayhavepreviouslytried.Somesamplecodeisincludedbelow.
print"What'syourfirstname?"first_name=gets.chompfirst_name.upcase!
iffirst_name=="NIK"print"Youmayenter!"
elseprint"Nothingtoseehere."end
Ifyouranthiscodeitwoulddothefollowing:
Printalineaskingforyourfirstname.Takeuserinput(gets.chomp)andsaveittothefirst_namevariable.Testtheuserinput.Ifitequals“NIK”thenprint“Youmayenter!”otherwiseprint“Nothingtoseehere.”
Eachofthesestatementtypesiscoveredinmoredetaillaterinthischapter.Fornow,asyoulookatthecode,noticesomeofitsstylingcharacteristics
Lesspunctuation:unlikeJavaScripttherearenocurlybraces,andunlikeHTMLtherearenoanglebrackets.Spaces,tabs,andindentationareignored:unlesswithinatextstringwhitespacecharactersdonotmatter.Newlinesindicatetheendofstatements:althoughyoucanusesemi-colonstoputmorethanonestatementonaline,thepreferredandmorecommonmethodistoputeachstatementonitsownline.Dot-notationisfrequentlyused:theperiod(asin.chompor.upcase)signalstheuseofamethod,whichiscommoninRuby.Amethodisasetofinstructionsthatcarryoutaparticulartask.Inthiscodeexample,.chompremovescarriagereturnsfromtheuserinput,and.upcasetransformstheuserinputintoalluppercase.Exclamationpointssignaldanger:methodsappliedtovariables,likefirst_name.upcase,bydefaultdonotchangethevariable’svalueandonlytransformacopyofthevariable’svalue.Exclamationpointssignalapermanentchange,sofirst_name.upcase!permanentlychangesthevalueofthevariablefirst_name.
CodingCommonRubyTasksand
CommandsRubycanperformmanytasksfromsimpletextmanipulationtocomplexloginandpassworduserauthentication.Thefollowingbasictasks,whileexplainedwithinaRubycontext,arecoreprogrammingconceptsapplicabletoanyprogramminglanguage.Ifyouhavereadaboutanotherprogramminglanguageinthisbook,thefollowingwilllookfamiliar.ThesetasksalltakeplaceintheRubyshell,whichlookslikeacommandlineinterface.RubycanalsogenerateHTMLtocreateinteractivewebpages,butthatisslightlymorecomplexandnotcoveredhere.
Instructionsonhowtodothesebasictasksarebelow,butyoucanalsopracticetheseskillsrightawaybyjumpingaheadtothe“BuildingaSimpleForm-TextFormatterUsingRuby”section,laterinthischapter.
Programminglanguagescandothesamesetoftasks,andunderstandingthesetoftasksinonelanguagemakesiteasiertounderstandthenextlanguage.
DefiningdatatypesandvariablesVariables,likeinalgebra,arekeywordsusedtostoredatavaluesforlateruse.Thoughthedatastoredinavariablemaychange,thevariablenamewillalwaysbethesame.Thinkofavariablelikeagymlocker—whatyoustoreinthelockerchanges,butthelockernumberalwaysstaysthesame.
VariablesinRubyarenamedusingalphanumericcharactersandtheunderscore(_)character,andcannotbeginwithanumberorcapitalletter.Table13-1listssomeofthedatatypesthatRubycanstore.
Table13-1DataStoredbyaVariable
DataType Description Example
Numbers Positiveornegativenumberswithorwithoutdecimals 156–101.96
Strings Printablecharacters HollyNovakSeñor
Boolean Valuecaneitherbetrueorfalse truefalse
Toinitiallysetorchangeavariable’svalue,writethevariablenameanduse
oneequalssign,asshowninthefollowingexample:myName="Nik"pizzaCost=10totalCost=pizzaCost*2
UnlikeJavaScript,Rubydoesnotrequireyoutousethevarkeywordtodeclareavariable,ortosetitsvaluethefirsttime.
Variablenamesarecasesensitive,sowhenreferringtoavariableinyourprogramrememberthatMyNameisadifferentvariablefrommyname.Ingeneral,giveyourvariableanamethatdescribesthedatabeingstored.
ComputingsimpleandadvancedmathAfteryoucreatevariables,youmaywanttodosomemathonthenumericalvaluesstoredinthosevariables.Simplemathlikeaddition,subtraction,multiplication,anddivisionisdoneusingoperatorsyoualreadyknow.Onedifferenceisexponentiation(suchas,forexample,2tothepowerof3)isdoneusingtwoasterisks.Examplesareshownbelow,andinTable13-2.
sum1=1+1(equals2)sum1=5-1(equals4)sum1=3*4(equals12)sum1=9/3(equals3)sum1=2**3(equals8)
Advancedmathlikeabsolutevalue,roundingtothenearestdecimal,roundingup,orroundingdowncanbeperformedusingnumbermethods,whichareshortcutstomakeperformingcertaintaskseasier.Thegeneralsyntaxistofollowthevariablenameorvaluewithaperiod,andthenameofthemethodasfollowsforvaluesandvariables
value.methodvariable.method
Thevaluesandvariablesthatmethodsactuponarecalledobjects.IfyoucomparedRubytotheEnglishlanguage,thinkofobjectslikenounsandmethodslikeverbs.
UsingstringsandspecialcharactersAlongwithnumbers,variablesinRubycanalsostorestrings.Toassignavaluetoastringusesingleordoublequotationmarks.
firstname="Jack"lastname='Dorsey'
Todisplaythesevariablevalues,youcanputsorprintthevariablevaluetothescreen.Thedifferencebetweenthetwoisputsaddsanewline(ie.,carriagereturn)afterdisplayingthevalue,whileprintdoesnot.
Variablescanalsostorenumbersasstringsinsteadofnumbers.Eventhoughthestringlookslikeanumber,Rubywillnotbeabletoperformanyoperationsonit.Forexample,Rubycannotevaluatethiscodeasisamountdue="18"+24.
Oneissueariseswithstringsandvariables—whatifyourstringitselfincludesasingleordoublequote?Forexample,ifIwanttostoreastringwiththevalue‘I’monmywayhome’or“Carriesaidshewasleavingfor“justaminute””.Asis,thedoubleorsinglequoteswithinthestringwouldcauseproblemswithvariableassignment.Thesolutionistousespecialcharacterscalledescapesequencestoindicatewhenyouwanttousecharacterslikequotationmarks,whichnormallysignalthebeginningorendofastring,orothernon-printablecharactersliketabs.Table13-3showssomeexamplesofescapesequences.
Escapesequencesareinterpretedonlyforstringswithdoublequotationmarks.Forafulllistofescapesequences,seehttp://en.wikibooks.org/wiki/Ruby_Programming/Strings
Decidingwithconditionals:If,elsif,elseWithdatastoredinavariable,onecommontaskistocomparethevariable’svaluetoafixedvalueoranothervariable’svalue,andthenmakeadecisionbasedonthecomparison.IfyoupreviouslyreadtheJavaScriptchapter,youmayrecallmuchofthesamediscussion,andtheconceptisexactlythesame.Thegeneralsyntaxforanif-elsif-elsestatementisasfollows:
ifconditional1statement1toexecuteifconditional1istrueelsifconditional2statement2toexecuteifconditional2istrueelsestatement3torunifallpreviousconditionalsarefalseend
Noticethereisonlyone‘e’inelsifstatement.
Theifisfollowedbyaconditional,whichevaluatestotrueorfalse.Iftheconditionistrue,thenthestatementisexecuted.Thisistheminimumnecessarysyntaxneededforanif-statement,andtheelseifand
elseareoptional.Ifpresent,theelsiftestsforanadditionalconditionwhenthefirstconditionalisfalse.Youcantestforasmanyconditionsasyoulikeusingelsif.Specifyingeveryconditiontotestforcanbecometedious,soitisusefultohavea“catch-all”.Ifpresent,theelseservesthisfunction,andexecuteswhenallpreviousconditionalsarefalse.
Youcannothaveanelsiforanelsebyitself,withoutaprecedingifstatement.Youcanincludemanyelsifstatements,butoneandonlyoneelsestatement.
Theconditionalinanifstatementcomparesvaluesusingcomparisonoperators,andcommoncomparisonoperatorsaredescribedinTable13-4.
Hereisanexampleifstatement.
carSpeed=40ifcarSpeed>55print"Youareoverthespeedlimit!"elsifcarSpeed==55print"Youareatthespeedlimit!"elseprint"Youareunderthespeedlimit!"end
Figure13-1:Anif-elsestatementwithanelsif.
AsthediagraminFigure13-1shows,therearetwoconditions,eachsignaledbythediamond,whichareevaluatedinsequence.Inthisexample,carSpeedisequalto40,sothefirstcondition(carSpeed>55)isfalse,andthenthesecondconditional(carSpeed==55)isalsofalse.Withbothconditionalsfalse,theelseexecutesandprintstothescreen“Youareunderthespeedlimit!”
InputandoutputAsyouhaveseeninthischapter,Rubyallowsyoutocollectinputfromanddisplayoutputtotheuser.Tocollectuserinputusethegetsmethod,whichstorestheuserinputasastring.Inthefollowingexample,theuserentershisfirstnamewhichisstoredinavariablecalledfull_name:
print"What'syourfullname?"full_name=gets
getsmightsoundlikeanoddkeywordtocollectuserinput.RubyisinfluencedbytheCprogramminglanguage,whichalsohasagetsfunctiontocollectuserinput.
Imaginetheuserenteredhisname,“SatyaNadella.”Asthecodeiscurrentlywritten,ifyoudisplaythevalueofthevariablefull_nameyouwouldseethis
SatyaNadella\n
The\nescapesequenceappearsafterthenamebecauseafteraskingforinputtheuserpressedthe“Enter”key,whichRubystoresas\n.Toremovethe\n
addthechompmethodtothestring,anditwillremovethe\nand\rescapesequences.
print"What'syourfullname?"full_name=gets.chomp
Nowwhenyoudisplaythefull_namevariableyouwouldonlysee“SatyaNadella”.
Todisplayoutputtotheuseryoucaneitheruseprintorputs,shortfor“putstring”.Thedifferencebetweenthetwoisthatputsaddsanewlineafterexecuting,whileprintdoesnot.Thefollowingcodeshowsthedifferencewhenprintandputsisexecuted.
Printcode:print"Themissionhas"print"greattacos"
Result:Themissionhasgreattacos
Putscode:puts"Themissionhas"puts"greattacos"
Result:Themissionhasgreattacos
ShapingYourStringsManipulatingstringsisoneofthemostcommontasksforaprogrammer.Sampletasksinthiscategoryinclude:
Standardizingstringstohaveconsistentupper-andlowercase.Removingwhitespacefromuserinput.Insertingvariablesvaluesinstringsdisplayedtotheuser.
Rubyshineswhenitcomestodealingwithstrings,andincludesmanybuilt-
inmethodsthatmakeprocessingstringseasierinRubythaninotherlanguages.
Stringmethods:upcase,downcase,stripStandardizinguserinputtohavepropercaseandremoveextrawhitespacecharactersisoftennecessarytoeasilysearchthedatalater.Forexample,imagineyouaredesigningawebsitefortheNewYorkDepartmentofMotorVehicles,andonepageisfordriverlicenseapplicationandrenewals.Boththeapplicationandrenewalformsaskforcurrentaddress,whichincludesafieldfortwoletterstateabbreviation.Afterreviewingcompletedpaperforms,andpreviouselectronicdatayouseethatdriversenterthestateinseveralwaysincluding“NY”,“ny”,“Ny”,“ny“,“nY”,andothersimilarvariants.If“NY”wasthedesiredresultyoucoulduseupcaseandstriptomakethisinputconsistent.Table13-5furtherdescribesthesestringmethods.
Insertingvariablesinstringswith#Toinsertvariablevaluesintostringsshowntotheuser,youcanusethehashtagsequence#{...}.Thecodebetweentheopenandclosingcurlybracesisevaluatedandinsertedintothestring.Likewithescapesequences,thevariablevalueisinsertedonlyintostringscreatedwithdoublequotationmarks.Seetheexamplecodeandresultbelow.
Code:yearofbirth=1990pplinroom=20puts"Youryearofbirthis#{yearofbirth}.Isthiscorrect?"
puts'Youryearofbirthis#{yearofbirth}.Isthiscorrect?'puts"Thereare#{pplinroom/2}womenintheroomwiththesamebirthyear."
Result:Youryearofbirthis1990.Isthiscorrect?Youryearofbirthis#{yearofbirth}.Isthiscorrect?Thereare10womenintheroomwiththesamebirthyear.
Thefirststringuseddoublequotesandthevariablewasinsertedintothestringanddisplayedtotheuser.Thesecondstringusedsinglequotessothecodeinsidethecurlybraceswasnotevaluated,thevariablevaluewasnotinserted,andinstead#{yearofbirth}wasdisplayed.Thethirdstringshowsthatanycodecanbeevaluatedandinsertedintothestring.
Thismethodofinsertingvariablevaluesintostringsiscalledstringinterpolation.
BuildingaSimpleForm-TextFormatterUsingRuby
PracticeyourRubyonlineusingtheCodecademywebsite.Codecademyisafreewebsitecreatedin2011toallowanyonetolearnhowtocoderightinthebrowser,withoutinstallingordownloadinganysoftware.Practiceallofthetags(andafewmore)thatyoulearnedinthischapterbyfollowingthesesteps:
1. Openyourbrowser,gotowww.dummies.com/go/codingfd,andclickonthelinktoCodecademy.
2. SignintoyourCodecademyaccount.
SigningupisdiscussedinChapter3.Creatinganaccountallowsyoutosaveyourprogressasyouwork,butit’soptional.
3. NavigatetoandclickonIntroductiontoRubytopracticesomebasic
Rubycommands.4. Backgroundinformationispresentedintheupperleftportionofthe
site,andinstructionsarepresentedinthelowerleftportionofthesite.
5. Completetheinstructionsinthemaincodingwindow.6. Afteryouhavefinishedcompletingtheinstructions,clicktheSave
andSubmitCodebutton.
Ifyouhavefollowedtheinstructionscorrectly,agreencheckmarkappears,andyouproceedtothenextexercise.Ifanerrorexistsinyourcodeawarningappearswithasuggestedfix.Ifyourunintoaproblem,orhaveabugyoucannotfix,clickonthehint,usetheQ&AForums,ortweetmeat@nikhilgabrahamandincludehashtag#codingFD.
Chapter14WrappingYourHeadaround
PythonInThisChapter
UnderstandingPythonprinciplesandstylePracticingPythoncodelikeassigningvariablesandusingifstatements
DoingasimplePythonproject
IchosePythonasaworkingtitlefortheproject,beinginaslightlyirreverentmood(andabigfanofMontyPython’sFlyingCircus).
—GuidovanRossum,creatorofPythonPythonisaserver-sidelanguagecreatedbyGuidovanRossum,adeveloperwhowasboredduringthewinterof1989andlookingforaprojecttodo.Atthetime,VanRossumhadalreadyhelpedcreateonelanguage,calledABC,andtheexperiencehadgivenhimmanyideasthathethoughtwouldappealtoprogrammers.HeexecutedupontheseideaswhenhecreatedPython.AlthoughABCneverachievedpopularitywithprogrammers,Pythonwasarunawaysuccess.Pythonisoneoftheworld’smostpopularprogramminglanguages,usedbybeginnersjuststartingoutandprofessionalsbuildingheavy-dutyapplications.
Inthischapter,youlearnPythonbasics,includingthedesignphilosophybehindPython,howtowritePythoncodetoperformbasictasks,andstepstocreateyourfirstPythonprogram.
WhatDoesPythonDo?Pythonisageneralpurposeprogramminglanguagetypicallyusedforwebdevelopment.ThismaysoundsimilartothedescriptionusedforRubyinthepreviouschapter,andreallybothlanguagesaremoresimilarthantheyare
different.Python,likeRuby,allowsforstoringdataaftertheuserhasnavigatedawayfromthepageorclosedthebrowser,unlikeHTML,CSS,andJavaScript.UsingPythoncommandsyoucancreate,update,store,andretrievethisdatainadatabase.Forexample,imagineIwantedtocreatealocalsearchandratingssitelikeYelp.com.Thereviewsuserswritearestoredinacentraldatabase.Anyreviewauthorcanexitthebrowser,turnoffthecomputer,andcomebacktothewebsitelatertofindtheirreviews.Additionally,whenotherssearchforvenues,thissamecentraldatabaseisqueried,andthesamereviewisdisplayed.StoringdatainadatabaseisacommontaskforPythondevelopers,andexistingPythonlibrariesincludepre-builtcodetoeasilycreateandquerydatabases.
SQLiteisonefreelightweightdatabasecommonlyusedbyPythonprogrammerstostoredata.
Manyhighlytraffickedwebsites,suchasYouTube,arecreatedusingPython.OtherwebsitescurrentlyusingPythoninclude:
Quoraforitscommunityquestionandanswersite.Spotifyforinternaldataanalysis.Dropboxforitsdesktopclientsoftware.Redditforgeneratingcrowd-sourcednews.IndustrialLight&MagicandDisneyAnimationforcreatingfilmspecialeffects.
Fromwebsitestosoftwaretospecialeffects,Pythonisanextremelyversatilelanguage,powerfulenoughtosupportarangeofapplications.Inaddition,tohelpspreadPythoncode,Pythonprogrammerscreatelibraries,whicharestand-alonepre-writtencodethatdocertaintasks,andmakethempubliclyavailableforotherstouseandimprove.Forexample,alibrarycalledScrapyperformswebscaping,whileanotherlibrarycalledSciPyperformsmathfunctionsusedbyscientistsandmathematicians.ThePythoncommunitymaintainsthousandsoflibrarieslikethese,andmostarefreeandopen-sourcesoftware.
Youcangenerallyconfirmthefront-endprogramminglanguageusedbyanymajorwebsitewithBuiltWithavailableatwww.builtwith.com.Afterenteringthewebsiteaddressinthesearchbar,lookundertheFrameworkssectionforPython.NotethatwebsitesmayusePythonforbackendservicesnotvisibletoBuiltWith.
DefiningPythonStructurePythonhasitsownsetofdesignprinciplesthatguidehowtherestofthelanguageisstructured.Toimplementtheseprinciples,everylanguagehasitsownconventions,likecurlybracesinJavaScriptoropeningandclosingtagsinHTML.Pythonisnodifferent,andwewillcoverbothdesignprinciplesandconventionssoyoucanunderstandwhatPythoncodelookslike,understandPython’sstyle,andlearnthespecialkeywordsandsyntaxthatallowthecomputertorecognizewhatyouaretryingtodo.Python,likeRubyandJavaScript,canbeveryparticularaboutsyntax,andmisspellingakeywordorforgettinganecessarycharacterwillresultintheprogramnotrunning.
UnderstandingtheZenofPythonTherearenineteendesignprinciplesthatdescribehowthePythonlanguageisorganized.Someofthemostimportantprinciplesinclude
Readabilitycounts:ThisispossiblyPython’smostimportantdesignprinciple.PythoncodelooksalmostlikeEnglish,andevenenforcescertainformatting,suchasindenting,tomakethecodeeasiertoread.Highlyreadablecodemeansthatsixmonthsfromnowwhenyourevisityourcodetofixabugoraddafeature,youwillbeabletojumpinwithouttryingtoohardtorememberwhatyoudid.Readablecodealsomeansotherscanuseyourcodeorhelpdebugyourcodewithease.
Reddit.comisatop-10-most-visitedwebsiteintheUS,andatop-50-most-visitedwebsiteintheworld.Itsco-founder,SteveHuffman,
initiallycodedthewebsiteinLispandswitchedtoPythonbecausePythonis“extremelyreadable,andextremelywriteable”.
Thereshouldbeone—andpreferablyonlyone—obviouswaytodoit:ThisprincipleisdirectlyoppositetoPerl’smotto,“There’smorethanonewaytodoit.”InPython,twodifferentprogrammersmayapproachthesameproblemandwritetwodifferentprograms,buttheidealisthatthecodewillbesimilarandeasytoread,adopt,andunderstand.AlthoughPythondoesallowmultiplewaystodoatask—as,forexample,whencombiningtwostrings—ifanobviousandcommonoptionexists,itshouldbeused.Iftheimplementationishardtoexplain,it’sabadidea:Historically,programmerswereknowntowriteesotericcodetoincreaseperformance.However,Pythonwasdesignednottobethefastestlanguage,andthisprincipleremindsprogrammersthateasy-to-understandimplementationsarepreferableoverfasterbutharder-to-explainones.
Accessthefulllistbydesignprinciples,whichisintheformofapoem,bytypingimportthis;intoanyPythoninterpreter,orbyvisitinghttps://www.python.org/dev/peps/pep-0020.Theseprinciples,writtenbyTimPeters,aPythoncommunitymember,weremeanttodescribetheintentionsofPython’screator,VanRossum,whoisalsoreferredtoastheBenevolentDictatorforLife(BDFL).
StylingandspacingPythongenerallyuseslesspunctuationthanotherprogramminglanguagesyoumayhavepreviouslytried.Somesamplecodeisincludedhere:
first_name=raw_input("What'syourfirstname?")first_name=first_name.upper()
iffirst_name=="NIK":print"Youmayenter!"else:print"Nothingtoseehere."
TheexamplesinthisbookarewrittenforPython2.7.TherearetwopopularversionofPythoncurrentlyinuse—Python2.7andPython3.Python3isthelatestversionofthelanguagebutitisnotbackwards-compatible,socodewrittenusingPython2.7syntaxdoesnotworkwhenusingaPython3interpreter.Initially,Python2.7hadmoreexternallibrariesandsupportthanPython3,butthisischanging.Formoreaboutthedifferencesbetweenversionsseehttps://wiki.python.org/moin/Python2orPython3.
Ifyouranthiscodeitwoulddothefollowing:
Printalineaskingforyourfirstname.Takeuserinput(raw_input(What’syourfirstname?))andsaveittothefirst_namevariable.
Transformanyinputtedtextintouppercase.Testtheuserinput.Ifitequals“NIK,”thenitwillprint“Youmayenter!”Otherwiseitwillprint“Nothingtoseehere.”
Eachofthesestatementtypesiscoveredinmoredetaillaterinthischapter.Fornow,asyoulookatthecode,noticesomeofitsstylingcharacteristics:
Lesspunctuation:UnlikeJavaScript,Pythonhasnocurlybraces,andunlikeHTML,noanglebrackets.Whitespacematters:Statementsindentedtothesamelevelaregroupedtogether.Intheexampleabove,noticehowtheifandelsealign,andtheprintstatementsunderneatheachareindentedthesameamount.Youcandecidetheamountofindentation,andwhethertousetabsorspacesaslongasyouareconsistent.Generally,fourspacesfromtheleftmarginisconsideredthestylenorm.
SeePythonstylesuggestionsonindentation,whitespaces,andcommentingbyvisitinghttps://www.python.org/dev/peps/pep-0008.
Newlinesindicatetheendofstatements:Althoughyoucanusesemi-colonstoputmorethanonestatementonaline,thepreferredandmorecommonmethodistoputeachstatementonitsownline.Colonsseparatecodeblocks:NewPythonprogrammerssometimesaskwhyusingcolonstoindicatecodeblocks,liketheoneattheendoftheifstatement,isnecessarywhennewlineswouldsuffice.Earlyusertestingwithandwithoutthecolonsshowedthatbeginnerprogrammersbetterunderstoodthecodewiththecolon.
CodingCommonPythonTasksandCommands
Python,aswithotherprogramminglanguageslikeRuby,candoeverythingfromsimpletextmanipulationtodesigningcomplexgraphicsingames.ThefollowingbasictasksareexplainedwithinaPythoncontext,butthey’refoundationalinunderstandinganyprogramminglanguage.Evenexperienceddeveloperslearninganewlanguage,likeApple’srecentlyreleasedSwiftprogramminglanguage,startbylearningthesefoundationaltasks.IfyouhavealreadyreadthechapteronRuby,thecodetoperformthesetaskswilllooksimilar.
StartlearningsomebasicPythonbelow,orpracticetheseskillsrightawaybyjumpingaheadtothe“BuildingaSimpleTipCalculatorUsingPython”section,laterinthischapter.
MillionsofpeoplehavelearnedPythonbeforeyou,soit’seasytofindanswerstoquestionsthatmightarisewhilelearningsimplybyconductinganInternetsearch.Theoddsareinyourfavorthatsomeonehasaskedyourquestionbefore.
DefiningdatatypesandvariablesVariables,liketheonesinalgebra,arekeywordsusedtostoredatavaluesforlateruse.Thoughthedatastoredinavariablemaychange,thevariablenamewillalwaysbethesame.Thinkofavariableasagymlocker—whatyoustoreinthelockerchanges,butthelockernumberalwaysstaysthesame.
VariablesinPythonarenamedusingalphanumericcharactersandtheunderscore(_)character,andtheymuststartwithaletteroranunderscore.Table14-1listssomeofthedatatypesthatPythoncanstore.
Table14-1DataStoredbyaVariable
DataType Description Example
Numbers Positiveornegativenumberswithorwithoutdecimals 156–101.96
Strings Printablecharacters HollyNovakSeñor
Boolean Valuecaneitherbetrueorfalse truefalse
Toinitiallysetorchangeavariable’svalue,writethevariablename,asingleequalssign,andthevariablevalue,asshowninthefollowingexample:
myName="Nik"pizzaCost=10totalCost=pizzaCost*2
Avoidstartingyourvariablenameswiththenumberone(1),alowercase“L”(l),oruppercasei(I).Dependingonthefontusedthesecharacterscanalllookthesame,causingconfusionforyouorotherslater!
Variablenamesarecasesensitive,sowhenreferringtoavariableinyourprogramrememberthatMyNameisadifferentvariablefrommyname.Ingeneral,giveyourvariableanamethatdescribesthedatabeingstored.
ComputingsimpleandadvancedmathAfteryoucreatevariables,youmaywanttodosomemathonthenumericalvaluesstoredinthosevariables.Simplemathlikeaddition,subtraction,multiplication,anddivisionisdoneusingoperatorsyoualreadyknow.Exponentiation(suchas,forexample,2tothepowerof3)isdonedifferentlyinPythonthaninJavaScript,andusestwoasterisks.Examplesareshownhere:
num1=1+1#equals2num2=5-1#equals4num3=3*4#equals12
num4=9/3#equals3num5=2**3#equals8
The#symbolindicatesacommentinPython.
Don’tjustreadthesecommands,trythem!Gotohttp://repl.it/languages/Pythonforalightweightin-browserPythoninterpreterthatyoucanuserightinyourbrowserwithoutdownloadingorinstallinganysoftware.
Advancedmathlikeabsolutevalue,roundingtothenearestdecimal,roundingup,orroundingdowncanbeperformedusingmathfunctions.Pythonhassomefunctionswhicharebuilt-inpre-writtencodethatcanbereferencedtomakeperformingcertaintaskseasier.ThegeneralsyntaxtousePythonmathfunctionsistolistthefunctionname,followedbythevariablenameorvalueasanargument,asfollows:
method(value)method(variable)
Themathfunctionsforabsolutevalueandroundingfollowthesyntaxabove,butsomemathfunctions,likeroundinguporroundingdownarestoredinaseparatemathmodule.Tousethesemathfunctionsyoumust:
Writethestatementimportmathjustonceinyourcodebeforeusingthemathfunctionsinthemathmodule.Referencethemathmodule,asfollows:math.method(value)ormath.method(variable).
SeethesemathfunctionswithexamplesinTable14-2.
ModulesareseparatefilesthatcontainPythoncode,andthemodulemustbereferencedorimportedbeforeanycodefromthemodulecanbeused.
Seeallthefunctioninthemathmodulebyvisitinghttps://docs.python.org/2/library/math.html.
UsingstringsandspecialcharactersAlongwithnumbers,variablesinPythoncanalsostorestrings.Toassignavaluetoastringyoucanusesingleordoublequotationmarks,asfollows:
firstname="Travis"lastname='Kalanick'
Variablescanalsostorenumbersasstringsinsteadofnumbers.However,eventhoughthestringlookslikeanumber,Pythonwillnotbeabletoadd,subtract,ordividestringsandnumbers.Forexample,consideramountdue="18"+24—runningthiscodeasiswouldresultinanerror.Pythondoesmultiplystringsbutinaninterestingway—print‘Ha’*3resultsin‘HaHaHa’.
Includingasingleordoublequoteinyourstringcanbeproblematicbecausethequotesinsideyourstringwillterminatethestringdefinitionprematurely.Forexample,ifIwanttostoreastringwiththevalue‘I’monmywayhome’Pythonwillassumethe‘afterthefirstletterIistheendofthevariableassignment,andtheremainingcharacterswillcauseanerror.Thesolutionistousespecialcharacterscalledescapesequencestoindicatewhenyouwanttousecharacterslikequotationmarks,whichnormallysignalthebeginningorendofastring,orothernon-printablecharactersliketabs.Table14-3
showssomeexamplesofescapesequences.
Escapesequencesareinterpretedonlyforstringswithdoublequotationmarks.ForafulllistofescapesequencesseethetableunderSection2.4"Literals"athttp://docs.python.org/2/reference/lexical_analysis.html
Decidingwithconditionals:If,elif,elseWithdatastoredinavariable,onecommontaskistocomparethevariable’svaluetoafixedvalueoranothervariable’svalue,andthenmakeadecisionbasedonthecomparison.IfyoupreviouslyreadthechaptersonJavaScriptorRuby,thediscussionandconceptshereareverysimilar.Thegeneralsyntaxforanif-elif-elsestatementisasfollows:
ifconditional1:statement1toexecuteifconditional1istrueelifconditional2:statement2toexecuteifconditional2istrueelse:statement3torunifallpreviousconditionalarefalse
Noticetherearenocurlybracketsorsemi-colons,butdon’tforgetthecolonsandtoindentyourstatements!
Theinitialifstatementwillevaluatetotrueorfalse.Whenconditional1istrue,thenstatement1isexecuted.Thisistheminimumnecessarysyntaxneededforanif-statement,andtheelifandelseareoptional.Whenpresent,theeliftestsforanadditionalconditionwhenconditional1isfalse.Youcantestforasmanyconditionsasyoulikeusingelif.Specifyingeveryconditiontotestforcanbecometedious,sohavinga"catch-all"isuseful.Whenpresent,theelseservesasthe"catch-all",andexecuteswhenallpreviousconditionalsarefalse.
Youcannothaveaneliforanelsebyitself,withoutaprecedingifstatement.Youcanincludemanyelifstatements,butoneandonlyoneelsestatement.
Theconditionalinanifstatementcomparesvaluesusingcomparisonoperators,andcommoncomparisonoperatorsaredescribedinTable14-4.
Hereisanexampleifstatement.
carSpeed=55ifcarSpeed>55:print"Youareoverthespeedlimit!"elifcarSpeed==55:
print"Youareatthespeedlimit!"else:print"Youareunderthespeedlimit!"
AsthediagraminFigure14-1shows,therearetwoconditions,eachsignaledbythediamond,whichareevaluatedinsequence.Inthisexample,carSpeedisequalto55,sothefirstcondition(carSpeed>55)isfalse,andthenthesecondconditional(carSpeed==55)istrueandthestatementexecutesprinting“Youareatthespeedlimit!”Whenaconditionalistrue,theifstatementstopsexecuting,andtheelseisneverreached.
InputandoutputPythoncancollectinputfromtheuser,anddisplayoutputtotheuser.Tocollectuserinputusetheraw_input(“Prompt”)method,whichstorestheuserinputasastring.Intheexamplebelow,theuserentershisfullnamewhichisstoredinavariablecalledfull_name.
full_name=raw_input("What'syourfullname?")
Figure14-1:Anif-elsestatementwithanelif.
Imaginetheuserenteredhisname,“JeffBezos.”Youcandisplaythevalueofthevariableusingprintfull_nameandyouwouldseethis
JeffBezos
Python,unlikeRuby,doesnotstorethenewline\nescapesequenceafteruserinput.
Atthispoint,youmayfeellikeprintingvariablesandvaluesinaPythoninterpreterconsolewindowisverydifferentfromdynamicallycreatingweb
pageswithvariablescreatedinPython.IntegratingPythonintoawebpagetorespondtouserrequestsandgenerateHTMLpagesistypicallydonewithaPythonwebframework,likeDjangoorFlask,whichhavepre-writtencodetomaketheprocesseasier.Theseframeworkstypicallyrequiresomeinstallationandset-upwork,andgenerallyseparatethedatabeingdisplayedfromtemplatesusedtodisplaythepagetotheuser.
ShapingYourStringsWheneveryoucollectinputfromusers,youneedtocleantheinputtoremoveerrorsandinconsistencies.Herearesomecommondatacleaningtasks:
StandardizingstringstohaveconsistentupperandlowercaseRemovingwhitespacefromuserinputInsertingavariable’svalueinstringsdisplayedtotheuser
Pythonincludesmanybuilt-inmethodsthatmakeprocessingstringseasy.
Dotnotationwithupper(),lower(),capitalize(),andstrip()Standardizinguserinputtohavepropercaseandremoveextrawhitespacecharactersisoftennecessarytoeasilysortthedatalater.Forexample,imagineyouaredesigningawebsitefortheNewYorkKnickssofanscanmeetplayersafterthegame.Thepageasksforfanstoentertheirname,sothatteamsecuritycanlatercheckfannamesagainstthislistbeforeentry.Reviewingpastfanentriesyouseethatfansenterthesamenameseveralwayslike“Mark”,“mark”,“marK“andothersimilarvariantsthatcauseissueswhenthelistissortedalphabetically.TomaketheinputandthesenamesconsistentyoucouldusethestringfunctionsdescribedinTable14-5.
Stringformattingwith%Toinsertvariablevaluesintostringsshowntotheuser,youcanusethestringformatoperator%.Insertedintothestringdefinition,%disusedtospecifyintegers,%sisusedtospecifystrings,andthevariablestoformat(mappingkey)arespecifiedinparenthesisafterthestringisdefined.Seetheexamplecodeandresultbelow:
Code:yearofbirth=1990pplinroom=20name="Mary"print"Youryearofbirthis%d.Isthiscorrect?"%(yearofbirth)print'Youryearofbirthis%d.Isthiscorrect?'%(yearofbirth)print"Thereare%dwomenintheroombornin%dand%sisoneofthem."%(pplinroom/2,yearofbirth,name)
Result:Youryearofbirthis1990.Isthiscorrect?Youryearofbirthis1990.Isthiscorrect?Thereare10womenintheroombornin1990andMaryisoneofthem.
Thefirststringuseddoublequotesandthevariablewasinsertedintothestringanddisplayedtotheuser.Thesecondstringbehavedjustlikethefirststring,becauseunlikeinRuby,definingstringswithsinglequotesdoesnotaffectthestringformatting.Thethirdstringshowsthatcodecanbeevaluated
(pplinroom/2)andinsertedintothestring.
Thestring.format()methodisanotherwaytoformatstringsinPython.
BuildingaSimpleTipCalculatorUsingPython
PracticeyourPythononlineusingtheCodecademywebsite.Codecademyisafreewebsitecreatedin2011toallowanyonetolearnhowtocoderightinthebrowser,withoutinstallingordownloadinganysoftware.Practiceallofthetags(andafewmore)thatyoulearnedinthischapterbyfollowingthesesteps:
1. Openyourbrowser,gotowww.dummies.com/go/codingfd,andclickonthelinktoCodecademy.
2. SignintoyourCodecademyaccount.
SigningupisdiscussedinChapter3.Creatinganaccountallowsyoutosaveyourprogressasyouwork,butit’soptional.
3. NavigatetoandclickonPythonSyntaxtopracticesomebasicPythoncommands.
4. Backgroundinformationispresentedintheupperleftportionofthesite,andinstructionsarepresentedinthelowerleftportionofthesite.
5. Completetheinstructionsinthemaincodingwindow.6. Afteryouhavefinishedcompletingtheinstructions,clicktheSave
andSubmitCodebutton.
Ifyouhavefollowedtheinstructionscorrectly,agreencheckmarkappearsandyouproceedtothenextexercise.Ifanerrorexistsinyourcodeawarningappearswithasuggestedfix.Ifyourunintoaproblem,orhaveabugyoucannotfix,clickonthehint,usetheQ&AForum,or
tweetmeat@nikhilgabrahamandincludehashtag#codingFD.
PartV
ThePartofTens
Seeadditionalresourcestohelpyouprogramatwww.dummies.com/extras/coding.
Inthispart…Continuetolearnhowtocodewithonlineresources.Stayuptodatewithindustrynewsandcommunitydiscussion.Solvecodingbugswithonlineandofflineresources.Keepinmindtentipsasyoulearnhowtocode.
Chapter15TenFreeResourcesforCoding
andCodersThetechnologyworldisconstantlyevolving.Newtechnologiesareinvented,developersbuildnewproductsusingthesetechnologies,andnewmarketsemergefrompeopleusingtheseproducts.Inthetimeittookmetowritethesechaptersandforthisbooktofinditswayintoyourhands,muchhasalreadychanged.Thefollowingresourceshelpyoucontinuelearning,answerquestions,andstayabreastofthesechanges.
Theresourceslistedbelowareallcompletelyfree.Manyoftheseresourcesstayfreebydependingoncommunitymemberslikeyoutocontribute,sodon’tbeshyaboutparticipating!
Learning-to-CodeWebsitesLearningtocodeisaconstantjourneythatneverendsforeventhemostexperiencedprogrammers.Newlanguagesandframeworksappeareveryday,andtheonlywaytostaycurrentistokeeplearning.Althoughyoumaynotbeanexperienceddeveloperjustyet,thefollowingresourcesappealtobeginnerswithdifferentlearningstyles.Youcanlearngeneralintroductorycomputersciencetopicsorspecificwebdevelopmenttechniquesbyreadingtextorwatchingvideolectures,anddoitatyourownpaceorinascheduledclass.Let’sgetstarted!
Codecademywww.codecademy.com
Codecademy,createdforpeoplewithnopreviousprogrammingexperience,istheeasiestwaytolearnhowtocodeonline.Manychaptersinthisbookuselessonsfromthesite.Youcanusethesiteto
Learnfront-endlanguageslikeHTML,CSS,andJavaScriptTryback-endlanguageslikeRuby,Python,andPHP
BuildrealpagesfromwebsiteslikeAirBnb,Flipboard,andEtsy
Front-endlanguagesaddresswebsiteappearance,whereasback-endlanguagesaddwebsitelogic,suchaswhattoshowusersandwhen.SeeChapter2formoredetail.
Youdon’tneedtodownloadorinstallanythingtostartcodingatCodecademy—justsignuporsigninandstartlearning.
Ifyougetstuck,checkforahintatthebottomoftheinstructions,orclicktheQ&AForumlinktoaskaquestionortoseeifsomeonehasalreadypostedasolutiontoyourproblem.
CourseraandUdacitywww.coursera.org
www.udacity.com
MOOCs,ormassiveopenonlinecourses,areclassesorcoursesthataretaughtviatheInternettoavirtuallyunlimitednumberofstudents.Thesecoursesencouragetheuseofonlineforumsandinteractivitytocreateasenseofcommunity.CourseraandUdacity,twoofthebiggestMOOCs,haveavarietyofcoding-relatedcourses.Eachcourseistaughtthroughaseriesofvideolecturesbyauniversityfacultymemberoranindustryexpert.(SeeFigure15-1.)Afterwatchingvideolectures,yourhomeworkassignmentsandprojectshelpreinforcewhatyou’velearned.Eachsiteoffersoptionalpaidfeatures,suchascertificatesofcompletionorindividualsupport,butyoudon’thavetopayanythingtoaccessthebasematerial.Thestrengthofthesesitesistheirhundredsofhoursofvideodedicatedtotechnologytopicssuchasfront-endwebdevelopment,mobilewebdevelopment,datascience,orgeneralcomputersciencetheory.
Beforeyoustartacourseateitherwebsite,makesureyoucansetasidetimeforstudyeachweek.Youcanexpecttodevote5to10hoursperweekfor7to10weeksforanyofthesecourses.
Hackdesign.orgwww.hackdesign.org
Figure15-1:IntrotoComputerScience,taughtbyUniversityofVirginiaProfessorDavidEvansonUdacity.
Theotherhalfofcodingisdesigning.Goodvisualdesignisoftenthedifferencebetweenhavinghundredsofpeopleuseandshareyourwebsiteandhavingmillionsofpeopledoso.HackDesignhas50designlessonscreatedbytopdesignersfromaroundtheworld,includingdesignersfromFacebook,Dropbox,andGoogle.Eachlessonisemailedtoyouweekly,andincludesarticlestoread,anddesigntaskstocompletebasedonwhatyouhavejustlearned.Topicscoveredincludetypography,productdesign,userinteractions,andrapidprototypingtools.
Manyoftheexpertdesignershavepublicportfoliowebsitesatwhichyoucanseepastdesignsandprojects.Inaddition,manyposttheircreativeworkonDribble,availableatwww.dribbble.com(notethethreeb’sintheURL).
Code.orgwww.code.org
InDecember2013,Code.orgmadehistorywhenover15millionU.S.schoolstudentsparticipatedinalearn-to-codeeventcalledHourofCode.
Throughout2014,anadditional25millionstudentswouldpracticetheirprogrammingskillsforonehour.Code.orghostsitsowncontentforstudentsfromkindergartentoeighthgrade.Italsoprovideslinkstootherlearn-to-coderesources,whicharetargetedforarangeofages,andtopicsinclude
TutorialsthatteachHTML,JavaScript,Python,andotherlanguagesVisualprogrammingtoolsthathelpelementaryandmiddleschoolstudentsdrag-and-droptheirwaytolearninghowtocodeInstructionstomakeyourownAngryBirds,FlappyBird,andLostinSpaceapps
Code.orgalsohasofflinelearn-to-codematerials,soyoucankeeplearningevenifyoudon’thavereliableaccesstoanInternetconnection.
Coding-ReferenceWebsitesAsyoulearntocode,eitherbyreadingthisbookorfromsomeofthewebsitesdiscussedpreviously,youwillgetstuck.Yourcodejustwon’tbehaveasyouintended.Thishappenstoeveryprogrammer—it’saninevitablepartoftheprocessofturninghumanlogicandfuzzythoughtsintorigidcodeacomputercanunderstand.Theimportantthingistohaveaplan,andtohavesomeresourcestohelpdebugyourcodeandsolveyourproblem.Thefollowingresourcesincludereferencetexts,whichhelpyoucheckyourcodingsyntax,andcommunityusergroups,whichhelpyoucheckyourprogramlogic.
W3Schoolswww.w3schools.com
W3Schoolsisoneofthebestresourcesforbeginnerswhoarejuststartingtolearn.ThewebsiteincludesreferencematerialandbasictutorialsforHTML,CSS,JavaScript,PHP,andotherprogramminglanguages,libraries,andstandards.(SeeFigure15-2.)Inaddition,thereferencepagesincludemanycodingexamples,whichyoucanviewandmodifyinyourbrowser,alongwithalistofattributesorpropertiesthatcanbeused.Ifyouknowyoucan
insertanimageusingHTML,changethetextcolorusingCSS,orshowanalerttotheuserusingJavaScript,butyoucannotremembertheexactsyntaxtodoso,trystartingwithW3Schools.
Althoughit’sagreatresource,W3SchoolshasnoaffiliationwithorendorsementfromtheW3C,whichisthegoverningbodythatcreatesthestandardsbrowsersfollowwhenrenderingHTML,CSS,andotherlanguagesandformats.
Figure15-2:HTML,CSS,andJavaScripttutorialsandreferencepagesonW3Schools.
MozillaDeveloperNetworkhttp://developer.mozilla.org
MozillaDeveloperNetwork(MDN)isawiki-stylereferenceandtutorialwebsitethatcoversHTML,CSS,JavaScript,andvariousAPIs.Thewebsiteismaintainedbythedevelopercommunity,soanyonecancontribute—evenyou!Althoughnotasbeginner-friendlyasW3Schools,MDNisoneofthemostcompleteandaccuratesourcesofdocumentationforweblanguages.DevelopersfrequentlyuseMDNtoreferencesyntax,andalsotoseedesktopandmobilebrowsercompatibilityforspecifictagsandcommands.YoucanalsocheckouttutorialsonMDNhostedbytheMozillaFoundation,anon-profitorganizationthathelpssupportandmaintaintheFirefoxbrowser.
StackOverflowwww.stackoverflow.com
StackOverflowisrelativelyyoung,foundedin2008,buthasquicklybecomethebestplacefordeveloperstoaskandanswerquestionsaboutcoding.Anyonecanaskaquestion,individualprogrammersprovideanswers,andthewebsitecommunityvotesupordowntheanswerstoshowagreementordisagreement.Thesiteincludestopicsthatcoverallmajorwebprogramminglanguages,andthemostpopulartopicsincludeJavaScript,Ruby,andPython.
Beforeaskingaquestion,searchthewebsiteandseeifananswertoyourquestionhasalreadybeenposted.Oneofthewebsiterulesofetiquetteisshowingyouhavedonesomeresearchbeforepostingaquestion.
TechNewsandCommunityWebsitesTherearepeoplecodingallovertheworld,andsomeoneinShanghaicanmakeanappyouuseeverydayjustaseasilyassomeoneinSanFrancisco.Anumberofresourcesareavailablefordeveloperstobetterunderstandwhatothersareworkingon,bothatbigcompaniesandatstartups.Inadditiontowhatpeopleareworkingonrightnow,ifyouhaveawebsiteyouwanttobuild,itcanbehelpfultoseewhathasbeenbuiltinthepast,soyoucanidentifyareasforimprovement.
Beyondbeinginformative,theseresourcesoffercommunitiesofpeoplewithgoalssimilartoyours.Thesecommunitiesareamongthemostvaluableresourcesavailabletoyou.Whetheryouarelearningtocodeoranexpertdevelopersolicitingfeedbackonawebsite,workingwithothersisbetterthanworkingalone.
Thefollowingresourceshelpyoustayinformedonwhatishappeninginthetechcommunity,andinteractwithotherpeopleinterestedintechinyourcity.
TechCrunchwww.techcrunch.com
TechCrunchisapopularblogthatcoverstechnologystartupsandmajortechnologycompanies.In2006,thewebsitecementeditsreputationwhenitbrokethestoryofGoogleacquiringYouTubefor$1.6billion.Alongwithitsonlinereporting,TechCrunchhasconferencesthroughouttheyear,suchasDisrupt,whichhostsconversationswithindustryveteransandhighlightsnewtechstartups.
TechCrunchalsooperatesCrunchBase(www.crunchbase.com),acrowdsourceddatabaseof650,000peopleandcompanies.Crunchbaseisoneofthemostaccurateandcompletesourcesofinformationonstartups,pastandpresent,andtheirfounders.
HackerNewshttp://news.ycombinator.com
HackerNews(HN)isadiscussionwebsitehostedbyYCombinator,astartupincubatorinCalifornia.Thewebsitehomepageisacollectionofhyperlinks,oftentostartupwebsitesandnewsarticles,thatindividualusershavesubmitted.(SeeFigure15-3.)Afterasubmissionismade,theentirecommunitycanupvotethesubmission,andthetop-rankedsubmissionsarelistedfirstonthehomepage.Also,thecommunitycancommentonindividualsubmissions,andeachcommentcanalsobeupvoted,withthetop-rankedcommentappearingfirstoneachsubmissionpage.Inthisway,thecommunitycuratesthebestnews,whichappearsonthefrontpage,andthebestcomments,whichappearoneachsubmissionpage.Thecommunityismadeupofhundredsofthousandsofusers,includingAirBnBco-founderBrianChesky,Dropboxco-founderDrewHouston,Netscapeco-founderandnowventurecapitalistMarcAndreessen,andventurecapitalistFredWilson.
Figure15-3:Thecommunity-curatednewsanddiscussionsatHackerNewshomepage.
Submissiontitlesthatbeginwith“ShowHN”arearequesttothecommunitytocommentonastartupwebsitethathasjustlaunched.Submissiontitlesthatbeginwith“AskHN”arearequesttothecommunitytoanswerorcommentonaquestion.
Meetupwww.meetup.com
Meetupisawebsitethatorganizesface-to-facelocalmeetingsbasedoninterestsoractivities.Meetuporganizers,whoarevolunteercommunitymembers,hostmeetingsbypostinginformationonthewebsite.Then,communitymemberssearch,join,andRSVPformeetingsthroughthewebsite.
Tousethewebsite,gotowww.meetup.comandthenfollowthesesteps:
1. Enteryourcityandhowfaryouarewillingtotravel.2. Inthesearchfield,entercodingorwebdevelopment.Ifyouhavea
specificlanguageyouwanttolearn,likeRubyorJavaScript,enter
thelanguagename.3. ReviewtheMeetupgroups,andlookforoneswithagoodnumberof
members.Youcanjoinagroupandreceivenotificationsoffutureevents,orRSVPforaspecificupcomingevent.Someeventsmayhaveafeetocoverexpenses.
Althoughyoucanlearnalone,findingotherpeoplelearningtocodeisagreatwaytostaymotivatedandkeepupyourmomentum.Thepeopleyoumeetmaybelearningtocodeforthesamereasonsyouare,suchastobuildawebsite,improveskillsforanexistingjob,orfindanewtech-relatedjob.
Chapter16TenTipsforNoviceCoders
Learningtocodeismorepopulartodaythaneverbefore.Itseemslikeeveryonehasawebsiteoranappidea,andassoonasyourfriends,family,orcoworkersdiscoveryournewcodingabilities,manywillaskforadviceandhelp.Nomatterwhetheryou’redabblingatitafterwork,orattendinganintensiveten-weekcodingbootcamp,learningtocodecanbeachallengingjourney.Itcanpaytopickupafewpointersfromsomeofthepeoplewhocrossedthefinishlineaheadofyou.Keepthefollowingtipsinmind,especiallywhenstartingyourcodingjourney.
PickaLanguage,AnyLanguageAsanovicecoder,youmaynotbesurewheretostart.ShouldyoulearnC++,Python,Java,Ruby,PHP,JavaScriptallatthesametime,sequentially,orjustpickafew?Ifyouhaveneverprogrammedbefore,Irecommendlearningalanguageusedtocreatewebpages,becausewiththeselanguagesit’seasytogetstartedandpublishworkforotherstosee.Withinthissetoflanguages,IrecommendstartingwithHTMLandCSS.Botharemarkuplanguages,whicharetheeasiesttolearn,andletyouputcontentonawebpagewithHTML,andstylethatcontentwithCSS.Afteryouunderstandsomeofthebasicsofpresentingcontent,youcanthenlearnaprogramminglanguagetomanipulatethatcontent.Keepinmindthatyoudon’tneedtolearneveryprogramminglanguage—JavaScript,whichaddsinteractivitytothewebpage,isacommonstartingpointforbeginners,alongwitheitherRubyorPython,whichaddsmoreadvancedfeatureslikeuseraccountsandlogins.
Learningtocodeissimilartolearningtodriveacar.Whenyoufirstlearnedtodrive,youprobablydidn’tworrytoomuchaboutthetypeofcaryouweredriving.Afterpassingthedrivingtest,youcouldoperatejustaboutanycar,evenoneyouhadn’tdrivenbefore,becauseyouknewtolookfortheignition,accelerator,andbrake.Learningaprogramminglanguageworksthesameway:Afteryoulearnonelanguage,youknowwhattolookfor,andlearningandusinganotherlanguagebecomeseasier.Inotherwords,juststart
somewhere!
DefineaGoalWhenyoustartlearningtocode,pickingagoalcanhelpyoustaymotivated.Youcanpickanygoalyoulike,butmakesureit’ssomethingyouwouldbereallyexcitedtoaccomplish.Goodgoalsforbeginnersinclude
Creatingasmallwebsite—consistingofonetofourdifferentpages—foryourself,abusiness,oragroup.Buildingyourcodingvocabularysoyoucanunderstandwhatdevelopersordesignerssayinmeetingsatwork.Creatingaprototype,orabasicversion,ofawebsiteorappidea—forexample,anappthattellsyouwhenthenextbusisarrivingtoyourcurrentlocation.
Atfirst,practicedoingverysmallcodingtasks—theequivalentofchoppingvegetablesinculinaryschool.Thesetasks,suchasboldingaheadline,mayleaveyoufeelingdisconnectedfromyourultimategoal.Butasyoukeeplearning,youwillstarttopiecetogetherindividualcodingskillsandseeapathtoaccomplishyourgoal.
Pickasimplegoalatfirsttobuildyourconfidenceandtechnicalskills.Asyougainconfidence,youcanbuildmoreprofessional-lookingwebsitesandapps.
BreakDownYourGoalintoBite-SizedSteps
Afterdefiningagoal,breakitdownintosmallsteps.Thishelpsyou
SeeallthestepsneededtocompletethegoalResearchhowtodoeachspecificstepAskothersforhelpeasilywhenyou’restuckonastep
Forexample,ifyouwanttobuildanappthattellsyouwhenyoucanexpectthenextbustoarriveclosesttoyourcurrentlocation,youcanlistthestepsasfollows:
1. Findyourcurrentlocation.2. Findthebusstationclosesttoyourcurrentlocation.3. Identifythespecificbusthattravelstotheclosestbusstation.4. Determinethelocationofthatbustravelingtothebusstation.5. Calculatethedistancefromthebus’scurrentlocationtothebusstation.6. Assuminganaveragespeedforthebus,convertthedistanceintotime
usingtheequationdistance=speed×time.7. Displaythetimetotheuser.
Thislevelofdetailisspecificenoughtostartresearchingindividualsteps,suchashowtofindyourcurrentlocationusingcode,anditgivesyouacompletelistofstepsfromstarttofinishfortheintendedgoal.
Atfirst,thestepsyoucreatemaybebroadorincomplete,butwithtimeyouwillimproveyourabilitytodetailthesesteps,whicharesometimescalledspecifications.
DistinguishCupcakefromFrostingWhetheryou’reathomecreatingyourfirstapp,oratworkonateambuildingawebsite,yourprojectswilltendtoincludetoomanyfeaturestobuildbyaspecificdeadline.Thisleadsinevitablytooneofthreeresults:Theprojectlaunchesontimebutisbuggy;theprojectlauncheslate;oryourteamworksovertimetolaunchtheprojectontime.Theonlyotherchoicesforaprojectbehindschedulearetoextendthedeadline,whichusuallydoesnothappen,ortoaddadditionalprogrammers,whichusuallyisnothelpfulbecauseofthetimeneededtogetthenewprogrammersup-to-speed.
Abetterstrategyistodecideupfrontwhichfeaturesarethecupcake—thatis,whichareessential—andwhicharetheunessentialfrosting,theonesthatarenicetohavebutoptional.Thisshowsyouwhereyourprioritiesare.If
yourprojectisrunningoverontimeorbudget,youcanbuildtheoptionalfeatureslaterornotatall.
Whenbuildingyourownappsmakesureyoudistinguishtheessentialfromtheoptionalfeaturesbeforeyouactuallystartcoding.Inthebusappexampleabove,determiningmycurrentlocationcouldbeoptional.Instead,Icouldselectonespecificbusstop,andfirstcompletesteps3through7.Then,iftimeallows,Icanmaketheappmoreflexiblebyfindingmycurrentlocation,andthenfindingtheclosestbusstop.
Thephraseminimumviableproductisusedbydeveloperstorefertothesetoffeaturesessentialtotheproperfunctioningoftheproduct.
GoogleIsaDeveloper’sBestFriendDevelopersconstantlyusetheGooglesearchenginetoresearcheithergeneralquestionsonhowtocodeafeature,orspecificquestionsonsyntaxforacommandortag.Forexample,imaginethatafewmonthsfromnow,afterreadingthisbook,youneedtoaddanimagetoawebsite.YourememberthatHTMLhasatagtoinsertimagesonawebsite,butyoudon’trecalltheexactsyntax.Toquicklyandefficientlyfindtheanswer,youcouldfollowthesesteps:
1. Gotowww.google.com.
2. SearchforHTMLimagesyntax.
Theprogramminglanguage,theintendedcommand,andthewordsyntaxshouldbesufficienttofindagoodsetofresources.
3. ForsyntaxquestionsinHTMLandCSS,youwilllikelyseethesedomainsnamesinthetop10searchresults,andyoushouldreadtheircontentasanextstep:
w3schools.comisoneofthebestresourcesforbeginnerstofindbasicinformation.developer.mozilla.orgisacrowdsourceddocumentationandtutorialsite.Itsdocumentationisveryaccurate,althoughsome
contentisnotbeginner-friendly.stackexchange.comandstackoverflow.comarecrowdsourceddiscussionsiteswheredeveloperscanaskandanswerquestions.w3.orgisthegoverningbodythatcreatesHTMLandCSSstandards.Itsdocumentationisthemostaccurate,butit’sdryandnotbeginner-friendly.
Youcanusethissameprocesstoresearchquestionsinothercodinglanguages,ortofindcodeexamplesfromotherdeveloperswhoarebuildingfeaturessimilartoyours.
ZapThoseBugsWhileyou’redoingallthiscodingyouwillinevitablycreateerrors,commonlyreferredtoasbugs.Therearethreetypesoferrors:
Syntaxerrorsoccurwhenyouwriteinvalidcodethecomputerdoesn’tunderstand.Forexample,inCSS,you’dwritecolor:blue;tochangethecolorofanelement.Ifyouwrotefont-color:blue;instead,you’dgenerateasyntaxerrorbecausefont-colorisaninvalidproperty.Semanticerrorsoccurwhenyouwritevalidcodethathasanunintendedeffect.Forexample,tryingtodivideanumberbyzeroisasemanticerrorinJavaScript.Logicordesignerrorsoccurwhenyouwritevalidcodethathastheintendedeffect,butthecodeproducesthewrongresult.Forexample,inJavaScript,convertingmilestofeetusingvarmiles=4000*feetisalogicerror.Althoughthecodeiswrittencorrectlyanddoeswhattheprogrammerwantsittodo,itstillproducesthewronganswer—thereareactually5,280feetinamile,not4,000.
YourbrowserwilldoitsbesttodisplayyourHTMLorCSScodeasyouintended,eveninthepresenceofsyntaxerrors.However,withotherprogramminglanguages,suchasJavaScript,codewithsyntaxerrorswon’t
runatall.Thebestwaytofindandeliminatebugsistofirstcheckyourcodesyntax,andthenthelogic.Reviewyourcodelinebyline,andifyoustillcannotfindtheerror,askanotherpersontotakealookatyourcode,orpostitonanonlinecommunityforumlikestackoverflow.com.
Developersusespecializedtoolsinthebrowsertodiagnoseanddebugerrors.YoucanlearnmoreaboutthesedevelopertoolsintheChromebrowserbygoingtowww.codeschool.com/courses/discover-devtools.
JustShipItReidHoffman,thefounderofLinkedIn,famouslysaid,“Ifyouarenotembarrassedbythefirstversionofyourproduct,you’velaunchedtoolate.”Whenyoustartcoding,youwilllikelybereluctanttoshowothersyourcreations,whetherit’syourfirstbasicwebsiteorsomethingmorecomplex.Hoffmanwascommentingonthisdesiretokeeptryingtoperfectwhatyouhavebuilt,andsaysinsteadtorelease(or“ship”)yourcodetopublicviewevenifyoufeelembarrassed.Regardlessofthesizeofyourwebsiteorapp,itisbettertoreceivefeedbackearlyandlearnfromyourmistakes,thentocontinueheadinginthewrongdirection.
Also,rememberthatthehighlytrafficked,highlypolishedwebsitesyouusetodaystartedinitiallyfromhumblebeginningandverysimpleprototypes.Google’sfirsthomepage,forexample,hadonlyafractionofthefunctionalityorstyleofitshomepagetoday.(SeeFigure16-1.)
Figure16-1:Google’soriginalhomepagein1998.
CollectFeedbackAfteryoufinishcodingthefirstversionofyourwebsiteorapp,collectfeedbackonyourcodeandonthefinalproduct.Evenifeverythingisworkingandyourwebsitelooksgreat,thatdoesn’tmeanyourcodewaswrittencorrectlyorthatyoursitedoeseverythingitcould.Forexample,YouTubeinitiallystartedasavideo-datingsite,butchangedtoageneralvideo-sharingwebsitebasedonuserfeedback.
Thebestwaytoobtainthisinformationistocollectquantitativeandqualitativedataonyourcodeandtheproduct.Measuringtheplaceswherevisitorsclickandhowlongtheystayoneachwebpagegivesyouquantitativeinformation,whichhelpsyoudiagnoseandimprovelow-performingpages.Youcancollectqualitativeinformationbysurveyingusers,eitherbyemailingthemsurveyquestionsorbywatchingpeoplein-personuseyourwebsiteandthenaskingquestions.Oftenthisdatawillsurpriseyou—usersmayfindconfusingthefeaturesyouthoughtwereobviousandeasilyunderstood,andvice-versa.Similarly,ifpossible,havesomeoneexamineyourcode,inaprocesscalledacodereview,toensurethatyoudidn’toverlookanymajorproblems.
IterateonYourCodeAfteryou’vecollectedfeedback,thenextstepisto“iterate”onthatfeedback:Keepcodinguntilthemajorissuesinyourfeedbackhavebeenaddressed,anduntilyouhaveimprovedboththecodeandtheproduct.Keepinmindthatit’susuallybesttoconfirmtheusefulnessofyourproductfirst,beforespendingtimeimprovingthecode.
Thisprocess—buildingaproductwithaminimumsetofessentialfeatures,collectingfeedbackontheproduct,andtheniteratingonthatfeedback—issometimesreferredtoastheLeanStartupmethodology.Inthepast,manufacturingprocesses,onceset,wereextremelydifficulttochange,butthesedays,changingsoftwareisassimpleasmodifyingafewlinesofcode.Thiscontrastswiththewayproductsusedtobecoded,whichinvolvedlongerdevelopmentcyclesandlessupfrontfeedback.
Justlikewithdocumentdrafts,savetheoldversionsofyourcodeincaseyourealizeanolderversionwasbetter,orintheeventyoufindbugsinthecurrentversionofyourcodeandyouhavetouseanolderversionofthecodetodebugit.
ShareYourSuccessandFailureWhilecodingyoumayhavecomeacrossdocumentationonawebsiteyoufoundconfusingorjustplainwrong.Maybeyoufoundagreatresourceoratoolthatworkedespeciallywellforaproductyouwerebuilding.Orperhapstheoppositehappened—nooneusedthefeaturesyoubuiltwithcode,andyouhadtogiveuptheproject.
Inallthesesituations,thebestthingyoucandoforyourselfandthelargercommunityistoblogaboutyoursuccessesandfailures.Bloggingbenefitsyoubecauseitshowsotherstheissuesyou’rethinkingaboutandtryingtosolve.Similarly,bloggingbenefitsotherswhowilluseGoogletosearchforandreadaboutyourexperiences,justasyouusedGoogletosearchforideasandsolveproblems.Manynon-technicalentrepreneurs,suchasDennisCrowleyofFoursquareandKevinSystromofInstagram,taughtthemselvesenoughcodingtobuildsmallworkingprototypes,builtsuccessfulproducts,andthensharedthatjourneywithothers.
YoucanblogforfreeandshareyourexperiencesusingbloggingsiteslikeWordpress(www.wordpress.com),Blogger(www.blogger.com),orTumblr(www.tumblr.com).
AbouttheAuthorNikhilAbrahamhasworkedatCodecademy.comforthelasttwoyears.AtCodecademy,hehelpstechnology,finance,media,andadvertisingcompaniesteachtheiremployeeshowtocode.Withhishelp,thousandsofmarketing,sales,andrecruitingprofessionalshavewrittentheirfirstlinesofcodeandbuiltfunctionalapplications.Inadditiontoteaching,hemanagespartnershipsandbusinessdevelopmentforCodecademy,andhashelpedbringcodingtoschoolsintheUnitedStates,Brazil,Argentina,France,andtheUnitedKingdom.
PriortoCodecademy,Nikhilworkedinavarietyoffields,includingmanagementconsulting,investmentbanking,andlaw,andfoundedaY-Combinator–backedtechnologyeducationstartup.HereceivedaJDandMBAfromtheUniversityofChicago,andaBAinquantitativeeconomicsfromTuftsUniversity.
NikhillivesinManhattan,NewYork.
DedicationThisbookisdedicatedtoMollyGrovak.
Author’sAcknowledgmentsThisbookwaspossiblewithhelpfromanumberofpeople.
ThankstoallthepeopleatWiley,includingStevenHayes,forkeepinganopenmindtoasmanyideasascanfitinonephonecall,andChristopherMorrisforeditsandhelpfuladvice.Also,thankyoutoallthetechnicaleditorial,layout,andgraphicsfolksforturningtextofvariablequalityintotextofoutstandingquality.
Thankstothoseofyouwhohelpedshapethecontentinthisbookandonline.ForeveryoneatCodecademy,includingZachandRyan,thankyouforthefeedbackonthechaptersandforansweringmyquestions.ThankstoDouglasRushkoff,forstartinganationalconversationonwhetherweasasocietyshouldprogramorbeprogrammed,andforbringingthismessagetoschools,
universities,andnon-profits.ThankstoSusanKish,forbeingtheonlyexecutiveIcanfindwhohasspokenpubliclyaboutherjourneylearninghowtocode(checkoutherTEDTalk!),andforseeingthefutureofcodingincorporations.ThankstoAliaShafirandJoshuaSlusarzforallthecodingsessionsyouhelpedorganize,leadersyouwrangled,roomsyoureserved,andlaptopsyourebooted.ThankstoMelissaFrescholtzandherleadershipteamforsupportingacultureofcode,andbringingcodeeducationeventoplaceswhereit’susedeveryday.ThankstoalumniatCornellUniversity,NorthwesternUniversity,UniversityofVirginia,andYaleUniversityfortestingearlyversionsofcontent,andhelpingmakeitbetter.ThankstothepeopleatDonorschoose.org,includingCharlesBestandAliAusterlitz,andatGoogle.orgforshiningabrightlightoncodingforwomenandgirls.ThankstoCode.orgformakingcodingaccessibleandcoolfortensofmillionsofkidsintheUnitedStatesandabroad.
Finally,thankstoMolly,whoorderedmoretake-out,brewedmoretea,andcleanedtheapartmentmoretimesthanIcancount.
Publisher’sAcknowledgmentsExecutiveEditor:SteveHayes
SeniorProjectEditor:ChristopherMorris
CopyEditor:ChristopherMorris
TechnicalEditor:TravisFaas
EditorialAssistant:ClaireJohnson
Sr.EditorialAssistant:CherieCase
ProjectCoordinator:MelissaCossell
CoverImage:©iStock.com/blackred
Toaccessthecheatsheetspecificallyforthisbook,gotowww.dummies.com/cheatsheet/coding.
Findout”HOW”atDummies.com
TakeDummieswithyoueverywhereyougo!
GotoourWebsite
LikeusonFacebook
FollowusonTwitter
WatchusonYouTube
JoinusonLinkedIn
PinusonPinterest
Circleusongoogle+
Subscribetoournewsletter
CreateyourownDummiesbookcover
ShopOnline
WILEYENDUSERLICENSEAGREEMENT
Gotowww.wiley.com/go/eulatoaccessWiley’sebookEULA.