You are on page 1of 39

Page 1

JavaScript Notes
Background and overview
The history of JavaScript and its purpose. The environment in
which JavaScript operates. Standards.
Once upon a time there was the http protocol. Web pages defined with
HTML were a novelty. However after a while people became a little bored
with being able to do no more than clicing a lin and going to a new
page.
!o in "ecember 1##$ %etscape& deeply embroiled in the browser wars
with Microsoft& invented a scripting language which %avigator '.( could
e)ecute and which would enable a great deal more user interactivity. They
planned to call it LiveScript * but +ust before they released it& !un
Microsystems released the first version of ,ava. %etscape-s mareting
people thought ,ava sounded a lot more lively than Live!cript& so they
renamed it JavaScript& thus misleading a very large number of people
into thining that ,ava!cript and ,ava were somehow connected. They are
not. This was .ersion 1.(.
Chapter
1
Page '
Standards
Microsoft-s reply to %etscape-s ,ava!cript was something called JScript&
starting with /nternet 0)plorer 1.(. !ince /0 2more or less3 had to be able
to cope with ,ava!cript& ,!cript was pretty similar. 4s the table shows&
successive versions of %etscape-s %avigator and Microsoft-s /nternet
0)plorer used developing versions of ,ava!cript and ,script& with
Microsoft usually being one version behind. !ome co*ordination started in
1##5& when the standards agency 06M4 developed something called
06M4!cript '7'& and Microsoft and others agreed to comply with this.
However since then actual browser implementatiosn have continued to be
supersets of this standard.
Page 1
1994 %6!4
Mosaic
1995 /01& '
March
1996
%avigator
'.(
,ava!cript
1.(
August
1996
%avigator
1.(
,ava!cript
1.1
/0 1 ,script 1.(
,ava!cript
1.(
Jan
1997
/01 ,script '.(
,ava!cript
1.1
June
1997
%avigator
8.(
,ava!cript
1.'
Oct
1997
/0 8.( ,script 1.(
,ava!cript
1.1
Jun
e1998
06M4!cript*
'7' .ersion 1
Oct
1998
%avigator
8.$
,ava!cript
1.1
Mo9illa open
source starts
Mar
1999
/0 $ ,script $.(
06M4!cript
v.1
Dec
1999
06M4!cript
version 1
Nov
2
%avigator
7.(
,ava!cript
1.$
Ju!"
2
/0 $.$ ,script $.$
,ava!cript
1.$
The initial version of the 06M4!cript standard is on the web at *
http:;;www.ecma*international.org;publications;standards;0cma*'7'.htm
The latest 2,une '((83 change to this is an e)tension to <ML& at
http:;;www.ecma*international.org;publications;standards;0cma*1$=.htm
JavaScript and the host environment
/t is possible to see ,ava!cript as a general purpose language& but it was
designed for& and is used in& the specific environment of a web page inside
a browser. /t is little use without interaction with this environment * which
Page 8
includes buttons and frames and such*lie on the page. Hence it only
becomes useful when treated together with 1 other standards& all defined
by the W16 *
HTML * hyper*te)t marup language
6!! * cascading style sheets
"OM * the document ob+ect model
,ava!cript as a language is >uite straightforward ? it is well*defined 2as
06M4!cript '7' 3 and current browsers 2and many older ones3
implement that standard. However the host environment is a big problem.
There is HTML 8.(1& <HTML& "HTML& 6!!1 and 6!!'& and "OM1
and "OM'. "ifferent versions of particular browsers implement different
bits of different standards. One approach is to use ,ava!cript to wor out
which browser is being used& and then use different code. However there
is not even a standard way of finding which browser you are on ? and
code lie this has to be re*written every time a new version is released.
We will start with standard stuff which wors on all browsers& and then
loo at more fancy bits.
Page $
2 Starting to write
JavaScript
Organising software tools to write and debug web pages with
JavaScript
Open %otePad and type in the following& very carefully 2or if you are using the electronic
version& copy and paste it 3. !ave it with a file e)tension .html& such as @one.html@.
/nclude the @>uotes@ around te filename& or %otepad will stic .t)t on the end and you get
one.html.t)t.
Then in a browser 2/0 or whatever3 go Aile Open Browse to this file& and open it:
<!-- This shows a first piece of JavaScript -->
<!DOCTYPE HTML PUL!C "-##$%C##DTD HTML &'()##E*"
"http+##www'w%'or,#T-#ht./&#strict'0t0">
<ht./>
<hea0>
<MET1 http-e23iv4"Co5te5t-T6pe" co5te5t4"te7t#ht./8
charset4iso-99:;-)">
<tit/e> ----- ) - He//o$or/0 ------- <#tit/e>
<SC-!PT TYPE4"te7t#<avascript" >
<!--
a/ert="He//o wor/0">8
##-->
<#SC-!PT>
<#hea0>
<?o06>
<p> So.e pa,e co5te5t <#p>
<#?o06>
<#ht./>
This is what the browser should do:
Chapter
2
Page 7
We-ll loo at how this wors
soon.
Other Tool Sets
Ceally all you need is a te)t
editor 2since html files are +ust
te)t3 and a browser to chec it
wors. Dou might use a set of
browsers 2 /0& %etscape&
Mo9illa Airefo)& Opera3 to
chec the page wors in all of
them * which it may not.
Dou can use %otepad& WordPad or even Word as the te)t editor& but be
sure the file is saved as simple te)t with no formatting marup.
Better choices than these are te)t editors designed for software
development. 4n e)ample of this is te)tpad& available from
www.te)tpad.com. This has 1 advantages *
/t can synta) colour code the te)t& which maes it easier to
understand code 2see picture3
Dou can preview the page in the browser with one button clic
Dou can use the same editor to write ,ava& Perl or whatever.
4lternatively&
you can use
dedicated
HTML editors
such as
ArontPage or
"reamweaver&
and enter the
code in HTML
view. / would
use Te)tPad to
learn with& and
switch to
ArontPage if
you produce
pages with a significant amount of visual content.
Page =
Analysing the irst script
Here is the first script again:
<!-- This shows a first piece of JavaScript -->
<!DOCTYPE HTML PUL!C "-##$%C##DTD HTML &'()##E*"
"http+##www'w%'or,#T-#ht./&#strict'0t0">
<ht./>
<hea0>
<MET1 http-e23iv4"Co5te5t-T6pe" co5te5t4"te7t#ht./8
charset4iso-99:;-)">
<tit/e> ----- ) - He//o$or/0 ------- <#tit/e>
<SC-!PT TYPE4"te7t#<avascript" >
<!--
a/ert="He//o wor/0">8
##-->
<#SC-!PT>
<#hea0>
<?o06>
<p> So.e pa,e co5te5t <#p>
<#?o06>
<#ht./>
Most of this * all e)cept from the part in white * is HTML. This is valid
HTML 8.(1 !trict. The ,ava!cript part is *
<SC-!PT TYPE4"te7t#<avascript" >
<!--
a/ert="He//o wor/0">8
##-->
<#SC-!PT>
%ote this is placed in the EheadF section. The element
E!6C/PT TDP0G@te)t;+avascript@ F
..
E;!6C/PTF
encloses the script 2do not use the language G @,ava!cript1.'@ attribute * it
is not valid HTML 8.(13.
There is +ust one state#ent in the script& which is
alert2@Hello world@3H
and when this e)ecutes& it displays the small dialog bo) shown above.
%ote the semi*colon at the end of the statement.
Page 5
The only tricy point about this is the way it deals with old browsers
which do not understand ,ava!cript. There is a danger they would display
the ,ava!cript code on the page * and they are stopped from doing this by
the
<!--
-->
These are HTML comments * in other words they tell the browser to
ignore what is between them * and that is the ,ava!cript which it does not
understand.
However modern browsers do understand ,ava!cript. But the
**F
would be seen as ,ava!cript& and it isn-t * this problem is solved by putting
the two slashes ;; before it. This is a ,ava!cript comment * so the browser
which does understand ,ava!cript will ignore them. !o it wors both ways.
/f this seems confusing& donIt worry. ,ust use the script above as a
template for the later scripts you write. Dou-ll get used to it in a while.
Practical Tass
1. /f you haven-t done so already& run the -Hello world- page on your
system.
'. 4lter the alert statement so it says something else.
1. Try putting in two alert statements and find out what happens.
!here to place the script
The script2s3 can be placed in the head& as above. Or they can be placed in
the body element lie this *
<!-- This shows a first piece of JavaScript -->
<!DOCTYPE HTML PUL!C "-##$%C##DTD HTML &'()##E*"
"http+##www'w%'or,#T-#ht./&#strict'0t0">
<ht./>
<hea0>
<MET1 http-e23iv4"Co5te5t-T6pe" co5te5t4"te7t#ht./8
charset4iso-99:;-)">
<tit/e> ----- ) - He//o$or/0 ------- <#tit/e>
<#hea0>
<?o06>
<p> So.e pa,e co5te5t <#p>
<SC-!PT TYPE4"te7t#<avascript" >
<!--
a/ert="He//o wor/0">8
##-->
<#SC-!PT><#?o06>
Page #
<#ht./>
The difference is pretty subtle. /n the first version the browser displays
-Hello world-& then -!ome page content- * because Hello world came first.
/n this second version -!ome page content- appears first& then -Hello world-.
Or the script can be ept in a separate file * so you have two files& one
HTML and the other ,ava!cript& and the HTML file uses the !C6 attribute
in the !6C/PT element to specify the name of the ,ava!cript file * lie
this:
<!-- This shows a first piece of JavaScript -->
<!DOCTYPE HTML PUL!C "-##$%C##DTD HTML &'()##E*"
"http+##www'w%'or,#T-#ht./&#strict'0t0">
<ht./>
<hea0>
<MET1 http-e23iv4"Co5te5t-T6pe" co5te5t4"te7t#ht./8
charset4iso-99:;-)">
<tit/e> ----- ) - He//o$or/0 ------- <#tit/e>
<SC-!PT SRC="hithere.js" TYPE4"te7t#<avascript">
<#hea0>
<?o06>
<p> So.e pa,e co5te5t <#p>
<#?o06>
<#ht./>
where the file -hithere.+s- +ust contains:
a/ert="He//o wor/0">8
The first approach is used for page*specific code& while the second can be
used for pieces of code which are needed on many pages in one site& and
where you don-t want to modify all those pages separately when the
common code changes.
Practical Tas
1. Try the separate file approach to display the message -Welcome to the
marvellous world of ,ava!cript-
Page 1(
" # $anguage undamentals
The core of the JavaScript language
%aria&les
%early all scripts need to handle data in some way. 4s the script runs& the
data values must be held in memory& as variables. Before you use a
variable& you must declare it& using the reserved word var 2reserved
means the word has special significance in ,ava!cript& so that you can-t
name a variable var3. Aor e)ample if you want to use a variable called
price& you would include
var price8
in your script. 4fter that you could give a value to that variable by saying
price4@':(8
4lternatively you can declare and initialise a variable in one statement:
var price 4 @':(8
Dou can declare a variable once only& but you can give it different values
many times.
Bear in mind that
Dou should choose variable names that make sense to you& the
programmer. 6hoose names lie incomeTa) or rateOfPay or
priceOfAish& not ) or i
Those variable names do not make sense to the computer. The
system -understands- reserved words lie var& but has no sense of
what price actually means.
Chapter
"
Page 11
'nput and output
.ariables can be given values in the script& as above. However we often
want to get data values from the user& off the screen * in other words we
want to input data. There are several ways to do this * to start with we will
use prompt23. Aor e)ample& you could get the user to input the price by
saying *
price 4 pro.pt="E5ter the price"A ")('((">8
which produces *
Aor output& we can use alert23& lie this
a/ert="The price is "Bprice>8
which produces:
Simple arithmetic
We can get the computer to do arithmetic with variable values lie this *
tota/ 4 price C 23a5tit68
Here we are telling it to calculate a total on the basis of multiplying 2 J
means multiply 3 the price and the >uantity. This involves three variables&
which would all have had to be declared with var. 4s well as J& use K for
add& * for subtract& and ; for divide. Dou can use constants as well as
variables * such as
res3/t 4 @B%8
!ometimes you need to use bracets to control the order in which things
are wored out * for e)ample
Page 1'
res3/t 4 )B%C&8
gives 11& since the multiplication is done before addition. But
res3/t 4 =)B%>C&8
gives 17& since the bracets are wored out first.
(esigning a script
!uppose we need a script which will calculate a total on the basis of a
price and a >uantity. We can put together these ideas to do this.
The script must handle 1 variables * the unit price& the >uantity& and the
total. !o these 1 variables must first be declared.
Then the user must be ased to input values for the price and the >uantity.
The computer must calculate the total.
Ainally the total must be displayed. Here is the script:
var price8
var 23a5tit68
var tota/8
price 4 pro.pt="E5ter the price+"A")('((">8
23a5tit6 4 pro.pt="How .a56+ "A")">8
tota/ 4 price C 23a5tit68
a/ert="The tota/ is "Btota/>8
This can be embedded in HTML as we have seen before& so the complete
page would be :
<!DOCTYPE HTML PUL!C "-##$%C##DTD HTML &'()##E*"
"http+##www'w%'or,#T-#ht./&#strict'0t0">
<ht./>
<hea0>
<MET1 http-e23iv4"Co5te5t-T6pe" co5te5t4"te7t#ht./8
charset4iso-99:;-)">
<tit/e> ----- ) - He//o$or/0 ------- <#tit/e>
<SC-!PT TYPE4"te7t#<avascript" >
<!--
var price8
var 23a5tit68
var tota/8
price 4 pro.pt="E5ter the price+"A")('((">8
23a5tit6 4 pro.pt="How .a56+ "A")">8
tota/ 4 price C 23a5tit68
a/ert="The tota/ is "Btota/>8
##-->
<#SC-!PT>
<#hea0>
<?o06>
<p> So.e pa,e co5te5t <#p>
<#?o06>
<#ht./>
Practical Tas
Page 11
The user should be ased for the prices of 1 different items& and then the
total should be calculated and displayed. Modify the above to achieve this.
(ata types
4ll the variables so far have been number data type. Dou can also have
strings& which are strings of characters * for e)ample
var .6*a.e8
.6*a.e 4 "$a/ter Mi/5er"8
%ote that string constants must be enclosed in @double >uotes@. 6apital
letters and lower case are distinct& and a !P460 is +ust another character.
Dou can have a space in a string& but not in a variable name * for e)ample&
you could not call a variable .6 5a.e. To avoid this problem& whilst still
maing the script meaningful& is to mae variable names out of words&
with no spaces& but with capital letters to mar word starts. Aor e)ample
his%ame
basic/ncomeTa)
priceOfAish
and so on. Dou must be consistent in the capitalisation * hisname and
his%ame are different variables.
Dou can +oin strings together with a K. Aor e)ample
.6*a.e 4 "$a/ter Mi/5er"
a/ert="M6 5a.e is "B.6*a.e>8
!omething lie @1'1.8@ is a string& even though it loos lie a number.
!ometimes you have to tell ,ava!cript to change a string into a number.
!omething called parseAloat does this *
result G parseAloat2@1'1.8@3H
4fter this& result is a number type with value 1'1.8.
The other data type you can have is boolean& which is +ust true or false.
We-ll use this later.
)aking decisions
Page 18
/n many situations we need the computer to mae a decision on the basis
of some data. Aor e)ample& a customer may get a cheaper price if they
purchase a larger >uantity of items. /n this case we need the computer to
mae a decision on the basis of the >uantity. /n this situation you must use
the reserved word if. Aor e)ample
35itPrice 4 )'%(8
if =23a5tit6 > )((>
35itPrice 4 )'@(8
Here we start by giving the variable unitPrice the initial value of 1.1(. We
then chec whether the >uantity is over 1(( 2 F means greater than3 and if
so& change the unitPrice to 1.'(.
Dou #ust put 2round bracets3 around the condition.
There are 7 -comparison operators- *
!ymbol Meaning
F greater than
E less than
FG greater than or e>ual to
EG less than or e>ual to
GG e>ual
LG not e>ual
Practical Tas
Write a script which inputs the user-s age and displays the message -Too
young- if they are under 15.
*epeating actions
/n many situations we need a script to repeat something many times * in
other words& a loop. One way to do this is using the reserved word for&
lie this *
var co35ter8
for =co35ter4(8 co35ter<&8 co35terBB>
a/ert=co35ter>8
There are 1 parts to a for loop *
Page 1$
initia!isation * in this case counter G (
ho$ !ong to continue * in this case& while counter is less than 8
$hat to change each ti#e * here counterKK means add 1 to the
counter
These loops use an -inde)- variable& which in this case is called counter& but
it does not have to be * it can be called anything. This particular loop goes
around 8 times * first counter is (& then 1& then '& then 1& then it stops.
Practical Tas
Put this in a script to chec it wors.
6hange it so it counts down from 1( to $ 2use counter** 3.
Page 17
+ # Code structure
Using functions to structure scripts
4 function is a small section of program code. Cather than having all code
in one large bloc& there are several advantages in splitting code into
smaller units * and we will see later that a very significant aspect of
,ava!cript called event handling maes functions essential.
An e,ample unction
!uppose we want to have the user input 1 numbers& and display their
average. 4 neat way of doing this would be to have a main piece of code
which inputted the numbers and displayed the average& and a separate
function which calculated the average. The main bloc could be lie this:
var 53.)A 53.@A 53.%A res3/t8
53.)4parseD/oat=pro.pt="E5ter a 53.?er"A"">>8
53.@4parseD/oat=pro.pt="E5ter a seco50 53.?er"A"">>8
53.%4parseD/oat=pro.pt="E5ter a thir0 53.?er"A"">>8
res3/t 4 avera,e=53.)A 53.@A 53.%>8
a/ert="The avera,e is "Bres3/t>8
We have to use parseAloat& because prompt returns a string and we want
numbers. We-ve condensed two actions * inputting the value and turning it
into a number * into one statement. /n
parseD/oat=pro.pt="E5ter a 53.?er"A"">>8
the prompt happens first * maybe we type in @'=@. Then the parseAloat
wors on this& as if we-d had
parseD/oat="@E">8
Chapter
+
Page 1=
Then we are handing over the values of the 1 numbers to the avera,e
function. /t should wor out the answer and -return- it. The value it returns
is assigned to the variable called res3/t.
How do we define the functionM Lie this *
f35ctio5 avera,e=aA?Ac>
F
var tota/8
tota/ 4 aB?Bc8
ret3r5 tota/#%8
G
%ote the following *
Aunctions start with the reserved word f35ctio5& followed by the name
2chosen by the programmer3 of the function
!tatements in the function and enclosed by curly bracets N and O
/t is useful to thin of a function as a machine& into which material is fed
2data in3& the machine does something& then produces a fnished article
2returned value3. /n this e)ample& 1 numbers are sent in& and one value *
their average * is returned.
The values passed in are called parameters. /n this case there are 1
parameters& and they are given the names a b and c in the line
f35ctio5 avera,e=aA?Ac>
The function was @called@ in the main code by *
res3/t 4 avera,e=53.)A 53.@A 53.%>8
Here the names are different. The values are passed over in order * in other
words& the value of num1 is passed in as a& num' is passed in as b& and
num1 as c. The names donIt matter& but the order does.
The reserved word return is used to send the finished product bac. !o
ret3r5 tota/#%8
sends bac the value which has been wored out& and
res3/t 4 avera,e=53.)A 53.@A 53.%>8
means the value is given to res3/t.
Practical Tas
Page 15
1. We want a script which gets the user to input ' numbers& then displays
what they add up to.
Psing the above as a model& write this using a function to do the adding
up.
'. 6hange this so that the larger of the two numbers is displayed. "o this
by using an if in the function.
1. 6hange the last one so it inputs 1 numbers& and displays the largest one.
-vent#handling unctions
Most of what a ,ava!cript page does is in response to user actions& such as
using the mouse or eyboard. The way this wors is that many elements of
an HTML page can have associated with it an event& and it is possible to
say which ,ava!cript function is called when that event occurs. "ifferent
elements can generate different events * for e)ample a body has an onload
event& which we can do lie this *
<!DOCTYPE HTML PUL!C "-##$%C##DTD HTML &'()##E*"
"http+##www'w%'or,#T-#ht./&#strict'0t0">

