coding for dummies® · 2020. 3. 28. · chapter 4: exploring basic html what does html do?...

283

Upload: others

Post on 15-Mar-2021

4 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing
Page 2: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing
Page 3: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 4: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 5: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 6: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 7: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 8: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 9: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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()

Page 10: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 11: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 12: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 13: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

explainasmanyconceptsaspossibleusingexamplesandanalogiesyoualreadyknow.

IassumeyouhaveacomputerrunningthelatestversionofGoogleChrome.TheexamplesinthebookhavebeentestedandoptimizedfortheChromebrowser,whichisavailableforfreefromGoogle.Evenso,theexamplesmayalsoworkinthelatestversionofFirefox.UsingInternetExplorerfortheexamplesinthisbook,however,isdiscouraged.

IassumeyouhaveaccesstoanInternetconnection.SomeoftheexamplesinthebookcanbedonewithoutanInternetconnection,butmostrequireonesoyoucanaccessandcompletetheexercisesonwww.codecademy.com.

IconsUsedinThisBookHerearetheiconsusedinthebooktoflagtextthatshouldbegivenextraattentionorcanbeskipped.

Thisiconflagsusefulinformationorexplainsashortcuttohelpyouunderstandaconcept.

Thisiconexplainstechnicaldetailsabouttheconceptbeingexplained.Thedetailsmightbeinformativeorinteresting,butarenotessentialtoyourunderstandingoftheconceptatthisstage.

Trynottoforgetthematerialmarkedwiththisicon.Itsignalsanimportantconceptorprocessthatyoushouldkeepinmind.

Watchout!Thisiconflagscommonmistakesandproblemsthatcanbeavoidedifyouheedthewarning.

BeyondtheBook

Page 14: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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!

Page 15: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

PartIGettingStartedwithCoding

Visitwww.dummies.comforgreatForDummiescontentonline.

Page 16: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

Inthispart…Understandwhatcodeisandwhatyoucanbuildwithit.Reviewprogramminglanguagesusedtowritecode.Codeforthewebusingfront-endandback-endprogramminglanguages.Followtheprocessprogrammersusetocreatecode.Writeyourfirstprogramusingcode.

Page 17: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 18: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 19: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 20: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 21: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 22: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 23: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 24: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 25: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 26: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 27: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 28: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 29: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

Figure1-7:GooglemapsusedfortheYelpwebapplication.

Page 30: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 31: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 32: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 33: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 34: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 35: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 36: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 37: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 38: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 39: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 40: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 41: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 42: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 43: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 44: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 45: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 46: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 47: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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?

Page 48: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 49: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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,

Page 50: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 51: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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:

Page 52: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.)

Page 53: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 54: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

Ifyourunintoaproblemorhaveabugyoucannotfix,trythefollowingsteps

Clickonthehintunderneaththeinstructions.UsetheQ&AForumstopostyourproblemorquestion,andreviewquestionsothershaveposted.Tweetmeat@nikhilgabrahamwithyourquestionorproblem,andincludethehashtag#codingFDattheendofyourtweet.

Page 55: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

PartIIBuildingtheSilentandInteractive

WebPage

BuildwebpagesusingHTML,CSS,andJavaScriptatwww.dummies.com/extras/coding.

Page 56: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

Inthispart…PlacecontentonwebpageswithHTML,andstylingcontentwithCSS.StructureyourwebsitelayoutwithHTMLandCSS.Createyourfirstwebpage—theAirbnbhomepage.AddinteractivitytowebpageswithJavaScript.AccessreallivedatawithAPIs.

Page 57: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 58: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

(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.

Page 59: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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>

Page 60: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 61: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.)

Page 62: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 63: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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>

Page 64: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

<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.

Page 65: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 66: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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>

Page 67: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 68: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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):

Page 69: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

<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

Page 70: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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!

Page 71: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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>

Page 72: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

<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>

Page 73: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 74: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 75: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 76: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 77: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 78: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 79: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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>

Page 80: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

<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.

Page 81: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 82: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 83: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

<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.

Page 84: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 85: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 86: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 87: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 88: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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-

Page 89: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

downmenus,rangesliders,dates,phonenumbers,andmore.(SeeTable5-4.)Additionally,inputfieldscanbesettoinitialdefaultvalueswithoutanyuserinput.

Table5-4Selectedformattributes

Attributename Possiblevalues Description

type

checkbox

email

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.

Page 90: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 91: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 92: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 93: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 94: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 95: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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:

Page 96: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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>

Page 97: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

<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:

Page 98: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.)

Page 99: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 100: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

Figure6-4:TheCSSrulesthatstyletheHuffingtonPostwebsite.

Figure6-5:ChangingtheCSSchangesthecoloroftheheadline.

