CH-4 JavaScript
CH-4 JavaScript
FUNDAMENTALS OF JAVASCRIPT
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 Main Content
3.1 Inserting a JavaScript into HTML page
3.2 JavaScript Comments
3.3 Where to Locate JavaScript in a Program
3.4 JavaScript Statements
3.5 JavaScript Variables
3.6 Arithmetic Operators and Expressions
4.0 Conclusion
5.0 Summary
6.0 Tutor-MarkedAssignment
7.0 Reference/FurtherReading
1.0 INTRODUCTION
Java Scripts a scripting language that was developed by Netscape Communicator to provide interactivity to
static Web pages. The language was originally developed by Netscape under the name Live Script. Netscape
and Sunin December1995 later released Live Script under the name Java Script .Many people seem to be
confused about the relationship of JavaScript and Java, which is a separate programming language .Java
Scripts a simple ,interpreted language while Java is a compiled object-oriented programming
language .In this unit, we shall describe basic facts about JavaScript and how to incorporate the most
commonly used Java Script elements in to pages.
2.0 MAINCONTENT
What is JavaScript?
It is a programming language.
It is an interpreted language.
It is object-based programming. It is widely used and supported
It is accessible to the beginner.
Writing JavaScript
To insert a Java Script in to an HTML page, we use the<script>tag. Inside the<script>tag, we use
the type attribute to define the scripting language.
1|P a g e Internet and WebDevelopment
So we have<script type="text/JavaScript">and </script>to connote where the JavaScript starts and
ends. Example 1isa simple Java Script code that displays on a browser “Welcome to Dire Dawa
University of Ethiopia”–without the quotes.
The <SCRIPT> tag alerts a browser that JavaScript code follows. It is
typically embedded in the HTML.
Comments are added to JavaScript codes to make them more readable. JavaScript allows the use
of single line or multiple lines comments. To put a comment on a single line use//. Example2
illustrates the use of a comment in Java Script codes.
<script type="text/JavaScript">
//My details areas displayed in thefollowing three paragraphs
document.write("<p>My Name isAde MusaOkeke </p>");
document.write("<p>I amintheSchoolofScienceand Technology.</p>");
document.write("<p>MyJavaScript Language.</p>");
</script>
Example3: Multilinecomments
<script type="text/javascript">
/*
Mydetailsas astudentof theNationalOpenUniversityof Nigeria
aredisplayedin thenextthreeparagraphs
*/
document.write("<p>My NameisAbebe Tolosa</p>"); document.write("<p>I amintheSchoolofScienceand
Technology.</p>");
document.write("<p>MyMatriculationNumberisNOU031111.</p>");
</script>
2|P a g e Internet and WebDevelopment
3.3 WheretoLocateJavaScriptinaProgram
JavaScriptcodecanbelocatedinternallywithintheprogram or externally.
Ifitistobewithintheprogram,thenithastobelocatedin thebodyorheadsectionofanHTMLpage.Sinceprogram
instructions areexecutedsequentially,scriptsthataretobeexecutedlatterorwhena
userclicksabuttonarebetterplacedinasafunction. Foreasy maintenance
ofprograms,itisbettertoseparatefunctionfromthemain pagecontentbylocatingthemin theheadsection.
Ifonedoesnotwantascripttobeplacedinsideafunction,orifone’s scriptshouldwritepagecontent,itshouldbe
placedin thebodysection.
Example5: JavaScriptCodeslocatedinthebodysection
<html>
<head></head>
<body>
<scripttype="text/javascript">
document.write("This message is written by JavaScript");
</script>
</body></html>
3.3.1 UsinganExternalJavaScript
TouseJavaScriptasexternalfile,firstithastobewrittenandsaved witha.js
fileextension.Thenpointtothe.jsfileinthe“src”attributeof the<script>tag.
Example4illustratestheuseofJavaScriptasan externalfile.
JavaScriptisasequence ofstatementstobeexecutedbythebrowser.
Eachstatementmustbeseparatedbyasemicolon.Example5isusedto illustratehowJavaScriptprogram
canbeusedtodisplaythedetailsof studentto theWebpage
Example5: Studentdetails
<scripttype="text/javascript">
document.write("<p>My NameisAdeMusaOkeke</p>");
document.write("<p>I amintheSchoolofScienceand Technology.</p>");
document.write("<p>MyMatriculationNumberisNOU031111.</p>");
</script>
2.4.1 JavaScriptBlocks
JavaScriptstatementscanbegroupedtogetherinblocks.Blocksstart
withaleftcurlybracket{,andendswitharightcurlybracket}. The purpose of a block is to make the sequence of
statements execute together.InExample6,thethreelinesofthestudent’sdetailsaretreated as ablock.
Example6: BlockStatements
<scripttype="text/JavaScript">
{
document.write("<p>My NameisAdeMusaOkeke</p>");
document.write("<p>I amintheSchoolofScienceand Technology.</p>");
document.write("<p>MyMatriculationNumberisNOU031111.</p>");
}
</script>
Programmers use variables to store values. A variable can hold several typesof data. In JavaScript you don't
have to declare a variable's data type before using it. Any variable can hold any JavaScript data type,
including:
String data
Numbers
Boolean values (True/False)
JavaScriptVariables
Variablesare“containers”forstoringinformation. Aswithalgebra,
JavaScriptvariablesareusedtoholdvaluesorexpressions.Avariable can have a shortname,like amt,or a
moredescriptivename, like amount
To declare variables, use the keyword var and the variable name:
var userName
• To assign values to variables, add an equal sign and the value:
var userName = "Smith"
4|P a g e Internet and WebDevelopment
var price = 100
RulesforJavaScriptvariablenames
There are rules and conventions in naming variables in any programming language. It is good practice to use
descriptive names for variables. The following are the JavaScript rules:
Declaring(Creating)JavaScriptVariables
Example7: DeclarationStatements
var x;
var myname;
var examscore var radius
var greetings;
AssignmentStatement
Example8: AssignmentanddeclarationStatement
Var x=5;
Var myname=”Adebola”;
Var examscore=89;
Var radius=1.0;
Var greetings=”Welcome”;
3.6 ArithmeticOperatorsandExpressions
Anarithmeticexpression isone,whichisevaluatedbyperforminga
sequenceofarithmeticoperationstoobtainanumericvaluetoreplace
theexpression.Arithmeticoperatorsareusedtoperform arithmetic between variablesand/or
values.Table 1 shows a list of arithmetic operatorandexpressions.
GiventhatY=10,thetablebelowexplainsthearithmeticoperators:
Table2.1:ArithmeticOperatorsandExpressions
Thelistaboveissimilartothatofbasicmathematics. Theonlysymbol
thatmightlooknewisthemodulus(“%”),whichdividesoneoperand byanotherandreturnstheremainder
asitsresult.Inaddition,the+ operatorcanbe usedtoaddstringvariablesor textvaluestogether.
txt1="National Open";
txt2="University of Ethiopia";
txt3=txt1+txt2;
After the executionof the statementsabove, the variable txt3 will contain“NationalOpenUniversityof
Ethiopia.”
Practice1
Theprogrambelowcomputesthe areaofacircle.Typethecodesisingatexteditorpreferablynotepad.exe.Save
anHTMLfileandopenitwithabrowser.Whatistheresult?
<html>
<body>
<script type="text/javascript">
varradius=5;
var area=radius*radius*3.14159
document. Write("The Area of the Circle with radius=5”+area);
document.write("<br/>");
}
</script>
</body>
6|P a g e Internet and WebDevelopment
</html>
4.0 CONCLUSION
JavaScriptstatementsaretypicallyembeddeddirectlywithHTML. A singleHTML
documentcaninclude anynumberofembeddedscripts.
Whenusedproperly,JavaScripthasthecapacitytoimprovethelook
andenhanceuser’sinteractivitywithWebpages.Somestatements that
willenableonetowritesimpleJavaScriptcodeshavebeencoveredin thisunit.
5.0 SUMMARY
6.0 TUTOR-MARKEDASSIGNMENT
I. WhodevelopedJavaScriptandwhen?WhichbrowsersupportJavaScript?
II. LocateaJavaScriptcalculatorandexplainhowitworks.
III. UsingJavaScript,designaWebpagethatconvertstemperature readingin Celsiusto
Fahrenheitscale.
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 MainContent
3.1 LogicalStatement
3.2 DecisionMaking
3.3 IterationonJavaScript
4.0 Conclusion
5.0 Summary
6.0 Tutor-MarkedAssignment
7.0 References/FurtherReading
1.0 INTRODUCTION
JavaScriptprogramswillbeexecutedintheorderinwhichstatements arewrittenexcept
fortheuseofcontrolstatements withthescripts.The useofcontrolstatements
canleadtotheconditional,repeatedand alterationofthenormal
sequentialflowofcontrol.Controlstatementsin JavaScriptaresimilartotheircounterpartsinC/C+
+andJava. Theyare thuseasytolearn.
2.0 OBJECTIVES
Attheendof thisunit, youshouldbe ableto:
7|P a g e Internet and WebDevelopment
• implementlogicalconstructwithJavaScript
• applydecisionstatementswithJavaScript
• useloopswithJavaScript.
3.0 MAINCONTENT
3.1 LogicalStatement
ComparisonOperators
Comparison operators are used in logical statements to determine equalityor differencebetweenvariablesor
values.GiventhatY=10.
Table3.1:explainsthecomparisonoperators:
LogicalOperators
Logicaloperatorsareusedtodetermine thelogicbetweenvariablesor
values.GiventhatX=5andY=10,theTable3explainstheresultsofthe useof logicaloperatorin theexpressions.
Table3.2:LogicalOperators
Onemaywishtotestthevalueofavariable,andperformdifferenttasks basedontheoutcomeofthetest.
Forinstance,onemayneedtocheck theexamination scoreofastudenttoknowwhetherhepassedorfailed
andwhatgradehemade.Onecanuseconditionalstatementsinone’s code to achieve this. Conditional statements
are used to perform different actionsbasedon differentconditions.The “if and switch”
commandsarecommonlyusedtoimplementtheconditionalstatement.
Weshallbrieflyexaminethedifferentconstructofthe“ifandswitch”statements.
IfStatement:Thisisusedtoexecutesomecodeonlyifaspecified conditionistrue.
Syntax
If(condition)
{
code to be executed if condition is true
}
Example1
<scripttype="text/javascript">
varexamscore=80;
varresult;
if (examscore>=70)
{
result=“Pass”;
document.write("<b>Congratulation,YouPassed</b>");
}
</script>
If...elseStatement
Syntax
if(condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}
Example2
<scripttype="text/javascript">
varexamscore=80;
9|P a g e Internet and WebDevelopment
varresult;
if (examscore>=45)
{
result=“Pass”;
document.write("<b>Congratulation, YouPassed</b>");
}else
{
result=“Fail”;
document.write("<b>YouFailed,Tryagain</b>");
}
</script>
Thiswilldisplaytheinformation“Congratulation,Youpassed.”
Practice1
Ifthevalueofexamscoreis35,whatmessagewillbedisplayedonthe webbrowser?
SwitchStatement
Syntax
switch(m)
{case1:
executecodeblock1 break;
case2:
executecodeblock2 break;
..casem: executecodeblockm break;
default:
codetobeexecutedifmisdifferentfromcase1,Case2,...Casem
}
Itworksbyevaluatingasingleexpressionm(mostoftenavariable). Thevalueoftheexpression
isthencomparedwiththevaluesforeach
caseinthestructure.Ifthereisamatch,theblockofcodeassociatedwiththatcaseisexecuted.
Thebreakcommandisusedtopreventthe codefromrunningintothenextcaseautomatically.Weexaminethisby
lookingataprogram thatdisplaysthedayoftheweekbasedonauser selection.
Example3
<scripttype="text/javascript">
vardayoftheWeek;
switch(dayoftheWeek)
{
Case1:document.write("<b>TodayisSunday</b>");
break;
}
10 | P a g e Internet and WebDevelopment
Case2:document.write("<b>Todayis Monday</b>");
break;
{
Case3:document.write("<b>Todayis Tuesday</b>");
break;
}
{
Case4:document.write("<b>Todayis Wednesday</b>");
break;
}{
Case5:document.write("<b>Todayis Thursday</b>");
break;
}{
Case6:document.write("<b>Todayis Friday</b>");
break;
}
{
Case7:document.write("<b>TodayisSaturday</b>");
break;
}{
Default:document.write("<b>Thereare7Daysin aweek</b>");
break;
}</script>
SomestatementsinJavaScriptareknownasiterativestatements.Instead ofadding
severalalmostequallinesinascriptwecanuseloopsto
performthetasks.Loopstatementshavecontrolstructures thatdelimit
themandwhichdeterminehowmanytimes(zeroormore)thedelimited codeis
executed,basedonsomeconditions.
Wewilllookattwostructureshere:
• the“forstatement”
• the“whilestatement”andits variants
TheforLoop
for(startvalue;condition;increment){
statements;
}
Noticethattherearethreevariablesinsidethe forstatementconditional expression.Theyare
Startvalue:Thisholdsthevalueoftheinitialstateofthevariabletobe tested.It is
usuallydoneasanassignment.
Condition: The condition to be tested for. The statement keeps processingas longas
itremainstrue.
Increment:Theincrementbywhichthevariablebeingtestedchanges.
Example4
<html>
<body>
<scripttype="text/javascript">
varnum=0;
for(i=0;num<=100;num+)
{
document.write("TheNextNois "+num);
document.write("<br/>");
}
</script>
</body>
</html>
The“whilestatement”
While(expression){ Statements;
}
Anotherwaytoaccomplishthetaskinexample4isbyusingawhile
loopstatementasshowninExample5. Theloopstartswithi=0.The loopwillcontinue
torunaslongasiislessthan,orequalto100.iwill increaseby1eachtimetheloopruns:
Example5
<html>
<body>
<scripttype="text/javascript">
varnum=0;
while(num<=100)
{
document.write("The Next Number is " +num);
document.write("<br/>");;
}
</script>
</body>
</html>
Example6
The“do…whilestatement”
Thisisrequiredwhenablock ofcodeistoberunatleastonce. After running
ablockofcodeonce,“do…whilestatement”evaluatesthe
conditionalexpression.Iftheconditionalexpressionis true,thenitloops backto thebeginningof
thestatementandstartsagain.
Example7
<html>
<body>
<scripttype="text/javascript">
varnum=0;
do{
document.write("Thenextnumberis "+num);
document.write("<br/>");
}
while(num<=10);
</script></
body></html>
4.0 CONCLUSION
Thenormal executionofstatementsinaprogramisoneaftertheotherin
theorderinwhichtheyarewritten. Thisprocess iscalledsequential execution.Programmer
canhowever,specifytheorderinwhich statementsshouldbe executedby
usingcontrolconstructs/statement. Someof theseconstructshavebeencoveredin thisunits.
5.0 SUMMARY
6.0 TUTOR-MARKEDASSIGNMENT
CONTENTS
1.0 Introduction
2.0 Objectives
3.0 MainContent
3.1 JavaScriptPopupBoxes
3.2 JavaScriptFunctions
3.3 JavaScriptEvents
3.4 EventsHandlers
4.0 Conclusion
5.0 Summary
6.0 Tutor-MarkedAssignment
7.0 Reference/FurtherReading
1.0 INTRODUCTION
Theword“event”asusedinrelationtocomputerprogramming usually
signifiessomesortofactionoroccurrence.Aswillbefurtherdiscussed
inthisunit,aneventreferstoarepositioningofthemousecursor,a
mouseclick,thefillingofaform,orthepressing oftheenterkey. JavaScriptlets one reactsto
theseeventsby specifyingthe relevant attributeintheobject’sHTML tagcalledaneventhandler.
Tousean eventhandler,ithastobeincludedintheHTML tag.Mosttimes,a function
iscreatedtohandleanevent.Afunction islinesofJavaScript codethatperformsomeactionor
action(s).
2.0 OBJECTIVES
• implementJavaScriptPopupBoxes
• explainthemeaningof eventandeventhandlers
• applyJavaScriptFunctions
• useJavaScriptto implementeventsandeventhandlers.
3.0 MAINCONTENT
3.1 JavaScriptPopupBoxes
a.) AlertBox
Fig.4.1:Alert
b.) ConfirmBox
Aconfirm box is often used if one wants the user to verify or accept
something.Whenaconfirmboxpopsup,theuserwillhavetoclick either“OK”or“Cancel”
toproceed.Iftheuserclicks“OK”,thebox returns true. If the userclicks“Cancel”,theboxreturns
false.
Syntax confirm("sometext");
Example2
<html>
<head>
<scripttype="text/javascript">
functionshow_confirm()
{
Var r=confirm("Pressabutton");
if(r==true)
{
alert("YoupressedOK!");
}
else{
16 | P a g e Internet and WebDevelopment
alert("YoupressedCancel!");
}}
</script></head>
<body>
<inputtype="button"onclick="show_confirm()"value="Showconfirm box"/>
</body>
</html>
c.) PromptBox
Apromptboxisoftenusediftheuserisrequiredtoinputavaluebefore
enteringapage.Whenapromptboxpopsup,theuserwillhavetoclick
either“OK”or“Cancel”toproceedafterentering aninputvalue.Ifthe
userclicks“OK”,theboxreturns theinputvalue.Iftheuserclicks “Cancel,”theboxreturnsnull.
Syntax prompt("sometext","defaultvalue");
Example3
<html>
<head>
<scripttype="text/javascript">
functionshow_prompt()
{
varname=prompt("Pleaseenteryourname","Myname");
if (name!=null&&name!="")
{
document.write("Hello"+name+"!YouareWelcome!");
}}
</script>
</head>
<body>
<inputtype="button"onclick="show_prompt()"value="Showprompt box"/>
</body>
</html>
Fig.4.2:Prompt
3.2 JavaScriptFunctions
Afunctioncontainscodesthatwillbeexecutedbyaneventorbyacall
tothefunction.Afunctionmaybecalledfromanywherewithinapage
(orevenfromotherpagesifthefunction isembeddedinanexternal.js file).Functions
canbedefinedbothinthe<head>andinthe<body> sectionofadocument.
Syntax
functionfunctionname(var1,var2,...,varX)
{
somecode
}
Theparametersvar1,var2,andsoonarevariablesorvaluespassed into
thefunction.The{andthe}definesthestartandendof thefunction.
Note:Afunctionwithnoparametersmustincludetheparentheses()
afterthefunctionname.
Notethewordfunctionisinlowercaseandwhenacallismade,ithas to bespeltcorrectly.
Example4
<html>
<head>
<scripttype="text/javascript">
functionnounmessage()
{
alert("Welcome to National Open University of Nigeria!");
}
</script></head>
<body>
<form>
<inputtype="button"value="Clickme!"onclick="nounmessage()"/>
</form>
</body>
</html>
Fig.4.3:Welcome
Iftheline:alert("WelcometoNationalOpenUniversityofNigeria!!")in
theexampleabovehadnotbeenputwithinafunction,itwouldhave beenexecuted
assoonasthepagewasloaded.Now,thescriptisnot
executedbeforeauserhitstheinputbutton.Thefunctionnounmessage () willbeexecutedif
theinputbuttonis clicked.
Thereturnstatementisusedtospecifythevaluethatisreturnedfrom
thefunction.Therefore,functionsthataregoingtoreturnavaluemust
usethereturnstatement.
Theexamplebelowreturnstheareaofarectanglethatis,length*
breadth
Example5
<html>
<head>
<scripttype="text/javascript">
functionarea(length,breadth)
{
returnlength*breadth;
}
</script>
</head>
<body>
<scripttype="text/javascript">
document.write(area(10,15));
</script>
</body>
</html>
3.3 JavaScriptEvents
• Awebpageor an imageloading
• Mouseclick
• Mouseoverahotspotonthewebpage
• Selectingan inputfieldin anHTMLform
• Submittingan HTMLform
• A keystroke
Table4.1:MoreExamplesof EventHandlers
Event Description
Use this to invoke JavaScript up onclicking(a
onclick:
link, or form boxes)
Usethistoinvoke JavaScriptafterthepageoran
onload:
imagehasfinishedloading.
UsethistoinvokeJavaScriptifthemousepasses
onmouseover: bysomelink
UsethistoinvokeJavaScriptifthemousegoes
onmouseout: passsomelink
UsethistoinvokeJavaScriptrightaftersomeone
onunload: leavesthispage.
TheonSubmiteventisusedtovalidateALLform
fieldsbeforesubmittingit.
onSubmit
4.0 CONCLUSION
6.0 TUTOR-MARKEDASSIGNMENT
i. NamethreeJavaScripteventhandlersanddescribehowtheyare
used.CreateaWebpagethatincorporatesthem.
ii. Whataresomepracticalusesof alertboxes?