<ht./>
<hea0>
<tit/e> ----- @ - f35ctio5s ------- <#tit/e>
<SC-!PT TYPE4"te7t#<avascript" >
<!--
function greet()
F
a/ert="Loa0e0">8
G
##-->
<#SC-!PT>
<#hea0>
<?o06 onload="greet()">
<#?o06>
<#ht./>
Here the body tag *
<?o06 o5/oa04",reet=>">
is specifying the function -greet- as the one to e)ecute when the body is
loaded.
Practical Tas
The paragraph tag EpF has an o5Mo3seOver event& which triggers when
the user moves the mouse over the paragraph te)t. Psing the above as a
Page 1#
model& write a page containing a paragraph& so that a message is displayed
when the user moves the mouse over it.
Page '(
The (ocument O&.ect )odel
How JavaScript refers to items on the screen
The last two sections have shown how ,ava!cript can use data values
through variables. However the main things the script needs to process are
the items in the browser $in%o$& and so some way of taling about them
is needed. This is provided by the "ocument Ob+ect Model. This is a set of
ob+ects about windows and related things on the screen. This use of the
word o&'ect comes from ob+ect*oriented programming. These ob+ects have
properties
methods and
events
(roperties are pieces of data about the ob+ect. Aor e)ample& a window
ob+ect has a status property * this is the te)t which is displayed in the status
area at the bottom of the browser window.
4 #etho% is something you can tell an ob+ect to do. Aor e)ample& a
window has a resi9eTo23 method& which you use to tell the window to
change its si9e.
4n event is something that can happen to an ob+ect. Dou can set this to
some ,ava!cript function * when the event occurs& that function e)ecutes.
Aor e)ample..
/irst (O) e,ample
Chapter
0
Page '1
The browser already shows a window& but it is possible to use its open23
#etho% to create another window& by *
var 5ew$i50ow 4wi50ow'ope5=""A"5w"A ".e53?arA stat3sA
resiHa?/e">8
The open method taes 1 parameters. The first is the PCL to open the
window on * here that is @@ or nothing. The second @nw@ is the name of the
new window. 4nd the third sets some attributes of the new window * here
that it will have a menubar& a status bar and be resi9eable.