CommonCSSTasksandSelectorsAlthoughCSSincludesover150properties,andmanyvaluesforeachproperty,onmodernwebsitesahandfulofCSSpropertiesandvaluesdothemajorityofthework.Intheprevioussection,whenyou“hacked”theCSSonalivewebsite,youchangedtheheadingcolor—acommontaskinCSS.OthercommontasksperformedwithCSSinclude:

Changingfontsize,style,fontfamily,anddecorationCustomizinglinksincludingcolor,backgroundcolor,andlinkstateAddingbackgroundimagesandformattingforegroundimages

Page 101: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 102: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 103: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 104: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 105: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 106: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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)}

Page 107: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 108: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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{

Page 109: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 110: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 111: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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;

Page 112: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

}

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

Page 113: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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".

Page 114: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 115: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 116: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 117: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 118: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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>

Page 119: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

<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>

Page 120: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 121: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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{

Page 122: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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>

Page 123: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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,

Page 124: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 125: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

SunMicrosystemsco-founderandventurecapitalist.HorseebooksisaspambotthatbecameanInternetphenomenon.

Figure7-4:Stylingafamilytreeofelements.

Figure7-5:ParodyTechandNon-TechTwitteraccounts(browserview).

Figure7-6:ParodyTechandNon-TechTwitteraccount(HTMLtreeorDocumentObjectModelview).

TheHTMLtreeiscalledtheDOMordocumentobjectmodel.

Childselector

Page 126: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 127: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 128: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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"

Page 129: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 130: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

bloat,andincreasedcontrolofpagelayouts.

OrganizingdataonthepageBeforedivingintoanycode,let’sreviewinFigure7-9someofthebasicwayswecanstructurethepageandthecontentonit.Layoutshaveevolvedovertime,withsomelayoutsworkingwellondesktopcomputersbutnotdisplayingoptimallyontabletormobiledevices.

Alwaysaskyourselfhowyourintendedlayoutwillappearondesktop,tablet,andmobiledevices.

Hundredsofdifferentlayoutsexist,andafewselectedpagelayoutsappearherealongwithexamplewebsites:

Leftandrightnavigationtoolbarsarenotusuallyseenonmobiledevices.Topnavigationtoolbarsareusedbothondesktopandmobiledevices,andbottomnavigationtoolbarsaremostcommononmobiledevices.

Figure7-9:Verticalandhorizontalnavigationlayouts.

Page 131: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 132: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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>

Page 133: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 134: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 135: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 136: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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;

Page 137: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

}

#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>

Page 138: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

<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

Page 139: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

site.5. Completetheinstructionsinthemaincodingwindow.Asyoutype,a

livepreviewofyourcodeisgenerated.6. Afteryouhavefinishedcompletingtheinstructions,clicktheSave

andSubmitCodebutton.

Ifyouhavefollowedtheinstructionscorrectly,agreencheckmarkappears,andyouproceedtothenextexercise.Ifanerrorexistsinyourcodeawarningappearswithasuggestedfix.Ifyourunintoaproblem,orhaveabugyoucannotfix,clickonthehint,usetheQ&AForums,ortweetmeat@nikhilgabrahamandincludehashtag#codingFD.

Page 140: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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,

Page 141: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 142: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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)-->

Page 143: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

<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

Page 144: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 145: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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>

Page 146: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

</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.

Page 147: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 148: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 149: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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>

Page 150: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 151: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 152: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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>

Page 153: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

</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

Page 154: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 155: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 156: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 157: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 158: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 159: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 160: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 161: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 162: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 163: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 164: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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:

Page 165: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 166: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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:

Page 167: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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".

Page 168: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 169: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 170: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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:

Page 171: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

<!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>

Page 172: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

</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

Page 173: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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"}

Page 174: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 175: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 176: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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:

Page 177: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 178: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

D3.jsisaJavaScriptlibraryforvisualizingdata.JustlikewithjQuery,similareffectscouldbeachievedusingJavaScript,butonlyafterwritingmanymorelinesofcode.Thelibraryisparticularlyadeptatshowingdataacrossmultipledimensions,andcreatinginteractivevisualizationsofdatasets.ThecreatorofD3.jsiscurrentlyemployedatTheNewYorkTimes,whichextensivelyusesD3.jstocreatechartsandgraphsforonlinearticles.Figure9-9isaninteractivechartshowingtechnologycompanyIPOvalueandperformanceovertime.

Figure9-8:PhotogallerywithjQuerytransitionimageeffectstriggeredbynavigationarrows.

Figure9-9:AnIPOchartshowingthevaluationoftheFacebookIPOrelativetoothertechnologyIPOs.

Page 179: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 180: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

PartIIIPuttingTogetheraWeb

