0% found this document useful (0 votes)
45 views

CH-4 JavaScript

Uploaded by

Legesse Samuel
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views

CH-4 JavaScript

Uploaded by

Legesse Samuel
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

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
document.write("<p>My Name isAde MusaOkeke </p>");
document.write("<p>I amintheSchoolofScienceand Technology.</p>");
document.write("<p>MyJavaScript Language.</p>");
</script>

Tousemultilinecommentsstartwith/* andendwith*/. Example4is usedto illustratetheuseof


multilinecomments(/**/).

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.

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 onload="message ()">
</body>
</html>

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.

Example4: External Java Script


<html>
<head>
<script type="text/javascript"src="extfile.js"></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">
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:

 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
holdsthevalueWelcome.Notetheuseofquotesinthe
assignmentofatextvaluetovariablesmynameandgreetingsandthe
useofsemicolonaftereachvariabledeclaration. Semicolonisusedin JavaScripttomarktheendof
astatement

5|P a g e Internet and WebDevelopment


JavaScriptalsomakesitpossibletoassignavaluetovariablethathas
notbeendeclared.Seetheexamplebelow:
amt=10;
Thisis thesameas varAmt=10;

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

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
asitsresult.Inaddition,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 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

JavaScriptisthemostpopularscripting languageoftheInternet.Itis majorlyusedasa client-


sidescriptinglanguagetoaddinteractive
functionality,validateforms,detectbrowsers,etc.inWebdesign.Some ofitsconstructs
havebeencoveredinthisunit.Itissupportedbymajor 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 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

Whenwritingaprogram,itmaybecomenecessary thatsomesetsof statements


tobeexecutedarebasedontheoutcomeofalogical
expressioin.Comparsionandlogicaloperatorswouldberequired. Asthe namesconnote,
theyallowforcomparison ofvalues.Theyareusedwith if,while,switch,andforstatementstoaccomplish
decisionoriterative constructsin programming.One may be interestedin testingif one operandis
greaterthan, less than,equalto, or notequalto another
operand.Themajorityoftheseoperatorswillprobablylookfamiliaras in
otherprogramminglanguages.Theresultobtainedis
usuallyatrueorfalsewhichfurtherdetermineswhichstatementthecomputershould execute.

ComparisonOperators
Comparison operators are used in logical statements to determine equalityor differencebetweenvariablesor
values.GiventhatY=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
values.GiventhatX=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
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

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”;
document.write("<b>Congratulation, YouPassed</b>");
}else
{
result=“Fail”;
document.write("<b>YouFailed,Tryagain</b>");
}
</script>

Thiswilldisplaytheinformation“Congratulation,Youpassed.”

Practice1
Ifthevalueofexamscoreis35,whatmessagewillbedisplayedonthe webbrowser?

SwitchStatement

Thisisusedtoselectoneofmanyblocksofcodetobeexecuted.The syntaxof theswitchstatementis:

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>

11 | P a g e Internet and WebDevelopment


3.3 IterationonJavaScript

SomestatementsinJavaScriptareknownasiterativestatements.Instead ofadding
severalalmostequallinesinascriptwecanuseloopsto
performthetasks.Loopstatementshavecontrolstructures 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 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>

12 | P a g e Internet and WebDevelopment


Example 4definesaloopthatstartswithi=0.Theloopwillcontinueto
runaslongasiislessthan,orequalto100.iwillincreaseby1each
timetheloopruns.Theloopwillgenerateintegernumbersfrom0to100numbers.

The“whilestatement”

The“whilestatement”testacondition,andwhentrue, repeatedlyrunsa blockof


codeuntiltheconditionisnolongertrue.

Thesyntaxis givenas follows:

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.

13 | P a g e Internet and WebDevelopment


Thesyntaxis asfollow:
do{
statements;
}
While(expression);

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

Inthisunit,wehavecoveredthebasicstatements requiredtoimplement ControlConstructs


inJavaScript.Inthenextunit, weshallcoverevents andeventshandlers.

6.0 TUTOR-MARKEDASSIGNMENT

i. Identifyandcorrectthe errorsinfollowingsegmentsof code:


if(age>=30);document.write(“Agegreaterthanorequalto
30);elsedocument.write(“Ageis lessthan30);

ii. WriteascriptthatoutputsHTMLtextthatkeepsdisplayingin the


browserwindowthemultiplesoftheinteger2,namely2,4,8,16,
32,64,128,etc.Ensurethatyourloopterminateswhenthevalue
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
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

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


throughtotheuser.Whenanalertboxpopsup,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"onclick="show_confirm()"value="Showconfirm box"/>
</body>
</html>

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.

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

18 | P a g e Internet and WebDevelopment


TheReturnStatement

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

JavaScript programsdonothavetobeexecutedinsequence. Wecan


makewebpagesmoreinteractive byusingevents.Theseactionscanbe
detectedbyJavaScript.Awidevarietyofeventsenables scriptsto
respondtothemouse,thekeyboard,andothercircumstances.Examples 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


HTMLelements.Eventhandlersallowawebpagetodetectwhena
given“event”hasoccurred,sothatitcanrunsomeJavaScript code.In
one’scode,aneventhandlerissimplyaspecialattributethatoneaddsto
anHTMLelement.Forexample,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,andpromptbox.Eventsallowscriptstorespond toauserwhois movingthe
mouse,enteringformdataor pressingkeys.Eventsand
eventhandlershelptomakewebapplicationmoreresponsive, dynamic andinteractive.

20 | P a g e Internet and WebDevelopment


5.0 SUMMARY

Eventsuchastheonclickandonsubmit eventscanbeusedtotrigger scripts.JavaScript


events,whichallowscriptstorespondtousers’
interactionandmodifythepages,accordinglyhavebeendiscussedin thisunit.

6.0 TUTOR-MARKEDASSIGNMENT

i. NamethreeJavaScripteventhandlersanddescribehowtheyare
used.CreateaWebpagethatincorporatesthem.
ii. Whataresomepracticalusesof alertboxes?

21 | P a g e Internet and WebDevelopment

You might also like