We can set one of the properties of the new window by *
5ew$i50ow'stat3s 4"He//o fo/Is"8
which writes -Hello fols- in the status bar. This changes the value of the
status propert".
4nd we can call its resi9eTo23 #etho% to change its width and height *
5ew$i50ow'resiHeTo=&((A@((>8
Putting this together we get *
<!DOCTYPE HTML PUL!C "-##$%C##DTD HTML &'()##E*"
"http+##www'w%'or,#T-#ht./&#strict'0t0">
<ht./>
<hea0>
<MET1 http-e23iv4"Co5te5t-T6pe" co5te5t4"te7t#ht./8
charset4iso-99:;-)">
<tit/e> ----- ) - He//o$or/0 ------- <#tit/e>
<SC-!PT TYPE4"te7t#<avascript" >
<!--
var 5ew$i50ow 4wi50ow'ope5=""A"5w"A ".e53?arA stat3sA
resiHa?/e">8
5ew$i50ow'stat3s 4"He//o fo/Is"8
5ew$i50ow'resiHeTo=&((A@((>8
##-->
<#SC-!PT>
<#hea0>
<?o06>
<p> So.e pa,e co5te5t <#p>
<#?o06>
<#ht./>
Page ''
and the result loos lie *
Practical Tas
1. Try the last e)ample out.
'. 4 window ob+ect also has a moveTo2)&y 3 method& so that for e)ample
newWindow.moveTo21((&'((3H
moves the window called newWindow so that its top left corner is 1((
pi)els across& and '(( down from& the top corner of the screen. Try adding
this to the e)ample above.
6an you move the window off screen so the user cannot see itM
)he DOM *ierarch"
These ob+ects come in a hierarchy which is lie this :
The idea of this is that each window ob+ect contains other ob+ects * a navigator ob+ect& a
screen ob+ect and so on. !ome of these contain other ob+ects in turn * for e)ample the
document ob+ect might contain several form ob+ects. We-ll loo at some of these in
outline * for full details of all properties& events and methods you need to consult the
reference sources.
The navigator object
Ceally the navigator ob+ect means the browser being used. This has a few properties& such
as user4gent which gives information about which browser is in use * for e)ample
<SC-!PT TYPE4"te7t#<avascript" >
<!--
a/ert=wi50ow'5avi,ator'3ser1,e5t>8
##-->
<#SC-!PT>
which
produces
something
lie:
window
navigator screen history
location document
Page '1
%ote the synta) of
window.navigator.user4gent
This is picing out of the "OM hierarchy the thing we want * we are
taling about the window ob+ect& then the navigator ob+ect in that window&
then the user4gent property of the navigator object.
)he screen o&'ect
This means the whole screen of the monitor on which the browser is
displayed. The properties of this are rea%+on!" * you cant change them.
This maes sense * you can-t get a bigger monitor with a bit of program
code. But you can find out information about the users- screen and then use
that. Aor e)ample the screen ob+ect has an availWidth property which tells
you the width in pi)els of the usable part of the screen. 2 The Width
property tells you the whole width& but some is not usable * eg they might
have the tasbar at the side.3
!uppose you want to ma)imise the browser window. We can first move
the top corner of the browser to the top corner of the screen *
wi50ow'.oveTo=(A(>8
then find out the screen width and height *
7 4 scree5'avai/$i0th8
6 4 scree5'avai/Hei,ht8
then resi9e the browser window to fit *
wi50ow'resiHeTo=7A6 >8
However this is &a% eti,uette. The user may have other windows open *
they might be doing some wordprocessing or spreadsheet wor. /f they
visit your website and it splats itself all over their screen hiding what they
were doing& they will not be pleased and they wont coem bac. !o donIt do
itL
)he !ocation o&'ect
The location ob+ect holds information about the PCL of the server that
sent the web page. The most direct part of the this is the href property&
which is simply the PCL of the server. Dou can change this * in which
case the browser surfs to that new location. Aor e)ample
/ocatio5'href4"http+##www'6ahoo'co.#"8
Page '8
/mmediately switches to Dahoo. Dou can script buttons 2or other ob+ects3
to offer a menu of new page sto switch to. Or you can use it to re*direct
from one PCL to another& newer site.
)he %ocu#ent o&'ect
This represents the actual content displayed in the browser window. Aor
e)ample *
0oc3.e5t'?,Co/or4"6e//ow"8
0oc3.e5t'write="This is so.e <?>?o/0 te7t<#?>">8
This sets the bg6olor property 2bacground colour3 to yellow& then writes
the string out. The EbF E;bF are interpreted as HTML tags
Practical Tas
1. Try the last e)ample out.
'. The document ob+ect also has a fg6olor property which is the default
te)t colour. Try this out.