Application

Toseehowtobuildyourownappusinggeolocation,checkoutwww.dummies.com/extras/coding.

Page 181: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

Inthispart…Plantobringyourfirstwebapplicationtolife.Meetthepeoplewhohelpbuildwebapplications.Researcheachcomponentofyourfirstwebapplication.Buildyourwebapplicationwithoffersbasedonlocation.Debugtheerrorsinyourfirstwebapplication.

Page 182: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 183: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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:

Page 184: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 185: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

halfyourtime,especiallyifthisisthefirsttimeyouarebuildinganapp.Youmightbesurprisedtolearnthatactuallywritingcodewilltakearelativelysmallamountoftime,withtherestofyourtimespentdebuggingyourcodetocorrectsyntaxandlogicerrors.

Appdevelopmentprocesseshavedifferentnames,andthetwobiggestprocessesarecalledwaterfallandagile.Waterfallisasetofsequentialstepsfollowedtocreateaprogram,whereasagileisasetofiterativestepsfollowedtocreateaprogram.AdditionaldiscussioncanbefoundinChapter3.

Figure10-1:Timeallocatedtocompletethefourstepsintheappdevelopmentprocess.

PlanningYourFirstWebApplicationYouoryourclienthasawebappidea,andplanningistheprocessofputtingthoseideasdownonpaper.Documentingallthefeaturesthatwillgointotheappissoimportant,becauseasthecartooninFigure10-2showsforwebdevelopment,andincomputersciencegenerally,itcanbedifficulttounderstandupfrontwhatfeaturesaretechnicallyeasyversusdifficulttoimplement.

Theplanningphasealsofacilitatesanupfrontconversationaroundtime,projectscope,andbudget,whereacommonsayingisto“picktwooutofthe

Page 186: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 187: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 188: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 189: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 190: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 191: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 192: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.)

Page 193: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

Figure10-6:SundarPichaioverseesalmosteverymajorGoogleproduct.

TestingwithqualityassuranceTestingisthefinalstepofthejourneyafteranapporwebsitehasbeenbuilt.Asaresultofthemanyhandsthathelpedwithproduction,thenewlycreatedproductwillinevitablyhavebugs.Listsaremadeofallthecoreappusertasksandflows,andhumantestersalongwithautomatedprogramsgothroughthelistoverandoveragainondifferentbrowsers,devices,andoperatingsystemstofinderrors.Testerscompilethenewlydiscoveredbugs,andsendthembacktothedevelopers,whoprioritizewhichbugstosquashfirst.Trade-offsarealwaysmadebetweenhowmanyusersareaffectedbyabug,thetimeittakestofixthebug,andthetimeleftuntiltheproductmustbereleased.Themostimportantbugsarefixedimmediately,andminorbugsarescheduledtobefixedwithupdatesorlaterreleased.Today,companiesalsorelyonfeedbacksystemsandcollecterrorreportsfromusers,withfeedbackformsandinsomecasesthroughautomatedreporting.

Page 194: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 195: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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:

Page 196: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 197: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 198: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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:

Page 199: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 200: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

Figure11-3:DifferentdesignsforflightreservationfromHipmunk.comandUnitedAirlines.

4. Createbasicdesigns,calledwireframes,andcollectfeedback.

Wireframes,asshowninFigure11-4,arelowfidelitywebsitedrawingswhichshowstructurallyhowsitecontentandinterfaceinteract.Wireframesaresimpletocreate,butshouldhaveenoughdetailtoelicitfeedbackfromothers.Manywireframetoolsuseasimplealmostpencil-likedrawingtohelpanyoneprovidingcommentstofocusonthestructuralandbiggerpicturedesign,insteadofsmallerdetailslikebuttoncolorsorborderthicknesses.Feedbackatthisstagetorefinedesignissoimportantbecausethefirstwireframelikelydoesnotaddressusers’mainconcernsandovercomplicatesthetasksauserneedstodo.

Withmobiledevicesincreasinginpopularityrelativetodesktopdevices,remembertocreatemobileanddesktopversionsofyourwireframes.

Page 201: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 202: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 203: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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:

Page 204: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 205: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 206: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 207: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 208: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 209: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 210: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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,

Page 211: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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:

Page 212: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

If(distance<0.5){alert("Yougetafreeburger");}else{alert("Thanksforcheckingin!");}

ThesyntaxforaJavaScriptif-elsestatementisavailableatwww.w3schools.com/js/js_if_else.asp.

Page 213: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 214: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 215: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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:

Page 216: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

<!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;}

