Chapter Four
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
JavaScript code is typically embedded in the HTML, to be interpreted and
run by the client's browser. Here are some tips to remember when writing
JavaScript commands.
JavaScript code is case sensitive
White space between words and tabs are ignored
Line breaks are ignored except within a statement
JavaScript statements end with a semi- colon ;
2.1 Inserting a JavaScript in to an HTML page
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.
<SCRIPT language = "JavaScript">
statements
</SCRIPT>
Example1: Simple Java Script Code
<html>
<body>
<script type=”text/JavaScript”>
Document. Write(“Welcome to Dire Dawa University of Ethiopia”);
</script>
</body>
</html>
In this example, the “document. Write”command is a standard JavaScript
Command for writing output to a page. By entering the document. write command between the
<script>and </script>tags, the browser will recognize it as a JavaScript command and execute the
codeine.
3.2 JavaScript Comments
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.
Example2: Comments in JavaScript
<script type="text/JavaScript">
//My details areas displayed in thefollowing three paragraphs
[Link]("<p>My Name isAde MusaOkeke </p>");
[Link]("<p>I amintheSchoolofScienceand Technology.</p>");
[Link]("<p>MyJavaScript Language.</p>");
</script>
Tousemultilinecommentsstartwith/* andendwith*/. Example4is usedto illustratetheuseof
multilinecomments(/**/).
Example3: Multilinecomments
<script type="text/javascript">
/*
Mydetailsas astudentof theNationalOpenUniversityof Nigeria
aredisplayedin thenextthreeparagraphs
*/
[Link]("<p>My NameisAbebe Tolosa</p>"); [Link]("<p>I amintheSchoolofScienceand
Technology.</p>");
[Link]("<p>MyMatriculationNumberisNOU031111.</p>");
</script>
2|P a g e Internet and WebDevelopment
3.3 WheretoLocateJavaScriptinaProgram
JavaScriptcodecanbelocatedinternallywithintheprogram or externally.
Ifitistobewithintheprogram,thenithastobelocatedin [Link]
instructions areexecutedsequentially,scriptsthataretobeexecutedlatterorwhena
userclicksabuttonarebetterplacedinasafunction. Foreasy maintenance
ofprograms,itisbettertoseparatefunctionfromthemain pagecontentbylocatingthemin theheadsection.
Example4: JavaScript Codes located in the head section
<html>
<head>
<script type="text/javascript">
Function message ()
{alert("This alert Box was called With the onload event");
}
</script>
</head>
<body ()">
</body>
</html>
Ifonedoesnotwantascripttobeplacedinsideafunction,orifone’s scriptshouldwritepagecontent,itshouldbe
placedin thebodysection.
Example5: JavaScriptCodeslocatedinthebodysection
<html>
<head></head>
<body>
<scripttype="text/javascript">
[Link]("This message is written by JavaScript");
</script>
</body></html>
3.3.1 UsinganExternalJavaScript
TouseJavaScriptasexternalfile,firstithastobewrittenandsaved [Link]
[Link]“src”attributeof the<script>tag.
Example4illustratestheuseofJavaScriptasan externalfile.
Example4: External Java Script
<html>
<head>
<script type="text/javascript"src="[Link]"></script>
</head>
3|P a g e Internet and WebDevelopment
<body>
</body>
</html>
3.4 Java Script Statements
JavaScriptisasequence ofstatementstobeexecutedbythebrowser.
Eachstatementmustbeseparatedbyasemicolon.Example5isusedto illustratehowJavaScriptprogram
canbeusedtodisplaythedetailsof studentto theWebpage
Example5: Studentdetails
<scripttype="text/javascript">
[Link]("<p>My NameisAdeMusaOkeke</p>");
[Link]("<p>I amintheSchoolofScienceand Technology.</p>");
[Link]("<p>MyMatriculationNumberisNOU031111.</p>");
</script>
2.4.1 JavaScriptBlocks
[Link]
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">
{
[Link]("<p>My NameisAdeMusaOkeke</p>");
[Link]("<p>I amintheSchoolofScienceand Technology.</p>");
[Link]("<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,
[Link] 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:
The variable name must start with a letter or an underscore.
firstName or _myName
The variable name must start with a letter or an underscore.
firstName or _myName
You can use numbers in a variable name, but not as the first character.
name01 or tuition$
You can't use space to separate characters.
userName not user Name
Capitalize the first letter of every word except the first
salesTax or userFirstName
Variablenamesarecasesensitive(thevariableamtandAMTaretwo
differentvariables)
Declaring(Creating)JavaScriptVariables
Avariable isdeclaredbyprecedingitwiththekeywordvar.Example7 showsvaliddeclarationof variablesin
JavaScript.
Example7: DeclarationStatements
var x;
var myname;
var examscore var radius
var greetings;
AssignmentStatement
As long as no values are assigned to variable, they will remain empty.
Toassignvaluestothevariablesusetheassignmentoperator(=). We willlearnaboutotheroperators
laterinthismodule. InExample8,we combineboththedeclarationandassignmentstatements.
Example8: AssignmentanddeclarationStatement
Var x=5;
Var myname=”Adebola”;
Var examscore=89;
Var radius=1.0;
Var greetings=”Welcome”;
InExample 8,variablexholdsthevalue5,mynameholdsthevalue Adebola,examscore
holdsthevalue89,radiusholdsthevalue1.0while greetings
[Link]
assignmentofatextvaluetovariablesmynameandgreetingsandthe
useofsemicolonaftereachvariabledeclaration. Semicolonisusedin JavaScripttomarktheendof
astatement
5|P a g e Internet and WebDevelopment
JavaScriptalsomakesitpossibletoassignavaluetovariablethathas
[Link]:
amt=10;
Thisis thesameas varAmt=10;
3.6 ArithmeticOperatorsandExpressions
Anarithmeticexpression isone,whichisevaluatedbyperforminga
sequenceofarithmeticoperationstoobtainanumericvaluetoreplace
[Link] arithmetic between variablesand/or
[Link] 1 shows a list of arithmetic operatorandexpressions.
GiventhatY=10,thetablebelowexplainsthearithmeticoperators:
Table2.1:ArithmeticOperatorsandExpressions
Operators Meaning Example Result
+ Addition X=Y+2 X=12
- Subtraction X=Y-2 X=8
* Multiplication X=Y*2 X=20
/ Division X=Y/2 X=5
% Modulus X=Y%2 X=0
++ Increment X++ X=11
-- Decrement X-- X=9
Thelistaboveissimilartothatofbasicmathematics. Theonlysymbol
thatmightlooknewisthemodulus(“%”),whichdividesoneoperand byanotherandreturnstheremainder
[Link],the+ operatorcanbe usedtoaddstringvariablesor textvaluestogether.
To add two or more string variable stogether,usethe+operator.
txt1="National Open";
txt2="University of Ethiopia";
txt3=txt1+txt2;
After the executionof the statementsabove, the variable txt3 will contain“NationalOpenUniversityof
Ethiopia.”
Practice1
Theprogrambelowcomputesthe [Link]
[Link]?
<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);
[Link]("<br/>");
}
</script>
</body>
6|P a g e Internet and WebDevelopment
</html>
4.0 CONCLUSION
JavaScriptstatementsaretypicallyembeddeddirectlywithHTML. A singleHTML
documentcaninclude anynumberofembeddedscripts.
Whenusedproperly,JavaScripthasthecapacitytoimprovethelook
andenhanceuser’[Link] that
willenableonetowritesimpleJavaScriptcodeshavebeencoveredin thisunit.
5.0 SUMMARY
JavaScriptisthemostpopularscripting [Link] majorlyusedasa client-
sidescriptinglanguagetoaddinteractive
functionality,validateforms,detectbrowsers,[Link] ofitsconstructs
[Link] browsers,suchas
InternetExplorer,Firefox,Chrome,Opera,andSafari.
6.0 TUTOR-MARKEDASSIGNMENT
I. WhodevelopedJavaScriptandwhen?WhichbrowsersupportJavaScript?
II. LocateaJavaScriptcalculatorandexplainhowitworks.
III. UsingJavaScript,designaWebpagethatconvertstemperature readingin Celsiusto
Fahrenheitscale.
CONTROL STATEMENTS IN JAVASCRIPT
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 [Link] useofcontrolstatements
canleadtotheconditional,repeatedand alterationofthenormal
[Link] 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
Whenwritingaprogram,itmaybecomenecessary thatsomesetsof statements
tobeexecutedarebasedontheoutcomeofalogical
[Link]. Asthe namesconnote,
theyallowforcomparison [Link] if,while,switch,andforstatementstoaccomplish
decisionoriterative constructsin [Link] may be interestedin testingif one operandis
greaterthan, less than,equalto, or notequalto another
[Link] in
[Link]
usuallyatrueorfalsewhichfurtherdetermineswhichstatementthecomputershould execute.
ComparisonOperators
Comparison operators are used in logical statements to determine equalityor differencebetweenvariablesor
[Link]=10.
Table3.1:explainsthecomparisonoperators:
Operators Meaning Example Result
== Equalto Y ==8 False
=== Equivalentto Y===10 True
Y==="10" False
!= NotEqualto Y!=8 True
> Greaterthan Y>8 True
< Lessthan Y<8 False
>= Greater or Equal Y>=8 True
to
<= Lessor Equalto Y<=8 False
LogicalOperators
Logicaloperatorsareusedtodetermine thelogicbetweenvariablesor
[Link]=5andY=10,theTable3explainstheresultsofthe useof logicaloperatorin theexpressions.
Table3.2:LogicalOperators
Operators Meaning Example Result
&& And (x <7&&y>6) False
|| Or (x==5 ||y==6) True
! Not !(x==7) True
8|P a g e Internet and WebDevelopment
3.2 DecisionMaking
Onemaywishtotestthevalueofavariable,andperformdifferenttasks basedontheoutcomeofthetest.
Forinstance,onemayneedtocheck theexamination scoreofastudenttoknowwhetherhepassedorfailed
[Link]’s code to achieve this. Conditional statements
are used to perform different actionsbasedon [Link] “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”;
[Link]("<b>Congratulation,YouPassed</b>");
}
</script>
If...elseStatement
Thisisusedtoexecutesomecodesiftheconditionistrueandanother codeif theconditionis false.
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”;
[Link]("<b>Congratulation, YouPassed</b>");
}else
{
result=“Fail”;
[Link]("<b>YouFailed,Tryagain</b>");
}
</script>
Thiswilldisplaytheinformation“Congratulation,Youpassed.”
Practice1
Ifthevalueofexamscoreis35,whatmessagewillbedisplayedonthe webbrowser?
SwitchStatement
[Link] syntaxof theswitchstatementis:
Syntax
switch(m)
{case1:
executecodeblock1 break;
case2:
executecodeblock2 break;
..casem: executecodeblockm break;
default:
codetobeexecutedifmisdifferentfromcase1,Case2,...Casem
}
Itworksbyevaluatingasingleexpressionm(mostoftenavariable). Thevalueoftheexpression
isthencomparedwiththevaluesforeach
[Link],theblockofcodeassociatedwiththatcaseisexecuted.
Thebreakcommandisusedtopreventthe [Link]
lookingataprogram thatdisplaysthedayoftheweekbasedonauser selection.
Example3
<scripttype="text/javascript">
vardayoftheWeek;
switch(dayoftheWeek)
{
Case1:[Link]("<b>TodayisSunday</b>");
break;
}
10 | P a g e Internet and WebDevelopment
Case2:[Link]("<b>Todayis Monday</b>");
break;
{
Case3:[Link]("<b>Todayis Tuesday</b>");
break;
}
{
Case4:[Link]("<b>Todayis Wednesday</b>");
break;
}{
Case5:[Link]("<b>Todayis Thursday</b>");
break;
}{
Case6:[Link]("<b>Todayis Friday</b>");
break;
}
{
Case7:[Link]("<b>TodayisSaturday</b>");
break;
}{
Default:[Link]("<b>Thereare7Daysin aweek</b>");
break;
}</script>
11 | P a g e Internet and WebDevelopment
3.3 IterationonJavaScript
[Link] ofadding
severalalmostequallinesinascriptwecanuseloopsto
[Link] thatdelimit
themandwhichdeterminehowmanytimes(zeroormore)thedelimited codeis
executed,basedonsomeconditions.
Wewilllookattwostructureshere:
• the“forstatement”
• the“whilestatement”andits variants
TheforLoop
Thesyntaxof the “forstatement”is
for(startvalue;condition;increment){
statements;
}
Noticethattherearethreevariablesinsidethe forstatementconditional [Link]
Startvalue:Thisholdsthevalueoftheinitialstateofthevariabletobe [Link] 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+)
{
[Link]("TheNextNois "+num);
[Link]("<br/>");
}
</script>
</body>
</html>
12 | P a g e Internet and WebDevelopment
Example 4definesaloopthatstartswithi=[Link]
runaslongasiislessthan,orequalto100.iwillincreaseby1each
timetheloopruns.Theloopwillgenerateintegernumbersfrom0to100numbers.
The“whilestatement”
The“whilestatement”testacondition,andwhentrue, repeatedlyrunsa blockof
codeuntiltheconditionisnolongertrue.
Thesyntaxis givenas follows:
While(expression){ Statements;
}
Anotherwaytoaccomplishthetaskinexample4isbyusingawhile
loopstatementasshowninExample5. Theloopstartswithi=[Link] loopwillcontinue
torunaslongasiislessthan,[Link] increaseby1eachtimetheloopruns:
Example5
<html>
<body>
<scripttype="text/javascript">
varnum=0;
while(num<=100)
{
[Link]("The Next Number is " +num);
[Link]("<br/>");;
}
</script>
</body>
</html>
Example6
The“do…whilestatement”
Thisisrequiredwhenablock ofcodeistoberunatleastonce. After running
ablockofcodeonce,“do…whilestatement”evaluatesthe
[Link] true,thenitloops backto thebeginningof
thestatementandstartsagain.
13 | P a g e Internet and WebDevelopment
Thesyntaxis asfollow:
do{
statements;
}
While(expression);
Example7
<html>
<body>
<scripttype="text/javascript">
varnum=0;
do{
[Link]("Thenextnumberis "+num);
[Link]("<br/>");
}
while(num<=10);
</script></
body></html>
4.0 CONCLUSION
Thenormal executionofstatementsinaprogramisoneaftertheotherin
theorderinwhichtheyarewritten. Thisprocess iscalledsequential [Link]
canhowever,specifytheorderinwhich statementsshouldbe executedby
usingcontrolconstructs/statement. Someof theseconstructshavebeencoveredin thisunits.
5.0 SUMMARY
Inthisunit,wehavecoveredthebasicstatements requiredtoimplement ControlConstructs
[Link], weshallcoverevents andeventshandlers.
6.0 TUTOR-MARKEDASSIGNMENT
i. Identifyandcorrectthe errorsinfollowingsegmentsof code:
if(age>=30);[Link](“Agegreaterthanorequalto
30);[Link](“Ageis lessthan30);
ii. WriteascriptthatoutputsHTMLtextthatkeepsdisplayingin the
browserwindowthemultiplesoftheinteger2,namely2,4,8,16,
32,64,128,[Link]
2048576isprinted.
14 | P a g e Internet and WebDevelopment
EVENTSANDEVENTHANDLERSIN JAVASCRIPT
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
[Link]
inthisunit,aneventreferstoarepositioningofthemousecursor,a
mouseclick,thefillingofaform,orthepressing oftheenterkey. JavaScriptlets one reactsto
theseeventsby specifyingthe relevant attributeintheobject’sHTML tagcalledaneventhandler.
Tousean eventhandler,ithastobeincludedintheHTML [Link],a function
[Link] islinesofJavaScript codethatperformsomeactionor
action(s).
2.0 OBJECTIVES
Attheendof thisunit, youshouldbe ableto:
• implementJavaScriptPopupBoxes
• explainthemeaningof eventandeventhandlers
• applyJavaScriptFunctions
• useJavaScriptto implementeventsandeventhandlers.
3.0 MAINCONTENT
3.1 JavaScriptPopupBoxes
Popupboxesareusedtodisplay amessage, alongwithan“OK”button. Depending
onthepopupbox,itmightalsohavea“Cancel”button,and
onemightalsobepromptedtoentersometextJavaScripthasthreedifferenttypesofpopupboxavaila
bleforonetouse. TheyareAlert box,Confirmbox,andPromptbox.
a.) AlertBox
An alert box is often used ifonewantstomakesureinformation comes
[Link],theuserwillhaveto click"OK"to proceed.
15 | P a g e Internet and WebDevelopment
Syntax
alert("sometext");
Example1
<html>
<head>
<script type="text/JavaScript">
Function show_confirm()
{
Var r=confirm("Pressabutton");
if (r==true)
{
alert("YoupressedOK!");
}
else{
alert("YoupressedCancel!");
}}
</script>
</head>
<body>
<input type="button" box"/>
</body>
</html>
Fig.4.1:Alert
b.) ConfirmBox
Aconfirm box is often used if one wants the user to verify or accept
[Link],theuserwillhavetoclick either“OK”or“Cancel”
[Link]“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" box"/>
</body>
</html>
c.) PromptBox
Apromptboxisoftenusediftheuserisrequiredtoinputavaluebefore
[Link],theuserwillhavetoclick
either“OK”or“Cancel”toproceedafterentering [Link]
userclicks“OK”,theboxreturns [Link] “Cancel,”theboxreturnsnull.
Syntax prompt("sometext","defaultvalue");
Example3
<html>
<head>
<scripttype="text/javascript">
functionshow_prompt()
{
varname=prompt("Pleaseenteryourname","Myname");
if (name!=null&&name!="")
{
[Link]("Hello"+name+"!YouareWelcome!");
}}
</script>
</head>
<body>
<inputtype="button" box"/>
</body>
</html>
Fig.4.2:Prompt
3.2 JavaScriptFunctions
Afunctioncontainscodesthatwillbeexecutedbyaneventorbyacall
[Link]
(orevenfromotherpagesifthefunction [Link] file).Functions
canbedefinedbothinthe<head>andinthe<body> sectionofadocument.
17 | P a g e Internet and WebDevelopment
However,toassurethatafunction isread/loaded
bythebrowserbeforeitiscalled,itiswisetoputfunctionsinthe<head>section.
HowtoDefineaFunction
Syntax
functionfunctionname(var1,var2,...,varX)
{
somecode
}
Theparametersvar1,var2,andsoonarevariablesorvaluespassed into
[Link]{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!" ></form>
</body>
</html>
Fig.4.3:Welcome
Iftheline:alert("WelcometoNationalOpenUniversityofNigeria!!")in
theexampleabovehadnotbeenputwithinafunction,itwouldhave beenexecuted
[Link],thescriptisnot
[Link] () willbeexecutedif
theinputbuttonis clicked.
18 | P a g e Internet and WebDevelopment
TheReturnStatement
Thereturnstatementisusedtospecifythevaluethatisreturnedfrom
[Link],functionsthataregoingtoreturnavaluemust
usethereturnstatement.
Theexamplebelowreturnstheareaofarectanglethatis,length*
breadth
Example5
<html>
<head>
<scripttype="text/javascript">
functionarea(length,breadth)
{
returnlength*breadth;
}
</script>
</head>
<body>
<scripttype="text/javascript">
[Link](area(10,15));
</script>
</body>
</html>
3.3 JavaScriptEvents
JavaScript programsdonothavetobeexecutedinsequence. Wecan
makewebpagesmoreinteractive [Link]
[Link] scriptsto
respondtothemouse,thekeyboard,[Link] of eventsare:
• Awebpageor an imageloading
• Mouseclick
• Mouseoverahotspotonthewebpage
• Selectingan inputfieldin anHTMLform
• Submittingan HTMLform
• A keystroke
The scriptthat is usedto detectand respondto an eventis called an event handler
Eventhandlersareamongthemostpowerfulfeatures of JavaScript.
19 | P a g e Internet and WebDevelopment
3.4 EventsHandlers
In JavaScript/HTML, anevent handlerattaches JavaScript to your
[Link]
given“event”hasoccurred,sothatitcanrunsomeJavaScript [Link]
one’scode,aneventhandlerissimplyaspecialattributethatoneaddsto
[Link],torunsomeJavaScript whentheuser
clicksonanelement,addtheonClickattributetotheelement. More examplesof
eventhandlersarepresentedin Table4.1.
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
The onFocus,onBlur and onChangeevents are
m onFocus,onBlurand oftenusedincombinationwithvalidationoffor fields.
onChange
4.0 CONCLUSION
Oneverysimpleresponse toaneventistodisplayadialogbox. JavaScript
providesthreetypesofdialogboxes:alertbox,confirmation
box,[Link] toauserwhois movingthe
mouse,enteringformdataor [Link]
eventhandlershelptomakewebapplicationmoreresponsive, dynamic andinteractive.
20 | P a g e Internet and WebDevelopment
5.0 SUMMARY
Eventsuchastheonclickandonsubmit eventscanbeusedtotrigger [Link]
events,whichallowscriptstorespondtousers’
interactionandmodifythepages,accordinglyhavebeendiscussedin thisunit.
6.0 TUTOR-MARKEDASSIGNMENT
i. NamethreeJavaScripteventhandlersanddescribehowtheyare
[Link].
ii. Whataresomepracticalusesof alertboxes?
21 | P a g e Internet and WebDevelopment