Page '$
/orms
How JavaScript can use forms
/orms 1T)$ and the (O)
Cemember that the form element in HTML is coded lie this
<for. 5a.e4".6for." .etho04"post" actio54"" >
S3r5a.e + <i5p3t t6pe4"te7t" 5a.e4"s5a.e">
<?r>
Dore5a.e + <i5p3t t6pe4"te7t" 5a.e4"f5a.e">
<?r>
<i5p3t t6pe4"?3tto5" 5a.e4"3tto5" va/3e4"S3?.it" >
<#for.>
which loos lie as on
the right. /n other
words there is the
EformF element& and
that contains various
items lie te)t fields
and buttons. The most
common use of a form
is to pic up some
data from the user&
then send that off to
the server as input to a script which runs on the server. The script name is
specified in the action attribute of the form. The data is sent in 1 of ' ways
* Q0T and PO!T * which is specified in the method attribute.
The script on the server is a program written in a language such as Perl. /t
will often >uery a database stored on the server 2 often data on customers&
products and such*lie3& and the output from the program is sent bac to
the user as an HTML page.
Chapter
2
Page '7
,ava!cript can also deal with forms. This is different in that this is c!ient+
si%e processing * in other words this happens inside the browser on the
user-s computer& not sent across the web and done on a server. 4 typical
use of this is to validate data entry& and in particular to chec the user has
filled in all the fields& before sending off the data. /n other situations the
,ava!cript code can do all the processing re>uired locally.
/n terms of the "OM& a form is an ob+ect which is in the document. There
might be several forms in the same document. 0ach form contains several
elements 2te)t fields buttons and so on3. Psually we are interested in the
value property of the ob+ect. Aor e)ample if we want ,ava!cript to put the
string @,ohn@ in the forename field in the above form& we can +ust say
0oc3.e5t'.6for.'f5a.e'va/3e 4 "Joh5"8
This pics out from the "OM hierarchy the %ocu#ent& then the form by
name 2#"-or#3 then which element 2-na#e3 and assigns to its va!ue.
Simple Calculator -,ample

