javascript: javascript awesomeness book (awesomeness … learning, video professor, d… · but if...
TRANSCRIPT
JavascriptAwesomenessLearntowriteJavascripttheawesomeway
GiladE.TsurMayer
Copyright©2016byGiladE.TsurMayer
Tableofcontent
Introduction
Chapter1:WhyLearnJavascriptAnyway?
Chapter2:WhatisJavascript?
Chapter3:DoIneedtoknowanythingbeforeIlearnJavascript?
Chapter4:Howtosetupyourpage
Chapter5:Simplealert,writetodocument
Chapter6:Comments
Chapter7:Variables
Chapter8:Variabletypes
Chapter9:Usingdifferenttypesofvar
Chapter10:Mathoperators
Chapter11:Functions
Chapter12:FunctionsParameters
Chapter13:MultipleParameters
Chapter14:ReturnStatement
Chapter15:Callingfunctionfromanotherfunction
Chapter16Ifstatement
Chapter17:Else&Elseif
Chapter18:Switch
Chapter19:Forloop
Chapter20:Array
Chapter21:ArrayTricks
Chapter22:JavascriptonSteroids
Chapter23:Nowwhat?
StopEverything!IHaveaPresentForYou!
OMG!OMG!!!OMG!!!Aren’tyouexcited?…whodoesn’tlovepresents???
ThisbookgetsyoutoknowJavascript,butpersonallyIprefervideosoverbooks–Imean,it’seasierifsomeonedoesalltheworkofreadingforyou,right?Youcanwatchabunchofvideosandbeanexpertinnotime.
So,Itookthisbook,andblendeditallintoabite-sizedvideocourse.ifyouwillwatchit,youwillknoweverybasicbuildingblockofJavascriptinnotime!Neat,huh?
Andbecauseyouhavepurchasedthisbook,Iwillgiveyou50%offthisvideocourse.Awesome,right?
Grabthevideoshere:http://basicjavascript.gilad.me/discount50/
Introduction
HeyGuys!
WelcometotheJavascriptAwesomenessCourse,whereyouwilllearntowritethebasicsofJavascript,theawesomeway!
MynameisGilad,andIwillleadyouthroughthisamazingcourse!
Ibeganmycareerasawebdeveloper,butsoontransitionedtoentrepreneurship,whereIfoundedmyveryownstartupcompany.
Currently,IworkatthecompanyIfoundedfromscratch,doingwhatIlovemost-teachingyouguys!
IdesignedthiscourseforanyoneseekingtolearnbasicofJavascriptandbeginacareerasarockstarwebdeveloper,aswellasanybodywhojustlovestoexpandtheirknowledge.
Bytheendofthecourse,youwillhavearocksolidknowledgeofallJavascriptbuildingblockssuchas:
●JavascriptVariables
●JavascriptFunctions
●JavascriptIfStatement
●JavascriptFormValidation
●Andmanymanymore…
IwillteachyouthelatestversionofJavascriptbythestandardsoftheW3CAssociation.Thesestandardsareusedbyallthemajorcompaniesintheworld.
Iwillnotonlycoverallthesetopics,butIwillalsogiveyouanopportunitytopracticethembygivingyouapopquizeverynowandthen.
TheidealstudentforthiscourseisanybodywhowantstoexpandtheirknowledgeofJavascriptorgetalegupinthewebdeveloperworld.
Totakethiscourse,youwillhavetoknowthebasicsofHTMLandCSS,andalsocomeopen-mindedtomysillyjokes!
Youarefreetotakealookatthecoursedescription,andIlookforwardtomeetingyouinside.
Chapter1WhyLearnJavascriptAnyway?
Didyoueversitinyourcomfycouchatyourhouseandwondered;
WhyJavascript?
Whatcanitdoforme?
Whyallthebuzzaboutit?
And,whatisanelephantdoinginmylivingroom?
Ifithappenstoyou,petyourbrandnewelephantrightaway.Andalso,joinmeinbeingmoreknowledgeableaboutJavascript.
Rightofthebat,Javasriptisreallycool!Youcanaddlogictoyourwebsite,makeitmoreinteractive,andalsomanipulateyourHTMLandCSSduetothatlogic!
Butifyouthought“cool”istheonlyfeatureofJavascript,thenyouarewrong,becauseJavascriptisalsorelativelyeasy,andit’sthebaseofthemostpopularframeworksoutthere,suchasangular.js,react.js,backbone.js,knockout,andevengoodoldJQuery!Whereveryoustep,onthewebdevelopmentworld,you’llseethefootprintsofJavascript.
Ifyoudesiretobeawebdeveloper,thenyoujustHAVEtobefamiliarwithjavascript.Andthat’swhyyouarehere,right?
SoI’mgladyouarehere.Let’sgetstarted.
Chapter2WhatisJavascript?
Here’saperson,calledBob.
Bobhaseyes,ears,nose,mouth…
Hehasabody,andalsosomeclothes…
Butuntilithasabrainthatfunctionseverythingtogether,it’sonlyabunchoforgansconnectedtoeachother.
JustlikeourweirdbutbelovedBob,youcansurelyknowHTML,andstructurehugewebsite.
Youcanalsodecorateandstyleyourwebsite,withyouramazinglyCSSskills.
But,ifyoulackinyourJavascriptskills,yourwebpageswilllookdullandold.
Javascriptistheprogramminglanguageoftheweb.Itisourfunctioningbrainthatkeepseverythingintouch.
Ifyouwantyourwebsitetobemoreinteractive,soyouruserscouldclickononeelementandbeamazedwhenitactuallydoessomething,besureyouhaveyourJavascriptskillswellputtogether.
Sosittight,andletusbegin.
Chapter3DoIneedtoknowanythingbeforeIlearnJavascript?
Althoughit’sajavascriptcourse,youwillneedtoknowatleastalittlebitofHTMLandCSStounderstandthecoursecontent.
IwilluseseveralexamplesthatusesHTMLandCSS,soifyoudon’tknowanyofthose,pleasegobackandstrengthenthoseskills.
IdohaveHTMLcourseandCSScourseforthosewhoneedsit,andbecauseI’msoawesomelygenerouswithyouguys,Iwillgiveyoua50%couponforanyofmyothercourses.
Youcangrabyourcouponhere:http://basicjavascript.gilad.me/discount50/
Onemorething;forallmyexamplesinthiscourseIwilluseNotepad++,whichisacompletelyfreetexteditor.
(youcangrabithere,forfree!:http://notepad-plus-plus.org/download)
However,ifyouhappentobeallergictomysuggestions,youcanalwaystryothersoftwareaswell.
Iwon’tjudgeyou,Ipromise!
*whispering*Iwill!…*whispering*
Chapter4Howtosetupyourpage
AlrightAlrightAlright!!!YouarealreadysoldaboutlearningJavascript,youaresupposedtobesetwithyourNotepad++,andyouwanttostartcodingJavascript,right?
Beforeyoudo,youneedtosetupyourpage:
Inordertodoso,allyouneedtodo,istowriteinsideofyourheadtag,atagnamedscript.Likethat:
<!DOCTYPE>
<html>
<head>
<scripttype=“text/javascript”>
#…JAVASCRIPTCODE…#
</script>
</head>
<body>
</body>
</html>
Insideofthescripttag,wewillhaveanattributecalledtype/javascipt,thattellsthebrowserwearehavingajavascripttypedscript.
Insideofthattag,youwillwriteyourJavascriptcode!
Chapter5Simplealert,writetodocument
OMGOMGOMG!!!I’msoexcited!!!…justlikeababytryingtowalkitsfirststeps,youareabouttowriteyourveryfirstjavascriptcode.
Andit’sgoingtocontain…*DrumsRoll*…
Printingafluffyredgoat!
Whyprintingafluffyredgoat,youask?
Becausethereisnothingmoresuspiciousthanwalkingdownthestreetandseeapersonprintinggoatsjustforthesakeofprintinggoats.Thatisred…and…alsofluffy.
Andthat’sthekindofthingswewanttobeassociatewith,thesedays.Leatherjacketsandafluffyredgoat.So…howarewegonnaprintourfluffyredgoatintoourscreen?
Allyouneedtodoistoprintdocument,followbyadot,andthentypethewordwrite.
Rightafterthat,youwillhavetoopenparentheses“(“andcloseparentheses“)”.insideoftheseparentheses,wewillhavequotationmarks.
Andinthequotationmarks,wewillwritedown“I’mprintingafluffyredgoat…”.Because…that’swhatwedo.
Andintheend,justlikeanylanguage,ifwewanttoendasentence,youwillwriteadot,right?
Butinjavascript,wearewritingasemicolon“;”.
document.write(“I’mprintingfluffyredgoat…”);
Wewillsaveourfile,andrefreshourpageand.Ohmy!
Wejustprintedourveryownfluffyredgoat!
Ah!Hack!That’stoogoodtobeasingularevent!
Let’sprintmoreofthese!
document.write(“I’mprintingfluffyredgoat…”);
document.write(“I’mprintingfluffyredgoat…”);
document.write(“I’mprintingfluffyredgoat…”);
document.write(“I’mprintingfluffyredgoat…”);
Yay……Wearehavinglotsoffluffygoats….!
OKOK!!!…Nowwewanttowarneverybody,beforeweareprintingourgoats,towatchout!Fluffyredgoatsareontheloose!Preferablywithannoyingpopuponthescreen!
Sowewillwritedownalert,andthenwewillopenparentheses,andinsideourparentheses,wewillhavedoublequotationmarksaswell,andthenwewillwrite“watchout!Redfluffygoatsareontheirway!”
Andwewillcloseourstatementwithasemicolon,asusual.
alert(“watchout!RedFluffygoatsareontheirway!”);
Nowsaveyourdocumentandrefreshthepage,and…oh!Iamveryimpressedbyyoursort-of-a-road-signthingy,warningeverybodyaboutwhatcouldbe…theendoftime!
Bytheway,didyouseethatweplaceouralertbeforethedocument.write,andrefreshedthepage,thealertshowedfirst,butyoudidn’tseetheanyofthetextonyourdocumentjustyet.
That’sbecausejavascriptisoperateasaqueue.Firstinthefirststatement,thenthesecondone…Andsoon!
Nowyouknowallaboutwritingandprintinginyourdocument,andallaboutannoyingpopups!Aswellasallaboutfluffyredgoats.
InthenextchapterI’llshowyouhowtowritecomments.
Chapter6Comments
Ssshhh!!!Ihavetotellyouasecret.
Yesterday,Iwenttoafortuneteller!
Isatonthechair,andthensheapproachesmeandsaid;
“awww…Mydearlybelovedalmighty,awesomelyhumbleGilad…Ihavetotellyousomethingaboutyourstudents…”
Andyouknowme,Icareabigdealaboutmyyoungpadawans,soIasked…“what?”
Soshetoldme;”Inthenearfuture,theywillbeworkingonaproject…aswebdevelopers!”
AndIwasshocked!Isaid“WHAT???AreyouSURE?Mystudents???”
Soshesaid:“Wa…Wait,Ididn’tgettothepointyet!”.AndIwaslike“oh…Yeah…well…Carryon“
“…Inthenearfuture,theywillbeworkingonaproject…Aswebdevelopers!!!…Andtheywillbeworkingwithotherwebdevelopersaswell!!!…“
“Otherwebdevelopers???Other???Areyousure???”
“Indeed.”
SoIranquicklytomyofficeandpreparedyouthislecture.
Ifyouareabouttoworkwithotherwebdevelopers,youwillhavetocommunicatewiththemproperly,andthereisnobetteroptiontodoso,butwithcomments!
Commentsareforyourownsolepurpose,andforyourcolleaguesaswell.
Yousee,Commentsarenotbeingrenderedonthepage,soyoucanwritewhateveryouwant,like“heyJeff,don’tmentionaboutyesterday,Iwasreallyhungry.And….yourcomputerwastheonlythingthattasteslikechicken!P.S,thislineofcodeisgettingeverythingfromthedatabase.”.
Sonowyouknowwhydoyouneedcomments,buthowcanwedothat?
Simplywriteinsideofyourscripttagtwoforwardslash,andstarttyping!
Likethat:
//HeyJeff!…Sorryaboutyourtastychickencomputer
Saveit,Refreshit,and….It’sachristmasmiracle!Justlikewe’veexpected:nothingrenders!
NowonlymeandmycolleagueJeffwouldknowaboutourlittleincident.
ButwhataboutifIwanttoleaveJeffmulti-linecommentaboutwhatIatefordinner…thelist
ofthingsI’mallergicto…andwhyIalwayslaughlikeacrazypersonwhenitrains?
Sointhatcasewewouldhaveoneforwardslash,followedbystar.Wewritewhateverwewanttowrite,andthencloseitwithstar,and…anotherforwardslash.
/*HeyJeff,Thanksforthepresentforchristmas,howeverIfeellikeWearenotinthatphaseofourrelationshiptosendingeachotherParkingtickets.
P.S.:Thiscodeisnotworking.
P.S.S:weareoutofmilk.Sogetone.thanks!*/
Hopefully,youwouldnotworkwithJeff,becauseheisahandful…
Butifyouwouldorwouldn’t,atleastnowyouknowhowtowriteJavascriptcomments.
Chapter7Variables
Doyourememberbackinschoolwhenyourteachersaidsomethingalongthelinesof…
X=98
Andthenshesaidsomethinglike:
“DannyjusteatXapples”,
Youallknew…Youallknewshe'stalkingaboutDanny,thatjustswallowed98apples,right?
That’sexactlyhowvariablesworksonJavascript.
JavascriptVariablesarelikelittleplaceholders,theystoreyourdata,andthenifyouwanttousethatdatalater,youjustcallthevariablename,anduseit!
Sobeforeyouwilluseyourvariable,youneedtodeclareanameforit.
Sotodeclarevariable,thelazyjavascriptpeoplejustshorthandthewordvariableintojust“var”…soyoushouldalwayswrite“var”first,andthen,youcancomeupwitheverynameforyourvariable,anynameyoucanthinkof…I’llwritemynameforexample,“gilad”
Then,youshouldwriteanequalsign,andthenwhatyouwanttoassignyourvariableto.
Let’ssaywewanttoprintthenumber9.
Andwewillcloseitwithasemicolonlikealways.
vargilad=9;
Rightnowyoualreadyknowhowtoprintstufftoyourpage,rememberourfluffyredgoat?
document.write(“I’mprintingfluffyredgoat…”);
Soerasethetextinside,andjustwriteyourvariable’sname(noquotationmarkneeded!).
document.write(gilad);
Saveit,andrefreshit.
Hollygoats!We’vegota9onourscreen!
Let’sexplainwhatjusthappened:
Yourbrowserthinkingforhimself,“ohalright,awesomely-cool-web-developer!Youwantmetosetavariable,andthenyoucallthevariable‘gilad’.Soi’llsetaplaceinmyroomjustforyou…AndIwillcallthatplace‘gilad’fromnowon…“
Thenwewrotetheequalsign…sothatmeansyousetittowhateverontherightsideoftheequalsign.
Whichis9.
Sothecomputersays“ok,I’llnowstore9,inmyplacecalled‘gilad’.AndIpromiseyou,Iwilluseitwhateveryouwilltellmetouseit…“
Thenwhenwecalledthe‘gilad’variableinsideour ‘document.write’ ,thecomputertookthevalue,andprintitinsideofthedocument.
Oh,butonemorething…DoyourememberItoldyouaboutthenameofvariable,andthatyoucannameitwhateveryoulike…Well…youcan.
Butyouhave2rulesyouhavetokeep,ok?
Rulenumberone:
Don’teverwriteanythingfunkylikethat: #5^$%^^$. Yourbrowserwillgobananas,
andwouldn’tknowwhatyoumeanbythatname!Youcanonlycallyourvariablesbyletters,
numbers,andunderscores.
Rulenumbertwo:
Javascriptiscasesensitivelanguage,sodon’tcallyourvariable jeffery ,alllettercase,and
thenafterwardscallit JeFferY likeacrazyperson.Forthebrowser,It’slikeyouwillcall
Somegirl“Hillary!”andthenswitchto“HeyBrittney!SupBrit…Imean…Doris!…Doris!!!
Jenni…Bath!…Elizab…Doris!!!Doris…”
Yeah…sodon’tdothat…Otherthanthat.You’resafe!
Chapter8Variabletypes
Doyourememberwhenyouwereababy,youhadthisweirdgameofshapes,andyouweresupposedtosortthoseshapesandputeveryshapeintoitsplace?
Justlikethatgame,Javascripthasdifferenttypesofvariables.Andtheycannotfiteverywhere…
Letmeexplainittoyoubyfirstwritingitdowninourtexteditor:
Iwillwrite var ,name,equalsto9:
varname=9;
document.write(name);
That’swhatwe’vedoneinthelastlecture,right?
Wehaveavariablenamedname,andit’sequaltothenumber9.
But,mynameisnotnine,right?(Iswearit’sdoesn’t!)
Let’strytoerasethenumbernine,andplacemynameinstead.
varname=gilad;
document.write(name);
Saveit,refreshit,andlet’sseewhatwehavehere…
ah!Nothingshows!Whathappened?
Thedifferencebetween9andagilad,isthat“gilad”isatext(orasJavascriptliketocallit:a“string”).And9isjustanumber.
Thethingis,javascriptcouldeasilythinkthatgiladmaybejustanothervariable,andbecauseitcouldbeavariable,it'stryingtolookforitintheentirepage,andwhenitcouldn’tfindit,itjustsays…“OhWell,alright…Ididmybest,Icannotfinditanywhere…SoI’lljustdonothingandrelax…”(givingupearly,huh?)
TosayexplicitlytoJavascriptthatwehaveastringhere,weneedtowrapourtextinsideofquotationmark.
Let’sdothat:
varname=“gilad”;
document.write(name);
Saveit,refreshit,and…yeahbaby!We’vestillgotit!
Sonowweknowthatwehavetwodifferenttypesofvariables.
Numbers,andstrings.
Andthedifferencebetweenthemisthatlittlequotationmark.
Wehaveafewmoretypesofvariablesinjavascript,andwewillcovertheminlaterlectures.
Chapter9Usingdifferenttypesofvar
DidyouknowthatJavascriptcanmakeyourhomework?
IfIknewthat,IwouldstudyJavascriptatage5!
Here’sanexample:
document.write(3+3);
Thatcouldcomehandyinfirstgrade,don’tyouthink?
Hmm…let’strysomething…
I’lldeclaretwo vars ,thefirstoneIwillname num1 andsetitto4,andthensecondone,Iwillname num2 ,andsetittothenumber2.
Nowinthe document.write ,Iwillreplacethe3+3into num1+num2 ,andrunit.
varnum1=4;
varnum2=2;
document.write(num1+num2);
Alright…we’vegot6.Awesome!We’velearnedsomethingnew!Wecanactuallyaddvariablestogether!Imaginethepossibilities!
ButIwonderwhatwouldhappenedifIwouldchange…say… 4, into“ 4 ”,youknow,asastring…
Alright,let’sputourmadscientistgogglesandtryitout:
varnum1=“4”;
varnum2=2;
document.write(num1+num2);
Oh,that’sweird…42?
Imean,Iknowtheanswertolife,theuniverseandeverythingis42,but…Ididn’taskthat…
Let’sseewhathappened:
First,wetyped num1 ,equalsto4.Butsincewehaveourquotationmarkaround4,itwouldbeconsideredas“string”andnotasnumber.Soourbrowsermerelyprinted4onthescreen.Andthen,weadded2.Butsinceour4isonlyastring,ourbrowserdidn’tthoughtit’samath
problem,andjustaddedittothescreen,asis…
Sowecouldeasilyreplace4to“Iloveyou“
Andifwewillrefreshthepage,wecanseethatyourbrowserlovesyou2.
Browser!!!Sillyyou….
Chapter10Mathoperators
Inmath,wehave4basicoperationsthatyoucanmake.
Addition,subtraction,multiplication,anddivision.
Inthelastlecture,We’vealreadyseenthatwecanaddnumbersinjavascript.
varnum1=4;
varnum2=2;
document.write(num1+num2);
Butapartfrombasicaddition,we’vegotanothermathoperationinJavascript.
Let’stakeatakealookattherestofthem.
Wehavegotsubtraction:
varnum1=4;
varnum2=2;
document.write(num1-num2);
Yousimplymaketheminussign.
Ifyouwanttomultiplynumbers,don’twritethexletterorsomethinglikethat,simplywritestarinstead:
varnum1=4;
varnum2=2;
document.write(num1*num2);
That’sMultiplication.
Wecandividenumbersaswell.
Allyouneedtodo,istotypeaforwardslash.
varnum1=4;
varnum2=2;
document.write(num1/num2);
Sothat’sdivision.
NowI’vegotabonusforya!
Let’ssayyouwanttoincrementanumberbyone.
So…ofcourse…youcantypesomethinglikethat…:
varnum1=4;
document.write(num1+1);
But!Ifyouarealazypersonlikemyself,youcanshorthandanddothat:!
varnum1=4;
document.write(num1++);
Orsomethinglikethatifwewantanumbertobedecreased:
varnum1=4;
document.write(num1--);
Theplusplus(++)sign(andalsotheminusminus),willincrementor…decrement?(Canwesaydecrement?!)yournumberbyone.It’sshortanddandy,andwewillalsoseethatalotinourfuture,whenwewillencountermorecomplexstuffonJavascript!
Chapter11Functions
Here’saTruestory:
WhenIfirstcameoutfrommyparents’house,Ihada…well…a…littletiny…Really…mini-ti…tiny-problem.
Well,yousee?Ihatecleaning,andwhenIfirstcameoutfrommyparents’house,nobodywascleaningafterme(ahh!!!Thehorror!).Soafteradayortwo,Ihadtonsofdishesinmysink,mycleanclothsblendperfectlywithmydirtyclothesonmybed,myfloorwascompletelyamess,andmytwocatsdidn’treallyhelp(meow!).
SothefirstthingI’vedone,istogetmeonethoserobotswhocleanthefloorafteryou.
Aperfectsolutionforthelazymaninourera.
AndIwasveryglad!Itwasarepetitivetask,thatIcouldhavedonemyselfformanytimes,thatsomesortof…robot:isdoingitforme!
SoifwegotoourworldofJavascript,youmayalreadythinkthatthereisapossibilitytocodetheSAMEcodeoverandoveragain…
Andifyouarelazylikeme…well…youwillneedtofigureouthowtomakeyourselfanewrobot!
Tothisrobot,theJavascript-peoplecalled“Function”s.
Insteadofwritingthesamecodeoverandoveragain,yourFunctionwillbasicallystoreasegmentofyourcode,andwhenyouwouldliketoexecuteit,youcancallit,andthefunctionwillrun.
LikeIalwayssay,Let’sseesomeexample,andyouwillunderstanditbetter:
Let’ssaywewanttohaveafunctionthatwillcongratulateuseverytimeweenterourwebsite.
So,inordertowriteafunction,allyouneedtowriteis….
“function”!
Sogoahead,andwritefunction,andthenyournameofthefunction,andjustlikeyourvariables,youcannameitwhatevernameyouwant,butit’sagoodpracticetogowithameaningfulofwhatyourfunctionneedstodo.Soifwewanttocongratulateyourusers,let’scallit“Congrats”.
Andthenafterthename,weneedtoopenparenthesis,andcloseparenthesis(bytheway,thoseparenthesis’areactuallyhaveameaning,butfornow,justleaveitwithoutanythinginside).
Thenopencurlybracketandclosecurlybrackets.Andinsidethecurlybracketswewilltypeourcodethatwewanttobeexecutewhenwecallthefunction.
functionCongrats(){
//….javascript“congrats”code…
}
Wewantourcodetocongratulateourusers,solet’swritesomethingonalert…Let’ssee…
“Welcometothe‘hamster-mobile’website.Whereyoucanfindacheapvehicletoyourbelovedhamster…“
Well,Ithinkweknowwhatournextstart-upwouldbe,right?Ihopewedon'thaveanycompetition…hmm…
Ihavetocheckthisone…
Oh…man…Icannotbelieveit!
ApparentlythereISahamster-mobile…ohhh…mydreamsjustshutteredlikewindows8…
HowcanIrecoverfromthisone?
Anyway…
Let’salsoaddabitofcodethattellusourcongratulationalerthasjustbeenstarted.Andalsoonetextthatourcongratsjustended.
Let’srunourthing!
Nothingshows!Iwonderwhy?
That’sbecausewesetourfunction,butwedidn’tcallit,right?
Solet’scallit.Justtypeanywhereoutsideofyourfunction,yournameofyourfunction,andthenopenparenthesisandcloseparenthesis.Andthenendwithsemicolon:
functionCongrats(){
document.write(“startingcongratulations…”);
alert(“Welcometothehamster-mobilewebsite.
Whereyoucanfindacheapvehicletoyourbeloved
hamster…“);
document.write(“endingcongratulations…”);
}
Congrats();
Saveit,refreshyourpage,and…BAM!We’vegotourweirdlycongratulationsupand
running!
Noweverytimeyouwanttousethisthing,wewouldn’tneedtowriteourdocumentwriteagain,andouralert…Andanothertimethedocument.write…WejustneedtocallourCongratsfunctionagain,andthat’sit!
Congrats();
Congrats();
Chapter12FunctionsParameters
Doyouknowthatgameshowcall“Let’smakeadeal”,thatdoyouhave3curtains,andyousupposetoguesswhichcurtainhasthebrandnewshinycarandwhichonehaslikealivingadultllama?
Ialwayswonderediftheyactuallyhavetotakethellamaafterwards…Andfeedit,cleaningafterit,bebestfriendwithit…Eveniftheyareallergictothatllama,buttheydon’tfeelsafeenoughbecausethatLlamaisaviciousLlama…
Anyway…
TodaywewillhavetheJavascriptversionoftheshow“Let’smakeadeal”!
First,wewillhave3inputs,typedbutton.Eachandeveryoneofthem,willrepresentacurtain.
Curtain1,curtain2andcurtain3.
<inputtype=”button”value=”Curtain1”/>
<inputtype=”button”value=”Curtain2”/>
<inputtype=”button”value=”Curtain3”/>
Nowlet’smakeroomtoourfunction:
Createanewfunctioncalled ShowCurtain ,butinsteadofleavingtheparenthesisorphaned,typeprize.(don’tworry,wewillexplaineverythinginamoment,justletmefinishupthisfunction…)
Nowwewillwriteinsideofthefunctionanalert,with“youwon”message,andalso,thesameprizethatwehaveinsideofourparenthesis.
functionShowCurtain(prize){
alert(“Youwon”+prize);
}
Alright,let’sexplainwhatisthatprizethingy…
Whateverwehaveinourparenthesis,called“parameter”,andourparameterisactuallyactinglikeadynamicvariable…
Thatmeans,whenwewillcallourfunction,wewillsettheparameterinourparenthesesjustlikeweseteveryvariable…Andthen,ourparameterwillliveandbeusedaslongasthefunctionisrunning.
Alright,solet’strysomethingnew,ey?
Insteadofcallingourfunctionthelasttime,wecancallitwhenourbuttonisbeingclicked.
Soaddtoeachbuttonanattributecalled“ onclick ”,andsetittoyourfunction,andremember,ourfunctionasksforaprizeparameter,sosetittowhateverprizeyouwanttoget.AndbecausewealreadyuseadoublequotationmarkforourHTMLattribute,usesinglequotationmarkinsteadtowrapourstring…Thatshouldwork.
<inputtype=”button”value=”Curtain1”onclick=”’ashinybrandnewtoothpick!’”/>
<inputtype=”button”value=”Curtain2”onclick=”’acolorfulrubberband’”/>
<inputtype=”button”value=”Curtain3”onclick=”’alivingLlama!’”/>
Alright,saveit,refreshyourpage,andlet’strytoseewhatwe’vegothere:
Let’sopenourcurtainnumber1…Its…its…yes!!!Ashinybrandnewtoothpick!veryhandy…veryhandy…
…Nowcurtainnumber2…Thecrowdroarwithenthusiasm…it’s…ohmy!Acolorfulrubberband!!!Cannotwaittouseit!
Now…curtainnumber3…whatitwouldbe?ohmy!!!Icannotbelieveit…myall-timefavorite!Alivingllama!!!whowouldfeedthisanimal!?
Icannotbelieveit…Whatawonderfulday…
Javascriptfunctionparameters???andalivingLlama?!Whatmorecananinstructoraskfor?!
Chapter13MultipleParameters
Sometimes,youcanhavefunctions,thatcanholdparameters,butyouwillneedtoaddanotherparameteraswell.
Inourlastexample,wehadoneparameterthataskedtheprizemoney,andwehadamessagethattellstheuserwhatprizethathewon,butwhatifwewanttoaddanotherinformation,like,whatcurtainnumbertheuserjustopened?
Ifwewouldliketoachievethiskindoftask,wecanaddanotherparametertoourparenthesis.
Justaddacomma,andtypetheextraparameternameyouwanttoadd.
Forexample,tomakeourmessagecooler,wewilladdanotherparametercalled curtainNumber ,andthenpromptinourmessage“Youopenedcurtainnumber”andthenwewillhaveourparameter,andwewillcontinueourtextwithwhathewonlikewehavedoneinthelastexample:
functionShowCurtain(curtainNumber,prize){
alert(“Youopenedcurtainnumber”+curtainNumber+“,Youhavewon”+prize);
}
Nowwewilladdthedifferentcurtainnumberstoourbuttons,sotheparameterknowshowtobesetup.
onclick=”1,’ashinybrandnewtoothpick!’”
Butnotethattheorderoftheparameterisimportant,ifwehaveour curtainNumber thefirstparameter,wewillneedtosetitfirstaswell…
Alright,let’stestourcurtains!
Works!
yay!
Chapter14ReturnStatement
Inthepreviouslectureswetalkedaboutfunctionsandourfunctionsjustdidsomething,right?
Weprintthingsonthescreen,pressonebuttonandamessagepoppedout,stufflikethat…
Butinsomecasesyouwantyourfunctiontoreturnsomevalue,soyoucoulduseitlater.
That'swhywehaveourreturnstatement.
Let’shaveanexample:
Writeafunctioncalled BasicAddition, thatrequest2parameters, num1 and num2 .Itwillreturntheadditionofbothofthem.
functionBasicAddition(num1,num2){
returnnum1+num2;
}
Nowwewillcallthefunction,andwewillplacetheparameters1and2.Andwewillexpecttogetthenumber3beout,right?
BasicAddition(1,2);
Ifwewillrunitrightnow,nothingwillshows.
Andthisisbecausewedidn’ttellourfunctiontodoanythingwithit.Itdidn’tprint,anddidn’tevenstoreitanywhere.
Let’smakeanewvariable,called result .Andwewillgettheresultrightoutofour BasicAddition function.Andthen,wewillprintresulttothepage.
varresult=BasicAddition(1,2);
document.write(result);
Let’ssaveitandrefreshit,and…bam!We’vegotit!
Wereturntheresultofthenumberweadded,westoreditonavariablecalledresult,andthen,weusedthevariablecalledresult,andprintitonthepage.
Chapter15Callingfunctionfromanotherfunction
Oksoyoualreadyknowhowtowriteafunction,andhowtowriteaparameterforthisfunction,andevenmultipleparameters,andeven…(Godforbid!),areturnstatementforthisfunction!
NowI’llshowyoualittletrickthatwillcomehandyoneday…
Youcanactuallycallafunction…withinafunction!
Let’stryitout,createafunctioncalledGoodNight,andanotherfunctioncalledGoodMorning.Withouttakinganyparameters.
InsideoftheGoodNightfunctionwewouldhavedocument.write,andwewillsay“Goodnight!”andintheGoodMorningfunction,youguesseditright,wewilltype“Goodmorning!”
functionGoodNight(){
document.write(“GoodNight!”);
}
functionGoodMorning(){
document.write(“GoodMorning!”);
}
Andnowwewillhaveanotherfunction,calledStart,itandwewillcallbothfunctionsfromtheStartfunction.
functionStart(){
GoodMorning();
GoodNight();
}
Rightnow,ifwewillrefreshourpage,nothingwillhappen,becausealthoughwecalledGoodMorningandGoodNight,wehavenotinitiatetheStartfunction.OnlywhenwewillcalltheStartfunction,wewillseestuffgoingon.
Let’sdothat!
Start();
See?WhenwestartedStartfunction,werunalsobothfunctionswithinit.
Nowlet’strytobreakourbrowserapart.(don’ttryitathome!Nahh…kiddin’.Youcan!)
WewilltaketheGoodMorningfunction,andplaceitwithintheGoodNightfunction,andviceversa,andthenwewillcallstartbytellingittocallGoodMorning.(andforthesakeofreadability,addabrtagtoeachwritestatement.
WewillexpectthebrowsertogotoGoodMorningandsaygoodmorning,andthengotoGoodNightandsay“goodnight!”.Andthenbacktogoodmorning,goodnight,goodmorning,goodnightgoodmorning,goodnightgoodmorning…Hesupposedtogetinsideofsomesortofalimbo…leavingitswifeanditschildren…Andevenitsownsanity!
functionGoodNight(){
document.write(“GoodNight!<br/>”);
GoodMorning();
}
functionGoodMorning(){
document.write(“GoodMorning!<br/>”);
GoodNight();
}
functionStart(){
GoodMorning();
}
Start();
Let’srefreshit,and…oh…wow…Betterthanfireworks!
Chapter16Ifstatement
BeforeIwantedtobeawebdeveloper,Ialwayswantedtobeahamster-tamer.
Youknow,justlikealiontamerthatworkswithlions…But…withhamsters.
Yousupposetotamethem,sotheycan…dostuff.
Anyway,sometimesIwonderwhatifIwasgoingwithmydream.
Andtomakethisthoughtcometrue,Iwillusemyjavascriptskills!
InJavascript,youcanhaveconditionsinyourcode.
Forexample:
Ifxistrue,then…executethiscode.
Ifxisfalse…Then…dothatcode.
Ifxisgreaterthany,thenrunthosefunctions…
Let’smakeithappened!
Towriteanifstatement,youshouldtypeif,thenopenparenthesis,andtheninsideofthoseparenthesisyoushouldwriteyourcondition.
Thenyoushouldopencurlybrackets,andinsideofthosecurlybrackets,yourcodewillbeexecute,onlyiftheconditionistrue.
if(##YOURCONDITIONHERE##){
##YOURCODEHERE##
}
Solet’ssaywewanttocheckifthenumber2isreallyequalstothenumber2.(you’llneverknow,right?)
Let’smaketwovariables, num1 and num2 .Andwewillsetbothto2.
Sointhecondition,type num1==num2 .
Notethatwearehavingtwoequalsigns,andnotjustoneequalsign.Thereasonforthat,isthatifwewilltypejustoneequalsign,thebrowserwillmightconfuseandthinkwewanttosetanewvariable.Sotwoequalsignisthewaytogo,ifyouwanttocheckifsomethingisequaltosomething.
Let’schangeourcodeheretojustsay“IfIwasahamster-tamer,mycowwasbroken”,becauseshemightbesomeday!
varnum2=2;
varnum1=2;
if(num1==num2){
document.write(“IfIwashamster-tamer,mycowwasbroken”);
}
Andlet’srunthisthing!
Andindeedthat’strue,2isequalto2,afterall,andwehaveabrokencowjustnow.
Whatifwewanttocheckratherif2isnotequalto2.
Weshouldtypeinsteadoftwoequalsign(let’serasethat),weneedtotypeexclamationmark,followedbyequalsign.That’s“notequal”.
Solet’stestjustthat.
if(num1!=num2){
document.write(“mycowisbroken”);
}
Let’srefreshthat,andyup!Aswesuspect!Wedon’tgetanymessage,thatmeansthat2stilldoesequalto2,andbecausewecheckforifit’snotequal,thecodedoesn’tfire…
Ifwewillchangenum1intothenumber3,andrunthecodeagain,wewillseethatthecoderunperfectly,because3isnotequalto2.
Let’slearnanotherone!Whatifwewanttocheckratherif3isgreaterthan2.
Wewillchangeourconditiontothisfunkyanglebracket…
varnum2=3;
varnum1=2;
if(num1>num2){
document.write(“mycowisbroken”);
}
Ifwewanttocheckif2isgreaterthan3,weneedtochangeittoagreatersign.
if(num1<num2){
document.write(“mycowisbroken”);
}
Nowwecancheckifonenumberis“lessthan”theother,orequal…
if(num1<=num2){
document.write(“mycowisbroken”);
}
Soifwewillcheckthenumber4,itwon’trun,3,itwon’trun,2…?bam.Gotit.
Andwecanalsocheckifit’s“greaterthan”or“equal”
if(num1>=num2){
document.write(“mycowisbroken”);
}
Cool!
Chapter17Else&Elseif
Let’ssayyouhaveacondition,forexample….theword“banana”equalstotheword“banana”:
Andwhenitdoes,youwillhaveafunctioncalled“ChoppingBanana”.
if(“banana”==“banana”){
ChoppingBanana();
}
Tillnow,nothin’new,right?
Bananaisabanana,andthecodewillbefire.
AndifIwillreplaceoneofthebananasintoaPineapple…theChoppingBananafunctionwillnotbefired…right?
Butlet’ssayIwantsomeotherfunctiontobefireiftheconditionisnottrue?WhatdoIdo?
Inthiscase,weneedtotyperightafterourlastcurlybracketsan“else”statement.andanothercurlybrackets,andinsideofthosecurlybracketswecanwriteourcode.
if(“banana”==“pineapple”){
ChoppingBanana();
}else{
ChoppingPineapple();
}
Ifwewant,wecanwriteanotherconditionaswell,wewillwrite“elseif”andanothercondition,say“banana”equalsto“cherry”,andthenanothercurlybrackets.
if(“banana”==“pineapple”){
ChoppingBanana();
}elseif(“banana”==“cherry”){
ChoppingCherry();
}
else{
ChoppingPineapple();
}
Sointhisexample,thebrowserwillgofirstintothefirst if, andasktheconditionratherifabananaisapineapple.Ifit’snottrue,thenhewillgotothenextif,the“elseif”,andask…“Doesabananalookslikeacherry?”,wellitdoesn’t…Oh!Onemorething…Youcanhaveasmanyelseifaswecanwish!!!Wecanhavelike…Agazillion elseif …Ifsomeconditionistrue,itwillbefirethecodeinsideofit,andleavethewholebunchof ifs and“else”and“ elseifs alone…Butifitdoesn’t,itwillcontinuetoaskuntilitgetstothelastelse.
Theelseisthefinaltryofourbrowser,ifno if statementandno elseif wasfired,thanourbrowserwillbesatisfiedandgoin.
Ifyourbrowservisitedanycondition,the else statementwillnotbefired.
Chapter18Switch
Whoknows,maybesomedayyouwillhaveyourownwebdevelopmentcompany.
Andasanyotherbigcompany,ithasitsown…vendingmachine!
Butwearenotlikeanyotherbigcompany,right?ourvendingmachinewillbespecial!
Sowewillhavethe…*drum*
TheVendingPendingMachine!
Ourvendingmachinewillmakeyoupending.And…that’sit.Nosodaoranything.Just…waitforawhile,andgoaway.
Alright,sofirst,ofcourse,wehavetobuildourvendingpendingmachinetitle,sowewilladdafewshticksinHTML…
<h1>TheVendingPendingMachine</h1>
<inputtype=”button”value=”1”/>
<inputtype=”button”value=”2”/>
<inputtype=”button”value=”3”/>
<inputtype=”button”value=”4”/>
NowLet’sbuildtheVendingPendingMachinefunction.
Iwilltypeafunctionnamed VendingPendingMachine ,thatasksfora pendingTime parameter,andinsideofourfunction,Iwillinitiatea switchcase statement,letmetypeitdown,andIwillexplainitfurtherafterwards:
functionVendingPendingMachine(pendingTime){
switch(pendingTime){
case1:
//CODEFOR#1…
break;
case2:
//CODEFOR#2…
break;
case3:
//CODEFOR#3…
break;
Default:
//DEFAULTCODE…
}
}
Sothebrowsercomestoourfunction,withaparameterinhand,let’ssayithasthenumber1asaparametervalue,thencomestothe switchcase statement,itsetsthe switchcase withthe pendingTime as1,andthenitsearchfortherightcase,ifcaseis1,thenitcomestothefirstone,ifcasenumber2,thenitfiresthesecondone…Andsoonandsoforth…Itcouldbeevenanamelike…“Hamster”,iftheswitchisequaltothecase,thenitwillfireourcode.
Ifnocasematchesourcases,thenitwillbefireourdefaultcase,but…Ofcourse…Itsoptionalcase…
Let’spopulateourcases!
Wewillmakeamessagefunction,sothevendingpendingmachinecouldsaytoourusers,howmanyminutestheyaresupposetowait…
functionPendingMessage(time){
alert(“TheVendingPendingMachinesays
youhavetowait”+time+“minutes”);
}
SoIwillwriteafunctioncalled PendingMessage ,thatgetsa time parameter,andthenprintsthemessagewiththe time parameterwegot.
functionVendingPendingMachine(pendingTime){
switch(pendingTime){
case1:
PendingMessage(pendingTime);
break;
case2:
PendingMessage(pendingTime);
break;
case3:
PendingMessage(pendingTime);
break;
default:
PendingMessage(pendingTime);
}
}
functionPendingMessage(time){
alert(“TheVendingPendingMachinesays
youhavetowait”+time+“minutes”);
}
Nowweneedtoplaceourfunctionsinsideofourbuttons:
<inputtype="button"onclick="VendingPendingMachine(1)"value="1"/>
<inputtype="button"onclick="VendingPendingMachine(2)"value="2"/>
<inputtype="button"onclick="VendingPendingMachine(3)"value="3"/>
<inputtype="button"onclick="VendingPendingMachine(7)"value="4"/>
Alright!
Let’stryourvendingpendingmachineforthefirsttime!
Let’spressbuttonnumber1.
Wewillhavetowait1minute…(Butwewon’t…because…Idon’twannawait.)
Let’spressnumber4,weshouldgetintoourdefaultcase…
Wehavetowait7minutes…Ohno…
Ok…yougotothenextlecture,I’llwaithere.
For….7minutesIguess.
Chapter19Forloop
Backinthedays,andstillintheSimpson’sepisodes,therewasawidespreadpunishmentfornaughtystudents.Writinglikeagazilliontimeswhattheydidwrong…Forexample…“Imustnottalkinclass”or“Iwon’tforgettodomyhomeworkagain”…Andstufflikethat.
Sotodaywewillbreakallthenaughtystudentsfree,withourshinynewMachine,thatwritelinesforyou!
Sofirstofalllet’smakeourdocumentlookslikechalkboard…
<style>
body{background-color:#333333;color:#f0f0f0;}
</style>
Alright,firstthingfirst,let’sseehowcanwerepeatthesamestuffoverandoveragain…
Andtomakethathappen,wewilluseourbrother-from-another-mother,the“forloop”.
Theforloopisatechniquethatletsyouloopthroughanycode,untilyouhitsomesortofacounter…Let’swriteitdownandI’llexplainitfurther:
for(i=0;i<10;i++){
##…CODE…##
}
Alright,sotocreateaforloop,youhavetowritethewordfor,andopenparenthesis…Insideoftheparenthesisyouhave3sectionsdividedbysemicolons,thefirstsectionyousupposetoresetyourcounter.Becausetheforloopisrunninguntilyouhitthatcounter.Sothefirstsectionistoresetyourcounter,andyoucancallyourcounterwhateveryoulike,Inamedit i ,that’sshortenough,andresetittozero.
Rightafter,wehavethesecondsection.Itallabouttellingtheforloop:”ifthat’sconditionistrue…Well…justkeeploopin’willya?!“soIwrote“ i<10 ”,whichisinenglish:“aslongasourcounter‘i’isunder10,don’tmentionit,justkeeplooping…“
Andinthelastsection,isthethecounterincrement.Aftereveryloop,dotheplus-plusthingy,whichifyouareremember,means“incrementyourselfbyone!”,soifourcounteriis0,afteroneloopitwillchangeto1,andthento2,andthento3andsoon…
Andeverytimeourmiddlesectionissatisfied,ourcodeherewillkeeponrunning.
Alright,let’scombinealil’bitofforloopsandfunctions,andcreateourselvesaWritingLineMachine!
?? ♫ …WritingLineMachineee….yeahh…eaa…ea…a… ♫ ??
Yeah,sofirstofall,wewillwriteafunctioncalled WriteLineMachine witha forloop insideofit,andthatfunctionwilltakeaparametercalled lineText .
Andwewillletthe forloop runningfor10timesfornow…
functionWriteLineMachine(lineText){
for(i=0;i<10;i++){
//…Somewritefunction…
}
}
Iwillleaveacommentnowinsideofthe forloop ,andnowwewillwriteafunctionthatwritingourtext,andthenwewillinsertitinsideofourforloop,k?
Solet’swriteitdown!
Iwillcreateanotherfunctioncalled Write ,andthisfunctionwillaskforaparametercalled lineText ,anditwillsimplywillwriteonourdocument,thesamevaluetheparameterhas.
functionWrite(lineText){
document.write(lineText);
}
Andwewillinsertournewfunctioninsideofour WriteLineMachine …Andlinktheparameterofthe WriteLineMachine
functionWriteLineMachine(lineText){
for(i=0;i<10;i++){
Write(lineText);
}
}
Alright,andnowwewillhaveanotherfunctionthatstartsourmachine,called StartMachine ,andwewilljustinsertour WriteLineMachine insideofit.Withaparameterof lineText.
functionStartMachine(lineText){
WriteLineMachine(lineText);
}
Now,wewillhaveanewvariable,thatholdsatext.let’ssaywewanttorepeat…thistext:
“Iwillneverridemyhamster-mobiletoschooleveragain.”(Ipromise!!!)
vartext=“Iwillneverridemyhamster-mobiletoschooleveragain.”;
Andfinally,welinkalltogetherwitha StartMachine ,andlettingituseourtextvariable…
StartMachine(text);
Soourcodegotoour StartMachine function,withourtext,travelstoour WriteLineMachine functionwithourtext,loop10times,andeachandeveryloophewillvisitour Write function,thatjustprintinginsideofourdocument,ourtextwhichis…Well…myforbiddenridesonthehamster-mobile…
Bytheway,wecaneasilythinkofimprovingourmachine,andgiveitdynamicvariableofthenumberofloops…Likethat:
varloopNum=50;
for(i=0;i<loopNum;i++){
Write(lineText);
}
Andthat’sit.
Nowwecantrickourteachersandletourmachinetowritelinesforus!
Chapter20Array
SonowwewilllearnwhatArraysis.
SometimesyouwillwanttoliststuffonyourJavascript,likealistofyourusernames,ordates,orwhatever.
Inordertodojustthat,youcansurelydeclareavariableforeveryoneofthem,likevaruser1,varuser2,varuser3,andsoon…Butitwillbecompletelyinefficient.(especiallyonbiggerlist…)
Soforthatkindoftask,wehaveArrays.
Arrayswillstorealist,butonjustonevariable.
LetmeshowyouwhatImean,Iwillcreateanarrayofnames.allyouneedtodoistotype“ new ”andthen“ Array ”,andthe Array wordissomethingyouhavetotype,youcannottypewhateveryouwant,that’sreservedname…
Youopenparenthesis,andinsideofthoseparenthesesyouwriteyourvariables,IwilltypeanarrayofstringnamesasIsaidearlier.
BigTony,AmazingBob,CoolJeff,andAwesomeJane.
varnames=newArray(“BigTony”,“AmazingBob”,“CoolJeff”,“AwesomeJane”);
Nowlet’ssayIwanttoprintonthescreenthenameAmazingBob,whatdoIdo?
Iwillwrite document.write ,andtheninsideofourparenthesisIwillwritename,becausethat’sthevariableofourarray,andthenwewanttoaccessBob.
Whatwedon’tknowisthateachandeveryoneofthatarray,hasasecretindexnumber,andinsteadofone,itstartswithzero.
SoBigTonywillbeindexedzero,AmazingBobwillbeindexedone,CoolJeffwillbeindexedastwo,andAwesomeJanewillbethree.
SotoaccessamazingBob,weneedtotypeindexone,right?
Sotomakethathappened,wewillopensquarebrackets,andtype1.
Let’stryit.
document.write(names[1]);
Andherewego,wehaveamazingBobrightthere.
Andifwewantedto…getAwesomeJaneprintedonthescreen…Let’sseewhat'sherindexnumber…0,1,2,3.
ThreeistheindexofJane,let’schangeitto3here:
document.write(names[3]);
Andwe’vegotJane!
Nowlet’sdosomethingfunky!Let’ssayouruserAwesomeJane,decidedtochangehernametoTammy.
Inthatcase,wewouldwritenames[3]toaccesshername,andthensetit,justlikewesetanewvariable,“Tammy”,andlet’saddanotherdocument.write,toseethatindeeditchangedovertime.
varnames=newArray(“BigTony”,“AmazingBob”,“CoolJeff”,“AwesomeJane”);
document.write(names[3]+“<br/>”);
Names[3]=“Tammy”;
document.write(names[3]+“<br/>”);
Andyup.We’vegotit!
Chapter21ArrayTricks
Alright!WehaveafewmoretricksforArrays!
Wecanaddanewitemwithapushmethod
Solet’ssaywewanttoadd2morenamesforexample…Martha,andGeorge.
names.push(“Martha”,“George”);
document.write(names+“<br/>”);
Let’sseeifwe’vegotit…
yup!
Wecanalsosortitalphabetically…Withasortmethod…
names.sort();
document.write(names+“<br/>”);
Let'ssee…Yup!Sorteditout!!!
Andwecanalso…reverseeverything!
names.reverse();
document.write(names+“<br/>”);
Let’srefreshitandseewhatwegot….Yup!
Stillgotit!
Chapter22JavascriptonSteroids
Alright,sofar,wehavelearnedlotsofcoolstuff,butrightnow,it’stimetotakeitupanotch.
I’llwritesomeadvancedstuff,sobearwithme,k?
Alright…
Doyouknowallofthosemoviesthatyouhavethevillain,andhetakestheherostarringasTomCruz,andhehaslike…Abomb…Andeveryonewilldieifheisnotgoingtoplacetherightcombinationofpassword…?
Well,todaywewillbethevillainthatgoingtobuildthismachinethatpromptthepassword,andwewillknowifthepasswordisvalidornot!
SoLet’sbuildstuffonHTML…
<divid=”sendItem”>
<form>
Password:<br/>
<br/>
<inputtype=”password”id=”password”
placeholder=”password”/>
<br/>
<inputtype=”button”id=”submit”value=”send!”/>
</form>
</div>
Andlet’sstyleitabit,afterall,it’saspecialoccasion!
<style>
#sendItem{
background-color:red;
width:200px;
margin:30px;
padding:30px;
}
</style>
Nowwewillhaveafunction,andwewillcallit CheckValidation ,itwill…checkvalidationofthepasswordcombination…Ofcourse…
Insideofourfunction,wewillhaveavariablenamedpassword,anditwilleventuallygetthevalue,oftheinputtypeelementwhohastheidofpassword,let’stypedocument,getElementById,value.
Soinsideofpasswordwestorethevalueoftheinputtag.
Thenwewillhaveanifstatement,checkingratherourcombinationisok,sowewillwritepassword,isnotequalto….Let’ssee…whatcombinationeventhePentagoncan’tcrack???…
Oh!1234.Thatwilldo.
Andwewillhavean alert ,says“Caution!Passwordisincorrect!;
varpassword=document.getElementById(“password”).value;
if(password!=“1234”){
alert(“Caution!PasswordisIncorrect!”);
}else{
//success!
}
Alright,let’splaceourfunctiononthebutton,onclick…
<inputtype=”button”id=”submit”value=”send!”onclick=”CheckValidation()”/>
Andlet’scheckifwetypesomething,it’ssayserror…
Yup!!!
Itdoes!
Cool!
Now…notethatwehavea“send”button…So…wehavetosendourformsomewhere,right?
Letmeaddafewshticksintoourstyletag…
<style>
#sendItem{
background-color:red;
width:200px;
margin:30px;
padding:30px;
transition:3sall;
left:0;
}
.leftTrans{left:3000px!important;}
</style>
Iaddedanotherclasscalled leftTrans ,andaddafewmoremodificationstoour sendItemid…
Now,afterwewillsucceedourpasswordcombination,theformwillbesenttous,thevillains!
Let’saddintheelsestatement,vary,anditwilltaketheidof sendItem ,sowewillaccesstheelementof sendItem …Andnow,wewilltakevariabley,andaddaclasscalled, leftTrans .
else{
vary=document.getElementById(“sendItem”);
y.className+=“leftTrans”;
}
Andlet’strytofailonlyonce…Wegotourmessage…
Let’stryagainwithourstrongpassword1234….
Ooop!Wesentourform!Whoknowswhere?!Maybetomars.
Chapter23Nowwhat?
Congratulations!
Youaccomplishedthiscourse,youheardlotsofreallybadjokesinthisbook,
andI’mveryproudofyou!
Youmightaskyourself:
Now,thatI’veaccomplishedmyfirstJavascriptcourse,whatshouldIdonow?HowcanIimprovemywebdevelopingskills?
Well,myyoungpadawan,nowit’stimetocombineyourJavascriptskillswithsomeServerSide.
IdohaveaC#coursejustforyou,andbecauseyoupurchasedthisbook(orincompensationformybadjokes),Iwillgiveyou50%offallofmycoursesinUdemy.
Youcangrabyourcouponhere:http://basicjavascript.gilad.me/discount50/