Page 217: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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){

Page 218: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

//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

Page 219: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 220: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

Figure12-2:Thebrowserasksforyourpermissionbeforesharingyourlocation.

2. Updatelines12and13intheJavaScriptfilewiththelatitudeandlongitudeoftherestaurantnearyouservingastheMcDuck’sstore.

Afteryouhaveupdatedthelocation,makesuretochangethecommentinline10toreflecttheaddressofyourrestaurant(insteadofmyapartment).

3. Addanalertthatdisplaysthedistancebetweenyourlocationandtherestaurant.

Thedistancevariablestoresthemilesfromyourcurrentlocationtotherestaurant.Makearoughestimate—oruseamapforgreaterprecision—ofyourcurrentdistancefromtherestaurantyoupicked.Thenusinganalert,showthedistancebyinsertingthiscodebelowinline23.

alert(distance);

Ifthedistanceinthealertislargerorsmallerthanyouexpected,youlikelyenteredinincorrectvaluesforthelatitudeorlongitude.Ifthedistancematchesyourestimate,inserttwoslashes("//")beforethealertandcommentitout.

Page 221: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 222: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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:

Page 223: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 224: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

PartIVDevelopingYourCodingSkills

Further

SeehowtoprograminRubyandPythonatwww.dummies.com/extras/coding.

Page 225: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

Inthispart…LearnbasicprogrammingtasksinRuby.UseRubywriteasimpleprogramtoformattext.ReviewPythonphilosophyandbasiccommands.UsePythonwriteasimpleprogramtocalculatetips.

Page 226: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 227: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 228: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 229: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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!"

Page 230: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 231: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 232: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 233: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 234: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 235: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 236: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 237: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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-

Page 238: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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?"

Page 239: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 240: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

Rubycommands.4. Backgroundinformationispresentedintheupperleftportionofthe

site,andinstructionsarepresentedinthelowerleftportionofthesite.

5. Completetheinstructionsinthemaincodingwindow.6. Afteryouhavefinishedcompletingtheinstructions,clicktheSave

andSubmitCodebutton.

Ifyouhavefollowedtheinstructionscorrectly,agreencheckmarkappears,andyouproceedtothenextexercise.Ifanerrorexistsinyourcodeawarningappearswithasuggestedfix.Ifyourunintoaproblem,orhaveabugyoucannotfix,clickonthehint,usetheQ&AForums,ortweetmeat@nikhilgabrahamandincludehashtag#codingFD.

Page 241: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 242: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 243: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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,

Page 244: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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."

Page 245: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 246: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 247: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 248: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 249: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 250: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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!

Page 251: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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:

Page 252: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 253: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 254: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 255: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

(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

Page 256: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

tweetmeat@nikhilgabrahamandincludehashtag#codingFD.

Page 257: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

PartV

Page 258: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

ThePartofTens

Seeadditionalresourcestohelpyouprogramatwww.dummies.com/extras/coding.

Page 259: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

Inthispart…Continuetolearnhowtocodewithonlineresources.Stayuptodatewithindustrynewsandcommunitydiscussion.Solvecodingbugswithonlineandofflineresources.Keepinmindtentipsasyoulearnhowtocode.

Page 260: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 261: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 262: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 263: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 264: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 265: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 266: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 267: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 268: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

thelanguagename.3. ReviewtheMeetupgroups,andlookforoneswithagoodnumberof

members.Youcanjoinagroupandreceivenotificationsoffutureevents,orRSVPforaspecificupcomingevent.Someeventsmayhaveafeetocoverexpenses.

Althoughyoucanlearnalone,findingotherpeoplelearningtocodeisagreatwaytostaymotivatedandkeepupyourmomentum.Thepeopleyoumeetmaybelearningtocodeforthesamereasonsyouare,suchastobuildawebsite,improveskillsforanexistingjob,orfindanewtech-relatedjob.

Page 269: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 270: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 271: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 272: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 273: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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

Page 274: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 275: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 276: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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).

Page 277: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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,

Page 278: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

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.

Page 279: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

Publisher’sAcknowledgmentsExecutiveEditor:SteveHayes

SeniorProjectEditor:ChristopherMorris

CopyEditor:ChristopherMorris

TechnicalEditor:TravisFaas

EditorialAssistant:ClaireJohnson

Sr.EditorialAssistant:CherieCase

ProjectCoordinator:MelissaCossell

CoverImage:©iStock.com/blackred

Page 280: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

Toaccessthecheatsheetspecificallyforthisbook,gotowww.dummies.com/cheatsheet/coding.

Findout”HOW”atDummies.com

Page 283: Coding For Dummies® · 2020. 3. 28. · Chapter 4: Exploring Basic HTML What Does HTML Do? Understanding HTML Structure Identifying elements Featuring your best attribute Standing

WILEYENDUSERLICENSEAGREEMENT

Gotowww.wiley.com/go/eulatoaccessWiley’sebookEULA.