!uppose we want a web page we can use as a simple calculator * +ust doing
addition. We would need ' te)t fields to enter the numbers to add& and a
third one to display the result. We also need a button to signal when to do
the addition. /n other words we are trying to get:
The HTML fragment which produced this is:
<for. 5a.e4".6for." .etho04"post" actio54"" >
<i5p3t t6pe4"te7t" 5a.e4"53.)">
<i5p3t t6pe4"te7t" 5a.e4"53.@">
<?r>
<i5p3t t6pe4"?3tto5" 5a.e4"3tto5" va/3e4" B " >
<?r>
-es3/t+<i5p3t t6pe4"te7t" 5a.e4"res3/t">
<#for.>
Page '=
The calculation will be done by a ,ava!cript function& which needs to be
called when the user clics the button. We could name the function
@do4dd@& in which case we need to set this as the event handler for when
they clic the button *
<i5p3t t6pe4"?3tto5" 5a.e4"3tto5" va/3e4"B"
o5C/icI4"0o100=>">
/n the ,ava!cript function we need to *
get the two numbers from the form
add them
put the result bac into the form
Here-s the code that will do it:
f35ctio5 0o100=>
F
var 53.?er)A 53.?er@A res3/t8
53.?er)4parseD/oat=.6for.'53.)'va/3e>8
53.?er@4parseD/oat=.6for.'53.@'va/3e>8
res3/t 4 53.?er)B53.?er@8
.6for.'res3/t'va/3e4res3/t8
G
Here-s the complete thing with HTML and ,ava!cript together:
<ht./>
<hea0>
<tit/e> ----- : ca/c)------- <#tit/e>
<SC-!PT TYPE4"te7t#<avascript">
<!--
f35ctio5 0o100=>
F
var 53.?er)A 53.?er@A res3/t8
53.?er)4parseD/oat=.6for.'53.)'va/3e>8
53.?er@4parseD/oat=.6for.'53.@'va/3e>8
res3/t 4 53.?er)B53.?er@8
.6for.'res3/t'va/3e4res3/t8
G
## -->
<#SC-!PT>
<#hea0>
<?o06>
<for. 5a.e4".6for." .etho04"post" actio54"" >
<i5p3t t6pe4"te7t" 5a.e4"53.)">
<i5p3t t6pe4"te7t" 5a.e4"53.@">
<?r>
<i5p3t t6pe4"?3tto5" 5a.e4"3tto5" va/3e4" B "
o5C/icI4"0o100=>">
<?r>
-es3/t+<i5p3t t6pe4"te7t" 5a.e4"res3/t">
<#for.>
<#?o06>
<#ht./>
Page '5
Practical Tass
1. Try the last e)ample out.
'. 4dd another button for subtraction& together with another ,ava!cript
function 2 @do!ubtract23@ 3& and chec it wors. 6hec the add button still
wors as well.
1. 4dd multiply and divide buttons and test them.
8. /t will probably loo pretty untidy by this point. 6lear up the layout by
placing a table inside the form& and putting the form elements into the
table cells neatly. 2tae care to put a table inside the form& not the form
inside a table3.
%alidating data rom a orm
One of the commonest
uses of ,ava!cript is to
chec the data on a form
before submitting it. Aor
e)ample& we might have
the form shown& and we
want to chec the user has
entered something in both
the forename and surname
fields:
The HTML code for the table is:
<for. 5a.e4"for.)" .etho04"post" actio54"">
<ta?/e wi0th4"@J)" >
<tr>
<td id="fNameprompt" width="1!""
<0iv a/i,54"ri,ht"><fo5t face4"ooI.a5 O/0
St6/e">Dore5a.e+ <#fo5t><#0iv>
<#t0>
<t0 wi0th4"9;">
<i5p3t t6pe4"te7t" 5a.e4"fore5a.e">
<#t0>
<#tr>
<tr>
<td id="sName#rompt" width="1!""
<0iv a/i,54"ri,ht"><fo5t face4"ooI.a5 O/0 St6/e">S3r5a.e+
<#fo5t><#0iv>
Page '#
<#t0>
<t0 wi0th4"9;">
<i5p3t t6pe4"te7t" 5a.e4"s3r5a.e">
<#t0>
<#tr>
<tr>
<t0 wi0th4")(@">
<0iv a/i,54"ri,ht"><fo5t face4"ooI.a5 O/0
St6/e"><#fo5t><#0iv>
<#t0>
<t0 wi0th4"9;">
<i5p3t t6pe4"?3tto5" va/3e4"OK" onClic$="chec$%orm()"
5a.e4"?3tto5">
<#t0>
<#tr>
<#ta?/e>
<#for.>
There are two important things to note about this. The first is that we have
set the on6lic method to be the function -checAorm23-. The second is that
the two prompts have been given /"s. This is so that the ,ava!cript can
access them and change them * in fact it will mae them red if the user has
left the field blan.
The function is :
f35ctio5 checIDor.=>
F
var OK4tr3e8
if =0oc3.e5t'for.)'fore5a.e'va/3e44"">
F
a/ert="P/ease t6pe i5 6o3r fore5a.e">8
0oc3.e5t',etE/e.e5t6!0="f*a.ePro.pt">'st6/e'co/or4"re0"8
OK4fa/se8
G
if =0oc3.e5t'for.)'s3r5a.e'va/3e44"">
F
a/ert="P/ease t6pe i5 6o3r s3r5a.e">8
0oc3.e5t',etE/e.e5t6!0="s*a.ePro.pt">'st6/e'co/or4"re0"8
OK4fa/se8
G
if =OK>
F
## s3?.it for. here
G
G
This uses the variable called OR as a -flag- to remember whether the form
is OR& and we start assuming it is. /t then checs whether the forename
field is empty. /f it is& it alerts the user& then
0oc3.e5t',etE/e.e5t6!0="f*a.ePro.pt">'st6/e'co/or4"re0"8
gets the prompt& and changes the color property of its style. This use of
get.!e#ent/"0% is very common. /t then sets the OR flag to be false.
Page 1(
/t does the similar thing for the other field * then if the form is OR it would
submit it.

Practical Tass
This is not >uite right. /f they missed out two fields and submitted& then
filled in 1 and submitted again& it would still show the first field in red&
even though they-d filled it in. Try to fi) this 2in the script reset all to
blac& then change it to red if its blan3.
)ath (ate and timing
How JavaScript can use forms
The )ath o&.ect and random num&ers
The Math ob+ect has a collection of things relating to maths. One of these
is a random number generator * it is often useful to have the computer
-thin up- random number in a program. Math.random23 gives a random
number between ( and (.####& but often you need to alter this to get what
you want. Aor e)ample suppose you want a number between 1 and 7 for a
dice game. /f you use
) G 7 J Math.random23
you get a number between ( and $.#####. The function Math.floor23 gives
you the whole number part only& so if you said
Chapter
3
Page 11
) G Math.floor2)3H
) would be ( to $& whole numbers only. We can add 1 to this:
)G)K1H
and ) would range from 1 to 7 inclusive. Here-s the complete function :
f35ctio5 ro//Dice=>
F
var 7 4 Math'ra50o.=>8
7 4 JC78
7 4 Math'f/oor=7>8
747B)8
a/ert=7>8
G
This outputs the result& but we could have said
ret3r5 78
at the end of the function. Then we could have used this elsewhere in the
program& lie
6 4 ro//Dice=>8
and y would have been a random integer 1 to 7.
Practical Tass
Write a page with a button& so that when you clic the button it rolls ' dice
and tells you the total.
(ate and Time
The "ate ob+ect nows about dates and the current time. /f you say
var 5ow 4 5ew Date=>8
Then -now- is an ob+ect which includes the day& date and current time. Aor
e)ample this page :
<ht./>
<hea0>
<tit/e>U5tit/e0 Doc3.e5t<#tit/e>
<.eta http-e23iv4"Co5te5t-T6pe" co5te5t4"te7t#ht./8 charset4iso-
99:;-)">
<SC-!PT TYPE4"te7t#<avascript">
<!--
f35ctio5 showTi.e=>
F
var 5ow 4 5ew Date=>8
var res3/t 4 "!t is 5ow "B5ow8
0oc3.e5t',etE/e.e5t6!0="ti.eDie/0">'i55erTe7t4res3/t8
G
## -->
<#SC-!PT>
Page 1'
<#hea0>
<?o06 o5Loa04"showTi.e=>">
<p i04"ti.eDie/0"> <#p>
<#?o06>
<#ht./>
displays this:
PT6 is Pniversal
6o*ordinated Time.
/n the code we-ve
used the
get0lementBy/d to
pic out the
paragraph& and the -innerTe)t- property is the te)t in the element.
Once you-ve got a date there are methods to pic out the day& the hour and
so on. Dou can use this& together with ifs& to mae your page do different
things at different times of the day. 4nd this is on the browser& so the fact
that it is usually a different time on the server from that on the browser
2due to time 9ones3 does not matter.
Practical Tass
Write a page which displays -Qood morning- or -Qood afternoon-
depending on the time of day 2getHours23 e)tracts the hour from the date3.
Timing
!ometimes a page needs to trac time somehow. Aor e)ample an on*line
baning system might want to disconnect if the user does not hit a ey for
say $ minutes * in case they-ve wandered off and someone else will start to
access their account.
There are ' approaches. One is to set up something that will happen once
after a fi)ed delay. This is lie a firecracer * you light the fuse& and after
an interval it goes bang.
This method use a function called setTimeOut. Dou have to supply '
things& how long the delay is 2in milliseconds3 and which function to call
after that time. Aor e)ample when the following runs *
i5terva/4setTi.eo3t=L?a5,=>LA:(((>8
Page 11
then the function bang23 will be called $ seconds later. The function
returns a reference to the timer 2called interval in the above e)ample3. This
is so that you can cancel it * if this was e)ecuted
c/earTi.eO3t=i5terva/>8
less than $ seconds after the first& it cancels it. /ts lie putting the pin bac
in.
Aor e)ample this page:
<ht./>
<hea0>
<tit/e> ----- Ti.er i5 JavaScript ------- <#tit/e>
<SC-!PT TYPE4"te7t#<avascript" L1*MU1ME 4 "JavaScript">
<!--
f35ctio5 ?a5,=>
F
a/ert="a5,">8
G
f35ctio5 start=>
F
i5terva/4setTi.eo3t=L?a5,=>LA:(((>8
G
##-->
<#SC-!PT>
<#hea0>
<?o06 o5Loa04"start=>">
<p>N5?sp8<#p>
<#?o06>
<#ht./>
displays -bang- $ seconds after the page loads.
The first approach is a one*off. The second is to set up something to
happen repeatedly& again and again on set intervals. This is done using
set/nterval. Aor e)ample& when the following e)ecutes *
i5terva/4set!5terva/=LticITocI=>LA)(((>

then the function called ticToc23 will e)ecute every second. Only
clear/nterval23 stops it.
We can use this to display the time& refreshing every second :
<ht./>
<hea0>
<tit/e> ----- Show the ti.e ------- <#tit/e>
<SC-!PT TYPE4"te7t#<avascript" >
<!--
f35ctio5 ticITocI=>
F
var 5ow 4 5ew Date=>8
var res3/t 4 "!t is 5ow " B5ow8
0oc3.e5t',etE/e.e5t6!0="ti.eDie/0">'i55erTe7t 4 res3/t8
Page 18
G
f35ctio5 i5it=>
F
## 5ow set 3p a ti.er o?<ect - it wi// ca// ticITocI ever6 )(((
.i//iseco50s
i5terva/4set!5terva/=LticITocI=>LA)(((>
G
##-->
<#SC-!PT>
<#hea0>
<?o06 o5Loa04"i5it=>">
<p i0 4 "ti.eDie/0"> <#p>
<#?o06>
<#ht./>
Practical Tas
Airstly write a page that waits 1( seconds after a button clic& then says
-Times up- 2this uses setTimeOut23 3.
When that wors& change it so that it counts down as well& so that after the
button is cliced& it displays Time left G #& 5 =& and so on. This will use
both setTimeOut and set/nterval
Page 1$
Standard tricks
How a set of tricks are done with JavaScript
*ollovers
One tric is to change images when the user moves the mouse over
different areas. This can be done by setting the onMouseOver event to be
a function which changes the src of an image. The function is passed a
paratmeter showing which image to show. Aor e)ample the page below
initially displays -default.gif-& but it will display ' other images when the
mouse is rolled over two paragraphs :
<ht./>
<hea0>
<tit/e>U5tit/e0 Doc3.e5t<#tit/e>
<.eta http-e23iv4"Co5te5t-T6pe" co5te5t4"te7t#ht./8 charset4iso-
99:;-)">
<SC-!PT TYPE4"te7t#<avascript">
<!--
f35ctio5 showPic=f>
F
0oc3.e5t'pic'src4f8
G
## -->
<#SC-!PT>
<#hea0>
<?o06 >
<p o5Mo3seOver4"showPic=Lpic)',ifL>"> Pic o5e <#p>
<p o5Mo3seOver4"showPic=Lpic@',ifL>"> Pic two<#p>
<i., 5a.e 4 "pic" src4"0efa3/t',if">
<#?o06>
<#ht./>

%ote how - and @ have been used in the calls to showPic.
Chapter
4
Page 17
*ollover on an 'mage
We can similarly change an image when the mouse rolls over it and leaves
it. /n the page below& the image is initially default.gif. Whn eteh mouse
goe sover it it becomes pic1.gif& and pic'.gif when the mouse leaves:
<ht./>
<hea0>
<tit/e>U5tit/e0 Doc3.e5t<#tit/e>
<.eta http-e23iv4"Co5te5t-T6pe" co5te5t4"te7t#ht./8 charset4iso-
99:;-)">
<SC-!PT TYPE4"te7t#<avascript">
<!--
f35ctio5 showPic=f>
F
0oc3.e5t'pic'src4f8
G
## -->
<#SC-!PT>
<#hea0>
<?o06 >
<i., 5a.e 4 "pic" src4"0efa3/t',if"
o5Mo3seOver4"showPic=Lpic)',ifL>" o5Mo3seO3t4"showPic=Lpic@',ifL>"
>
<#?o06>
<#ht./>
5re#loading images
/mages may tae a while to load& and the usually happens as the part sof
the page are displayed. 4 common techni>ue is to load all the images into
memory before the page is displayed * the user still has to wait& but at least
they appear in one go.
This is done by creating /amge ob+ects& and telling ,ava!cript where to get
them from& in statements that will e)ecute first when the page loads. Aor
e)ample :
<ht./>
<hea0>
<tit/e>U5tit/e0 Doc3.e5t<#tit/e>
<.eta http-e23iv4"Co5te5t-T6pe" co5te5t4"te7t#ht./8 charset4iso-
99:;-)">
<SC-!PT TYPE4"te7t#<avascript">
<!--
var i.a,e)A i.a,e@A i.a,e%8
f35ctio5 preLoa0=>
Page 1=
F
i.a,e) 4 5ew !.a,e=%(A%(>8
i.a,e@ 4 5ew !.a,e=%(A%(>8
i.a,e% 4 5ew !.a,e=%(A%(>8
i.a,e)'src4"0efa3/t',if"8
i.a,e@'src4"pic)',if"8
i.a,e%'src4"pic@',if"8
0oc3.e5t'pic'src 4 i.a,e)'src8
G
## -->
<#SC-!PT>
<#hea0>
<?o06 o5Loa04"preLoa0=>" o5Mo3seOver4" 0oc3.e5t'pic'src 4
i.a,e@'src" >
<i., 5a.e 4 "pic" >
<#?o06>
<#ht./>

The preLoad function is called as the body loads. /t creates 1 /mage
ob+ects& then sets their src to be the filenames. /t then initialises an img
with one of them.
%ote the onMouseOver does not call a ,ava!cript function& but +ust
e)ecutes a single statement.
4lso note image1 image' and image1 are -global- variables. This mean
sthey are not declared inside preLoad23. /f they were& they would be
limited in -scope- to that function. /n fact they are global& so that other
functiosn could reference them as well.
/ancy menus
Many sites use fancy drop*down menus. These can be done using a
combination of styles settings and ,ava!cript.
The page below initially loos lie
and when the user clics on a bloc& they get
Page 15
The ey to this is that styles are defined for the menu blocs& an dthey
have a -display- style of -none- that is they are not displayed. 4n on6lic
function is set up for the menu& which changes the display to -bloc& so
they become visible. Parameters are passed to the clic method so it nows
which bloc to display& and how far across the screen:
<hea0>
<tit/e> ----- .e53s ------- <#tit/e>
<SC-!PT TYPE4"te7t#<avascript" >
<!--
f35ctio5 .o3seMetho0=/eftPosA which!D>
F #C whe5 the6 c/icI o5 a .e53 ite. C#
#C cha5,e fro. 0isp/a6 5o5e to 0isp/a6 ?/ocI - ca5 see it C#
0oc3.e5t',etE/e.e5t6!0=which!D>'st6/e'0isp/a6 4 "?/ocI"8
#C .aIe it correct positio5 across scree5 C#
0oc3.e5t',etE/e.e5t6!0=which!D>'st6/e'/eft 4 /eftPos8
G
f35ctio5 hi0e1,ai5=which!D>
F #C whe5 the6 c/icI hi0eA revert to 0isp/a6 5o5e C#
0oc3.e5t',etE/e.e5t6!0=which!D>'st6/e'0isp/a6 4 "5o5e"8
G
##-->
<#SC-!PT>
<st6/e t6pe4"te7t#css">
<!--
O!D)A O!D@ F #C i5itia/ setti5,s of the two .e53 ?/ocIs C#
fo5t-fa.i/6+ Me5evaA 1ria/A He/veticaA sa5-serif8
fo5t-siHe+ )@p78
co/or+ ODDDDDD 8
0isp/a6 + 5o5e8 #C <<<< so 6o3 ca5t see the. C#
?acI,ro350-co/or4 Offff((8
positio5+ a?so/3te8
top+ &(p78
wi0th+ ::p78
?or0er+ thi5 so/i0 ?/acI
G
O.e53!te. F #C st6/e for .e53 ite.s C#
fo5t-fa.i/6+ Me5evaA 1ria/A He/veticaA sa5-serif8
Page 1#
fo5t-siHe+ ):p78
co/or+ ODD(((( 8
?or0er+ thi5 so/i0 ?/3e8
?acI,ro350+ O99ffff8
c3rsor+ poi5ter #C this is CSS @') C#
G
-->
<#st6/e>
<#hea0>
<?o06 >
<!-- the two .e53 ?/ocIs - i5itia//6 hi00e5 -->
<0iv i04"!D)" >
<a href4"http+##www',oo,/e'co."> Moo,/e <#a><?r>
<a href4"http+##www',oo,/e'co."> Moo,/e <#a><?r>
<a href4"http+##www',oo,/e'co."> Moo,/e <#a><?r>
<a href4"<avascript+hi0e1,ai5=L!D)L>">C/ose<#a>
<#0iv>
<0iv i04"!D@" >
<a href4"http+##www'6ahoo'co."> Yahoo <#a><?r>
<a href4"http+##www'6ahoo'co."> Yahoo <#a><?r>
<a href4"http+##www'6ahoo'co."> Yahoo <#a><?r>
<a href4"<avascript+hi0e1,ai5=L!D@L>">C/ose<#a>
<#0iv>
<!-- the .e53 0isp/a6e0 as a o5e row ta?/e -->
<ta?/e ><tr>
<t0 o5C/icI4".o3seMetho0=L@(p7LA L!D)L>8" i04".e53!te.">
/ocI o5e <#t0>
<t0 o5C/icI4".o3seMetho0=L;(p7LA L!D@L>8" i04".e53!te.">
/ocI two <#t0>
<#tr><#ta?/e>
<#?o06>
<#ht./>

You might also like