Escolar Documentos
Profissional Documentos
Cultura Documentos
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 2 of 73
In the javascript tutorials you will learn how to create variables, how to create arrays, how
to use loops, conditions and functions as well as learning about the document object model
(DOM).
Also in this javascript tutorial you will learn how to create mouse rollovers, how to create
instances of objects and how to resize windows.
The javascript tutorials also cover strings, dates and maths functions.
What is JavaScript?
JavaScript is a programming language.
If you were concerned before that HTML and CSS was a bit like programming then
JavaScript is certainly heading into the dark realms of the software developer.
Based fundamentally around the Java language JavaScript enables you to add interactivity
to your pages.
It can be used for animation, games, form validation and many other things.
HTML is the tool that is used to display and format information in a browser. JavaScript
works alongside HTML to give the browser more power.
To give just a tiny indication of the power of javascript enter your name into the box below
and press the button.
JavaScript is a client side programming language. What does that mean? It means that it
happens on the user’s browser and not where the web page is stored.
Why are you telling me this? If you create a game in JavaScript and the user loads the page
they can log off the internet and still play the game because once it is loaded into their
browser it needs no further connection to the network.
This is useful when thinking of forms. If as a programmer you had a user fill in a form and
they sent it off to be validated and the validation was done by the server then it means the
user sends all their data across the world just to be told that they have entered something
incorrectly. If they are on a small modem then this will take a bit of time.
If the form was validated on the client using JavaScript then as soon as they entered a
wrong value the browser can tell them so.
Inline javascript
If you want to add just a small bit of JavaScript then you will probably use inline JavaScript
within your HTML code.
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 3 of 73
To add JavaScript into HTML the tags <SCRIPT LANGUAGE=”JavaScript”> and </SCRIPT>
are used. The first tag tells the browser that a script is about to be used and that script is
JavaScript. The second tag tells the browser that the script has finished.
<HTML>
<HEAD>
</HEAD>
<BODY>Hello and welcome to Newell Web Services.
<SCRIPT LANGUAGE="JavaScript">alert ("Welcome to Newell Web
Services");
</SCRIPT>
</BODY>
</HTML>
External Files
If you have a number of functions that run JavaScript then you should place these in a
separate file with a .js extension and link them in as follows:
<HEAD>
<SCRIPT LANGUAGE="JavaScript" SRC="external.js">
</HEAD>
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 4 of 73
What is a variable?
A variable is an area of memory that stores data.
Its like writing a name and phone number into an address book. Whenever you need that
number again you open the address book, search for the name and there is the number.
The word VAR means that you are about to assign and area of memory (called a variable).
The word name is what you will call this area of memory whenever you need to know what
is in it. “John Smith” is the value assigned to name.
Therefore if you now typed in the following the words “Hello John Smith” would be
displayed.
<HTML>
<HEAD>
</HEAD>
<BODY>
<SCRIPT Language=”JavaScript”>
VAR name=”John Smith”;
Document.write(‘Hello ‘ + name);
</SCRIPT>
</BODY>
</HTML>
The document.write part of the above code is used to display text to the screen. The first
thing it displays is the text “Hello “. It then sees the variable name. It knows not to display
the word name because it is not enclosed in “”. That means that it must be a variable.
So the browser goes off and finds out what was in the variable name. The variable name
contains “John Smith”.
At this point you may be thinking why bother with variables why couldn’t I just type in
“Hello John Smith”?
If you were sure the name would always be John Smith then yes it would be easier to enter
";Hello John Smith"; straight into the body of your page but imagine the value for name
was retrieved from a form. The variable name could contain anything therefore using
javascript your page always says hello to the correct person.
Variable Types
There are 4 types of variable.
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 5 of 73
To make it easier to read code and so other people reading your code can understand it
better variables are usually declared with the type in front of them.
For example:
At a later stage in your script you may wish to change the value of this variable.
The above code creates a variable called name and assigns the value “John Smith” to it.
The second line changes the value of name to “Gregory Jones”.
Conversion
Imagine you have the following two variables:
Are they the same? The answer is no they are not. The first variable is a string and the
second variable is an integer. To turn a string into an integer or a floating point number you
have to call special functions as follows:
The parseint function converts the string age into a number so that it can be added to
yourage to give totalage.
You can also convert back the other way. For example you can convert 21.56 to a string.
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 6 of 73
Arrays
An array is probably termed best as a group of variables all with the same name.
The above code writes all the months of the year to the screen. For example:
January February March April May June July August September October November
December.
It took 24 lines of code. Imagine you need a variable to store all your friends phone
numbers.
If you have hundreds of friends that would take a lot of effort to display them all using
document.write statements.
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 7 of 73
The variable months is declared as an array which means it can hold multiple values. In the
above case it holds all twelve months of the year.
Notice that the initial index is 0 and not 1. The last index is 11 and not 12.
Ok so to set up an array with 12 months took 1 line of code as opposed to 12. What about
displaying the contents of the array?
I know what your thinking. Its not saved much effort has it.
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 8 of 73
for (idx=0;idx<12;idx++)
{
document.write(months[idx] + " ");
}
You don't need to understand the workings of this code at this point. Needless to say
however that the output from the above is exactly the same as the output from the previous
example which is as follows:
Counting Arrays
There may be times when you do not know how many elements there are in an array and
you need to find out. In the previous example you will see this line:
for (idx=0;idx<12;idx++)
Notice that the bit in bold has the number 12. This is because we know there are 12 months
in a year.
Imagine for a moment that we did not know how many months there were in the year and
so did not know how many elements there were to the array.
You can find this out by using the length property as follows:
For (idx=0;idx<months.length;idx++)
Sorting Arrays
Imagine you have an array of data which is perhaps your friends names. For example Jim,
Alison, Paul, Steve and Barney.
If you displayed the names using the document.write statement then they would come out
in the order Jim, Alison, Paul, Steve and Barney.
Now imagine you want the names to come back in Alphabetical order.
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 9 of 73
What will be the value in age3? The actual value of age3 is “2435”. The reason for this is
the + concatenates two or more strings together.
What will be the value in age3? If you think it is 59 then maybe you should go back to the
previous chapter. The actual value of age3 is again “2435”. The reason for this is that any
expression that contains a string and a + sign will make all other values a string. In the
previous example because age2 is a string it instantly converted age1 to a string and placed
them in age3.
Finally:
What will be the value of age3? If you think it is 59 then don’t despair because actually it is.
Both age1 and age2 are integers and so age3 is an integer as well and this is the way we do
arithmetic.
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 10 of 73
The above would add 1 to age1 and then subtract 1 from age1.
The ++ is the same as AGE1 = AGE1 + 1 and the – is the same as AGE1 = AGE1 – 1.
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 11 of 73
What is a condition?
IF someone gives me money THEN I am very happy
ELSE I am very unhappy.
END IF.
A condition basically asks whether a statement is true or not such as are bananas yellow?
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
var num = 74;
function guessnum(){
var guess = document.forms['form1'].num.value;
if (guess == num)
{
alert("well done");
}
if (guess < num)
{
alert("Too low");
}
if (guess > num)
{
alert("Too high");
}
}
</SCRIPT>
</HEAD>
<BODY>
<H1>Guess the number between 1 and 100</H1>
<form name="form1">
Enter a number <input type="text" size=3 maxlength=3
name="num"> <input type="button" onClick="guessnum();"
value="Enter">
</form>
</BODY>
</HTML>
This is a simple guess the number script. Simply enter a number in the box below between 1
and 100. If you guess the number right the words "well done" appear.
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 12 of 73
This calls the function guessnum (Functions will be looked at in a later chapter).
There are 3 conditional statements to check that whether the number entered is the same
as the number to guess or lower than the number or higher than the number.
If (statement == statement)
{
Do whatever is between the brackets
}
The if statement starts off with the word if and then compares the parts between the
brackets (). If the statement is true then the part between the { and } are performed.
The following table shows a comparison operator and what it actually means.
Operator Description
== Is equal to.
> Is greater than
< Is less than
>= Is greater or equal to
<= Is less than or equal to
! Not
Actually what this does it place the value of B into A and so the statement is actually true.
The actual line should have been if (A == B) which translates in English to If A is equal to
B.
The ! negates the statement so the line if (A != B) means IF a is not equal to B. The line if
(A !< B) means if A is not smaller than B.
Multiple Comparisons
It is possible to compare more than one statement.
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 13 of 73
var a= 12;
var b= 22;
var c = 36;
if (a< b)
{
if (a< c)
{
document.write(“a is the smallest”);
}
}
As you can see one IF statement is embedded between another IF statement and it is
perfectly fine to do this. Translated into English this turns into.
IF A is smaller than B then if A is smaller than C display A is the smallest number. This is
actually true because A is the smallest number.
There is a better way of performing the above though to get the same result.
var a = 12;
var b = 22;
var c = 36;
if (a < b && a < c)
{
document.write(“A is the smallest”);
}
Notice the && symbols this means and. So the above statement translates into IF A is
smaller than B and A is smaller than C display A is the smallest.
Operator Description
&& And
|| OR
This is because the user has entered a string and this cannot be compared with the
number.
To find out whether a variable contains a number you can use a function called isNaN as
follows:
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 14 of 73
if (isNaN(guess))
{
alert("You must enter a number");
}
Else Statements
So far we have looked at what happens if a statement is true but sometimes you want one
thing to happen if something is true and something else to happen if something is false.
Lets take a simplified version of the earlier game as an example. This time if the user
enters the wrong number they are just told they entered the wrong number.
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
var num = 74;
function guessnum()
{
var guess = document.forms['form1'].num.value;
if (guess == num)
{
alert("well done");
}
else
{
alert("You entered the wrong number");
}
}
</SCRIPT>
</HEAD>
<BODY>
<H1>Guess the number between 1 and 100</H1>
<form name="form1">
Enter a number <input type="text" size=3 maxlength=3
name="num"> <input type="button" onClick="guessnum();"
value="Enter">
</form>
</BODY>
</HTML>
The text in bold in the example above shows how to do something if a condition is untrue
and is based around ELSE { }. Anything between the two {} will be performed if the
statement is untrue.
Loops
Loops are used to run a section of code over and over again. In an earlier chapter you saw
how that was useful because it meant that you could display all the months of the year with
less lines of code.
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 15 of 73
For Loops
While Loops
For Loops
A for loop is used to perform a section of code a set number of times:
<HTML>
<HEAD>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
var idx=1;
for (idx=0;idx<15;idx++)
{
document.write ("Hello World<BR>");
}
</SCRIPT>
</BODY>
</HTML>
for (statement)
{
do stuff
}
The FOR part tells the browser that a loop is about to occur. The statement part says how
many times the loop will occur. The { and } denotes which lines of code will be performed
during the length of the loop.
The first part IDX=0 sets the variable IDX to 0. The IDX<15 will run the loop all the time
IDX is less than 15. IDX++ increments IDX by 1 every time the loop has finished. This
means that the loop runs 15 times before IDX is 15.
<HTML>
<HEAD>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
var idx=0;
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 16 of 73
while (idx<15)
{
document.write ("Hello World<BR>");
idx++;
}
</SCRIPT>
</BODY>
</HTML>
while (statement)
{
Do stuff
}
The WHILE part tells the browser that a while loop is going to start and that the loop will run
until the condition is met in the STATEMENT part.
In the example above the statement is IDX<15 which means until IDX is 15 keep displaying
Hello World. Notice the line in that increments idx. (IDX++). This is important as without it
the loop would run forever.
This is the useful part of a while loop. It can be used to get input from a user a specified
number of times or whenever the user enters a certain value.
<HTML>
<HEAD>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
var idx=0;
while (idx!=74)
{
idx = window.prompt('Guess the number',0);
if (idx<74)
{
alert('too low');
}
if (idx>74)
{
alert('too high');
}
}
</SCRIPT>
</BODY>
</HTML>
The above example is back to the guess the number game. The while loop is performed until
the user enters 74. Instead of using a form to get the user to enter a number the windows
prompt is used.
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 17 of 73
Fortunately there is a break command that enables you to break out of a loop. Any
variables set within the loop keep their values at the time of the break.
The above example was ok but what happens if the user is bored of trying to guess the
number.
<SCRIPT LANGUAGE="JavaScript">
var idx=0;
while (idx!=74)
{
idx = window.prompt('Guess the number, enter 101 to finish',0);
if (idx==101)
{
break;
}
if (idx<74)
{
alert('too low');
}
if (idx>74)
{
alert('too high');
}
}
</SCRIPT>
Fortunately there is a break command that enables you to break out of a loop. Any
variables set within the loop keep their values at the time of the break.
In the above code sample the text in bold basically says if the user enters 101 then break
out of the script.
<SCRIPT LANGUAGE="JavaScript">
var names = new Array
("James","Steve","Paul","Amanda","Alice","Jack","Clive","Peter","Barbara","Mandy");
var ages = new Array(33,56,67,83,22,44,53,22,89,84);
var idx=0;
while (idx < 10)
{
if (ages[idx] < 65)
{
idx++;
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 18 of 73
continue;
}
document.write(names[idx] + " you are now eligible for a
government bus pass<BR>");
idx++;
}
</SCRIPT>
The continue statement in the example above skips to the end of the loop and goes around
again. The document.write statement therefore does not occur for anyone under 65.
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 19 of 73
A function is a block of code that can be ran over and over again. They make code much
more readable and it saves time when editing.
Declaring a function
Functions are created in the <HEAD> section of a HTML document. This is to ensure that
they are loaded prior to being called..
The function statement lets the browser know that the next block of code will be a function
and will only run that block of code when the function is called within the body section.
The function name is a unique name that you have given the function that is meaningful to
what the function actually does.
The arguments are a list of variables that you have sent to the function separated by
commas for example function myaddress(house,street,town)
Any code between the { and } tags are only ran when the function is called.
Calling functions
To call a function you just have to specify the name of the function and supply any
arguments that it requires.
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
function checkage(age)
{
if (age < 18)
{
document.write("Are you old enough to be looking at this
site?");
}
else
{
document.write("Welcome to my site");
}
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 20 of 73
}
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT Language="JavaScript">
var age = prompt("Enter your age",0);
checkage(age);
</SCRIPT>
</BODY>
</HTML>
The above example shows a function called checkage which accepts age as a parameter.
If the age that is passed to the function is less than 18 then one message is displayed and if
it is 18 or over then another message is displayed.
A global variable is held in memory all the time a page is loaded. A local variable dies at the
end of a function.
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
var age = 0;
function checkage()
{
var myage = 29;
if (age < 18)
{
document.write("Are you old enough to be looking at this site?");
}
else
{
document.write("Welcome to my site");
}
}
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT Language="JavaScript">
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 21 of 73
What do you think will be displayed as the output of this script. This script would actually
cause an error?
The reason is that myage is declared within the function checkage and so when it is checked
outside of checkage it does not exist and therefore cannot be compared to age.
Returning values
As well as being able to run code over and over again, saving editing time and being
incredibly useful functions can also return values.
Think about the previous example when there was an error. Wouldn’t it have been good if
myage was available?
The following example shows how to return myage so that the above example will work.
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
var age = 0;
function checkage()
{
var myage = 29;
if (age < 18)
{
document.write("Are you old enough to be looking at this site?");
}
else
{
document.write("Welcome to my site");
}
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 22 of 73
return myage;
}
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT Language="JavaScript">
age = prompt("Enter your age",0);
var myage = checkage();
document.write("<BR>You are " + age + " years old");
if (age > myage)
{
document.write("<BR>You are older than me");
}
if (age < myage)
{
document.write("<BR>You are younger than me");
}
if (age == myage)
{
document.write("<BR>We are the same age");
}
</SCRIPT>
</BODY>
</HTML>
The first line in bold text is within the function checkage and it returns the value of myage.
The actual call to the function has changed. We know that checkage now returns a value
and so that value can be placed into a variable. In the example above the value has been
placed in myage.
This is true but the myage in the function is only alive whilst the function is alive and ceases
to exist outside the function therefore the second declaration of myage is actually a new
variable.
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 23 of 73
<HTML>
<HEAD>
<SCRIPT Language="JavaScript">
function boo()
{
document.write("<IMG SRC='images/crab.gif'>");
}
</SCRIPT>
</HEAD>
<BODY>
<form name="form1">
<input type="button" value="click me"
onclick="window.setTimeout('boo()',5000);">
</form>
</BODY>
</HTML>
The setTimeout statement has two attributes. The first attribute is the statement that it is
going to run and the second attribute is how long it is before it runs the statement.
The statement can be one singular statement like display hello or it can be a function.
In the example above the function boo is called after 5000 milliseconds.
Regular Intervals
The setTimeout method was good for an ad-hoc boo effect but what if you wanted
something to happen at regular intervals.
The following example fills the second text box every 5000 milliseconds with the contents of
the first text box.
<HTML>
<HEAD>
<SCRIPT Language="JavaScript">
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 24 of 73
window.setInterval("document.form1.text2.value =
document.form1.text1.value",5000);
</SCRIPT>
<FORM name="form1">
<INPUT TYPE="text" NAME="text1" value="input">
<BR>
<INPUT TYPE="text" NAME="text2" value="input">
</FORM>
</BODY>
</HTML>
Notice the window.setInterval statement. The format for the setInterval is the same as the
setTimeout and so the first parameter is a statement and the second parameter is the time
value.
Stopping Timers
To stop a timer the clearTimeout and clearInterval functions are called.
The following example is the same as the one above but you can stop the process by
pressing the stop button.
<HTML>
<HEAD>
<SCRIPT Language="JavaScript">
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
stop = window.setInterval("document.form1.text2.value =
document.form1.text1.value",5000);
</SCRIPT>
<FORM name="form1">
<INPUT TYPE="text" NAME="text1" value="input">
<BR>
<INPUT TYPE="text" NAME="text2" value="input">
<INPUT TYPE="button" onClick="window.clearInterval(stop);"
value="Stop">
</FORM>
</BODY>
</HTML>
Looking at the code above you can see that the first thing that I have done is to have a
variable called stop that names the interval. This was so that when the clearInterval
statement was called the browser knew which timer to stop.
Events
The boring programming bit is nearly over and soon you will be able to create quite exciting
little scripts. In the previous chapters you have learned the foundations of many
programming languages.
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 25 of 73
Events are things that happen and can be triggered by the following occurrences:
All these events are useful for JavaScript programmers because these events can be used
to make other things happen.
For example have you ever left a web page and a pop up advert has appeared. Do you want
to know how that happens?
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
function winpopup()
{
wind_dialog=window.open
("http://www.partnershop.co.uk/shop/1918", "symbols",
"top=100,left=100,height=450,width=587,scrollbars=no");
}
</SCRIPT>
</HEAD>
<BODY onunload="winpopup()">
</BODY>
</HTML>
The important part about the above code is the onload=”” section. This is an example of an
event.
<html>
<head>
<title>Mouse Click</title>
<meta http-equiv="Content-Type" content="text/html;
charset=iso-8859-1">
<script language="javascript">
function mclick()
{
document.all.test.style.background = "red";
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 26 of 73
</script>
</head>
<body bgcolor="#FFFFFF" text="#000000">
<div id="test" style="background: yellow" onclick="mclick()">
Click here with your mouse
</div>
</body>
</html>
When you click the mouse in the yellow section above the background changes to red
This happens because the function mclick is called when the onclick event is fired.
Instead of using the onclick event the above example uses the ondblclick event.
Have you ever wondered about the rollover mouse buttons that you get on a lot of web
sites?
These can be created using cascading style sheets by using the hover tag but it can also be
achieved by using JavaScript and with greater effect.
Instead of using the onclick or on doubleclick we use the onmouseover and onmouseout
events.
Whenever the mouse is over an element it causes a mouseover event to occur. When the
mouse leaves the element the onmouseout event occurs.
<html>
<head>
<title>Mouse Click</title>
<meta http-equiv="Content-Type" content="text/html;
charset=iso-8859-1">
</head>
<body bgcolor="#FFFFFF" text="#000000">
<div id="test" style="background: yellow"
onmouseover="document.all.test.style.background='red'"
onmouseout="document.all.test.style.background='yellow'">
Click here with your mouse
</div>
</body>
</html>
This time when the mouse is over the text the background changes to red but when the
mouse moves away it turns back to yellow.
Two further events that can occur are onmousedown and onmouseup which are the states
of the mouse when the user holds down the mouse button and when the user lifts their
finger off the mouse button.
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 27 of 73
I'm sure at some stage you have come across a program that says "Press any key to
continue". Using the keypress event you can cause an event to happen.
For example on this page I have made it so that if you press a key the background colour
changes.
function changecolour()
{
document.all.page.style.background = "cyan";
}
and then I have used the onkeypress function in the body statement.
<body onkeypress="changecolour()">
Also on this page I have added a secret key that changes the colour to yellow. Its one of
the letter keys... see if you can find it.
Every key on the keyboard has a code number that goes with it. Letters A to Z are 97
through 123. A=97, B=98, C=99 etc. The code number is held in window.event.keycode.
function changecolour(keycode)
{
if (keycode=="98")
{
document.all.page.style.background = "yellow";
}
else
{
document.all.page.style.background = "cyan";
}
}
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 28 of 73
The keycode is passed to the function within the <body> tag as follows:
<body onkeypress="changecolour(window.event.keyCode)">
function getanswer(form)
{
var val1 = parseInt(form.val1.value);
var val2 = parseInt(form.val2.value);
var ans = val1 + val2;
form.answer.value = ans;
}
If you enter the above function in the head section and then add this form
<form name="form4">
Enter values into the 2 boxes and press the tab key to get the
answer:<br>
<input type="text" size=3 name="val1"> + <input type="text"
size=3 name="val2"> = <input type="text" size=3
name="answer" onfocus="getanswer(this.form)">
</form>
When you tab into the third box the onfocus event occurs which calls getanswer().
The onblur event occurs after the focus leaves the control. Using the onblur event you can
test whether number were actually entered in the first 2 boxes.
For example:
To achieve this effect add the following function to your <head> section:
function changecol(form)
{
document.all.page.style.background = form.select
[form.select.selectedIndex].text;
}
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 29 of 73
When a web page is first loaded it triggers the onload event and when the page is left it
triggers an onunload event.
To see why something did not work you can trap errors using the onerror event.
Finally there is also an onabort event which occurs when the user presses the x key on the
browser toolbar.
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 30 of 73
The document
The document is basically the whole HTML page loaded into the browser window.
All tags within a document are called elements. Things such as images, tables and forms.
Forms have elements of their own such as radio buttons and text boxes and these are
referred to as subobjects.
The following diagram helps to show the map of how things fit together.
The above diagram is not complete but hopefully you can see that the window is the top
element. Even when dealing with the current page there is a window surrounding it but on
the page that is loaded this is usually not referred to.
Alongside the document are the location and history properties which enable you to see
which pages were previously loaded or enable you to change the page location.
The document has attributes such as background colour and foreground colour. It also has
elements such as images, links and forms.
Images have their own attributes such as src, alt, border, width and height. Links have their
own attributes such as href.
Forms have subobjects such as radio buttons and text areas which themselves have
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 31 of 73
attributes.
I know you are needing an example right now so here is a quick example of accessing the
documents background colour to change the background colour of the webpage.
document.body.style.background = "blue";
The document is your HTML page loaded in the browser window. The body is the part of
your HTML page between the <body> and </body> tags. The style states that you want to
change the style of the body and background states that you want to change the
background colour.
Every single element can be accessed using the document object model.
Ok so its hard to know how to access each property and it takes a certain amount of
practise. Try to think logically and you can probably guess how to access certain objects.
Subobjects
A subobject is an object that is part of another object.
For example a form is a subobject of a document. To access a form you have to first access
the document as follows:
document.form1
document.form1.check1.value
Subobjects are an array of elements below the Object. For example a form is a subobject of
a document. If you have two forms on a page there are 2 elements to the array. This
means you can access the form by name, for example document.form1 or by its position in
an array, for example document.forms[0].check1.value;
Throughout this tutorial you have been accessing objects without realising it.
The document.write() clause that displays text to the screen is using the write function
available to document.
You have created variables that are strings. Strings are an object formed of a number of
characters and each string has functions that can be called such as substr.
These type of objects are called predefined objects and we’ll be looking at these more
closely in further chapters.
New Objects
You can create your own objects.
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 32 of 73
The above would create mydate as a date which enables you to access all the properties of
a date object.
The following example shows how to create a new object with its own methods and
properties.
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
function welcomeObject(var1)
{
welcomeObject.name = var1;
welcomeObject.welcome = printwelcome(var1);
}
function printwelcome(name)
{
document.write("Hello " + name);
}
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
harry = new welcomeObject("Harry");
harry.welcome();
</SCRIPT>
</BODY>
</HTML>
In the above example there is a new object created called welcomeObject. If you use the
term Object after the function name it creates a new object.
There is a second function created called printwelcome which is created as a method within
welcomeObject.
This may be a little hard to get your head around and I am expecting to get messages on
the forum about this subject. You can go along quite happily without creating your own
objects but if you are reading other people’s code then you may come across this from time
to time.
function hello(form)
{
alert("Hello" + form.name.value);
}
The above function accepts a form as a value. It assumes that the form has a field called
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 33 of 73
Notice that this.form was passed to the function hello(). This relates to the current form
because those are the tags where it is used.
When the function has to access the name field it is much easier to do so because instead
of typing document.form1.name.value all it has to access is form.name.value.
This means the function can be used for any form that has a name field.
This is useful when validating data. You can have one function throughout your whole
system that validates certain fields such as dates and credit card numbers and as long as
those fields exist on the form they can be validated by the relevant function.
Object Properties
The following example lists all the properties for all objects.
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
function displayprops(obj)
{
for (prop in obj) {
document.write(obj + prop + " = " + obj[prop] + "<BR>");
}
}
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
displayprops(document);
</SCRIPT>
</BODY>
</HTML>
The above example shows the properties of the document object. To display the properties
of a form send the form as the parameter to displayprops.
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 34 of 73
The following table shows a list of properties and methods for the array object.
Property Description
Length The number of items in the array
Methods Description
Join() Joins all the elements together with a “,” in
between
Sort() Sorts all the elements into alphabetical or
numerical order
Reverse() Reverses the order of the array
Slice() This takes the elements from one array and
creates a new array with the elements
selected
<HTML>
<HEAD>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
var names = new Array
("Tom","Steve","Gary","Alice","Mary","Dave","Sue","Christian");
document.write("There are " + names.length + " items in the array
names");
var strnames = names.join();
document.write("<BR>The names are " + strnames);
strnames = names.sort();
document.write("<BR>The names in order are " + strnames);
strnames = names.reverse();
document.write("<BR>The names in reverse order are " +
strnames);
strnames2 = names.slice(2,5);
document.write("<BR>An example slice " + strnames2);
</SCRIPT>
</BODY>
</HTML>
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 35 of 73
There are no methods for the image object but you can change the attributes of all the
images in a document.
<HTML>
<HEAD>
<META http-equiv=Content-Type content="text/html;
charset=windows-1252">
<SCRIPT language=JavaScript>
function swap()
{
if (document.form1.imag.value == "1")
{
document.images[0].border = 0;
}
if (document.form1.imag.value == "2")
{
document.images[0].border = 1;
}
if (document.form1.imag.value == "3")
{
var wth = document.images[0].width;
var hgt = document.images[0].height;
wth = wth * 2;
hgt = hgt * 2;
document.images[0].width = wth;
document.images[0].height = hgt;
}
if (document.form1.imag.value == "4")
{
var wth = document.images[0].width;
var hgt = document.images[0].height;
wth = wth / 2;
hgt = hgt / 2;
document.images[0].width = wth;
document.images[0].height = hgt;
}
}
</SCRIPT>
</HEAD>
<BODY>
<FORM name=form1>
<SELECT onchange=swap() name=imag>
<OPTION value=1 selected>Normal</OPTION>
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 36 of 73
<OPTION value=2>Border</OPTION>
<OPTION value=3>Zoom In</OPTION>
<OPTION value=4>Zoom Out</OPTION>
</SELECT>
</FORM>
<IMG src="images/wizzypig.gif">
</BODY>
</HTML>
The above example shows how to amend different attributes on an image. The parts in bold
are the important lines showing how to access an image.
Preloading images
There is a term in JavaScript called preloading images and you would normally do this for a
game or animation. Basically you load all the images in the <HEAD> section of the page.
Then you create images within the document with the source set to blank.gif. When the
onload event is called you replace the blank.gif with the images created in the <HEAD>
section.
The advantages of preloading images means that when running an animation the images
are loaded first and then the entire animation is shown. Imagine showing a slide show and it
jumps every so often because you have to wait for an image to load.
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
wizzy = new Image();
wizzy.src = "images/wizzypig.gif";
</SCRIPT>
</HEAD>
<BODY onload="document.images[0].src = wizzy.src">
<H1>This is a picture of WizzyPig</H1>
<img src="blank.gif">
</BODY>
</HTML>
In the above example you can see that a new image object has been created called wizzy
and the source for wizzy is wizzypig.gif. This loads the picture into the browser’s memory
without displaying it.
In the body section there is an image called blank.gif. This gets replaced by wizzypig.gif
using the body onload event.
Complete
There is a property that you can interrogate to see if the image has completely loaded in the
browser’s window.
If (document.images[0].complete)
{
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 37 of 73
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 38 of 73
Anchors
Each anchor is placed into an array of anchors and so if you have 10 anchors to a page you
can find out what is the name of each anchor as follows:
function booknames()
{
var ind;
for (ind=0;ind<10;ind++)
{
document.write("Bookmark " + ind + " is called " +
document.anchors[ind].name + "<BR>");
}
}
Links
Links are also held as part of an array of links therefore if you have 10 links on a page you
can access them as follows:
If (document.links[0].src = www.google.com)
If (document.links[0].target = “_blank”)
Property Description
HREF Document.links[0].href can be checked to
see where a link is pointing to or can be
amended to point somewhere else
Target Document.links[0].target can be checked to
see where the linked page will be loaded or
can be amended to point elsewhere
Host Document.links[0].host can be checked to
see the domain name of the link
Protocol Document.links[0].protocol can be checked
to see the protocol of the link for example
http: ftp: gopher: mailto:
Pathname Document.links[0].pathname can be checked
to see the actual path of the webfile
Port Document.links[0].port shows which port will
be used.
Hash Document.links[0].hash shows the anchor
name of a link
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 39 of 73
You can also redirect the user to a page that they have previously viewed.
The history object has one property called length which shows how many pages the user
has saved in their browser.
The history object has several methods available such as back(), forward() and go().
<HTML>
<HEAD>
</HEAD>
<BODY>
<H1>This is Chapter 16</H1>
<A HREF="javascript:window.history.back()">Back to previous
page</A>
<A HREF="javascript:window.history.forward()">On to the next
page</A>
</BODY>
</HTML>
Go()
The go method enables you to travel backwards or forwards a certain number of links.
<HTML>
<HEAD>
</HEAD>
<BODY>
<H1>This is Chapter 16</H1>
<A HREF="javascript:window.history.go(-4)">Back 4 pages</A>
<A HREF="javascript:window.history.go(-2)">Back 2 pages</A>
</BODY>
</HTML>
In the above example the user can go back 4 pages or back 2 pages in the history. These
could also be positive numbers such as (+2) or (+3) which would move forward through the
history.
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 40 of 73
This chapter deals with output to a window, formatting windows, changing status bars and
the general look and feel of a window.
Displaying Text
All the way through this tutorial you have seen the document.write() method and how it is
used to display text to the screen.
The document.write() method writes directly to the window and to add new lines you have
to use the tag
.
document.write("hello world")
You can change the text on the status bar using the window.status property as follows:
<BODY onload="document.fgColor='blue'">
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 41 of 73
You can change the visited link and active link using document.alinkColor or
document.vlinkColor etc.
Last Modified
Have you ever been to a site and it has said this page was last updated on 12/9/04 or 1st
September, 2004.
This is very useful to visitors of your site because they know how relevant the page is.
To display the date the page was last modified look at the following example:
The date can be formatted in various ways which will be covered in a later chapter.
It would be good then if every web page had its page name included on it.
You could type out the whole page every time but this is open to error.
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 42 of 73
New Windows
Earlier in the tutorial you were shown how to create a new window using the window.open
method.
1. URL – This is the page that will open within the new window and can be left blank.
2. Name – The second parameter names the window. This means that you can access
this window from the parent window.
3. Style – The third parameter enables you to set the width, height, toolbar, status,
menubar, scrollbars and whether the window is resizable.
The following example shows how to create a window and how to add text to the window:
<SCRIPT LANGUAGE="JavaScript">
window1 = window.open
("","window1","width=200,height=100,toolbar=no,status=no,menubar=no,scrollbars
window1.document.write("<H1>Welcome to the new
window</H1>");
window1.document.write("<p>Notice how the main document is
writing the text to this window using the name of the
window</p>");
When you open a window you can access the parent window by using the window.opener
property.
Closing a window
To close a window you use the window.close() method.
Remember that window is the top level object and so even the page you are viewing now is
a window.
Printing a window
The window.print() method enables you to print the contents of a window or web page.
If there is no printer available then the window.print() method does nothing at all.
Moving a window
You can move a window so that it appears in the position you want it to by using the
window.moveTo() method. The moveTo method takes 2 parameters which are x and y co-
ordinates specified in pixels.
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 43 of 73
Resizing Windows
There are two methods available to enable you to resize a window.
The first method is resizeTo which enables you to respecify the width and height.
The second method is resizeBy which enables you to specify how much bigger or smaller
you want the window.
Alerts
There have been a few examples in this tutorial of alerts appearing on the screen.
They are often used by programmers to determine whether a piece of code is working
properly and are placed in conditional statements to see if a statement is being reached or
not.
They can also be used to say hello to people accessing your page but can be quite
annoying.
alert("Hello World");
Prompting Users
You can ask users for information without having to create a form.
Notice that the prompt() method has two parameters. The first parameter tells the user
what to input and the second gives a default value in this case George.
The confirm dialog box is used to display a message with a yes/no answer.
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 44 of 73
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 45 of 73
This chapter deals with the string object and all the various things that can be done with a
string.
The string object has only one property which is length. However it has a number of
methods as shown in the following table:
Method Description
Bold Makes text bold
FontColor(color) Sets the colour of the text in the string
FontSize(size) Sets the size of the text in the string
Italics() Makes the text italicised
Link(href) Turns the string into a link
Small() Makes the text smaller
Big() Makes the text bigger
Strike() Makes the text strikethrough
Sub() Makes the text subscript
Sup() Makes the text superscript
ToLowerCase() Makes the text lowercase
ToUpperCase() Makes the text uppercase
CharAt(Index) Determines what the character is at a
particular point in the string
Concat(text) Join two strings together
Substring(index1,index2) Find out what text is in character positions
index1 thru index2
Substr(index1,length) The same as substring but for the length of
characters
Search() Searches for a string within text
IndexOf Searches for a string from a certain position
Split() The split function splits a string into two
separate portions.
<HTML>
<HEAD>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
var txt = "The cat and mouse ran around all day and the cat had a
great lunch";
var ands = 0;
for (var ind=0;ind {
if (txt.substring(ind,ind+3)=="and")
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 46 of 73
{
ands = ands + 1;
}
}
alert("There are " + ands + " occurrences of the word and");
</SCRIPT>
</BODY>
</HTML>
The above code defines a string called txt which has the value “The cat and mouse ran
around all day and the cat had a great lunch”.
The purpose of the script is to find how many occurrences of the word and there are.
Therefore a loop was set up starting at 0 and finishing at the length of the string txt.
The word and has 3 characters and so the if statement checks a substring of txt from point
ind (which goes from 0 through to length of txt) and finishing at point ind + 3. If the 3
characters are and then the number of occurrences are increased by 1.
The same example could be used for the substr method. Instead of specifying the start and
finish point of the text it specifies the start and length of text to test.
var txt = "The cat and mouse ran around all day and the cat had a
great lunch";
var ands = 0;
for (var ind=0;ind {
if (txt.substr(ind,3)=="and")
{
ands = ands + 1;
}
}
alert("There are " + ands + " occurrences of the word and");
It may be that the above examples were a bit too advanced for you to appreciate what was
going on so the example below is a simplified way of using substring and substr.
var txt = "The cat and mouse ran around all day and the cat had a
great lunch";
var txt2 = substring(5,8);
var txt3 = substr(1,17);
String Concatenation
During this tutorial there have been a number of examples of joining strings together.
There is an actual method called concat that can join two strings together.
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 47 of 73
document.write(txt.concat(txt2));
txt += txt2;
document.write(txt);
var txt3=txt + txt2;
document.write(txt3);
var txt = "Click here for the Newell Web Services website";
document.write(txt.link("http://www.newellwebservices.com"));
Changing case
To change a string to uppercase use the toUpperString() method and to change a string to
lower case use the toLowerCase() method.
var txt = "Click here for the Newell Web Services website";
document.write(txt.toUpperCase());
document.write(txt.toLowerCase());
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 48 of 73
Earlier on you were shown a rather tricky way of searching through a string for the number
of occurrences of the word and.
The following section shows you how to search for text within a string and how to search for
multiple occurrences of text within a string.
The first option for searching for text is using the search() function.
The search() function searches a string and returns the character position of the found text.
In the above example the number 21 is shown. The string str is searched for the word
Services. If you count along the word Services is 22 characters into the string. The number
21 is shown because a string index always starts at 0. If the word Services does not appear
in the string str the returned value would have been –1.
The above example is ok if you are searching for the word Services and it only appears
once. However if you want to search along a string continuously you would use the function
indexOf().
The indexOf() function can take one or two parameters. The first parameter is the text that
is to be searched, the second parameter which is optional is the position in the string that
the search should begin.
The following example counts how many times the word “and” appears in “You and I and
everyone shall unite as one to make the web a better place”.
var str = "You and I and everyone shall unite as one to make the
web a better place";
var ind = 0
var found = 0
while (ind != -1)
{
ind = str.indexOf("and",ind);
if (ind != -1)
{
found++;
ind++;
}
}
document.write(found);
In the above example the index is set to 0 initially and the str.indexOf statement looks for
the word and using the ind as an index. If the word “and” is found the found variable is
incremented by one and the ind variable is also incremented to stop the indexOf searching
from the same character position.
Splitting a string
Imagine you had written a form whereby a user entered their favourite hobbies separated
by commas. Now the chances are you might want to separate the hobbies into different
strings.
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 49 of 73
The split function enables you to split a string into an array of strings for example the string
“The fox ate the chicken” could be split into an array with 5 occurrences “The”, “fox”, “ate”,
“the”, “chicken”.
The split function takes one parameter, the string separator. This can be anything such as
spaces, commas or a full stop.
Notice in the above example that the string str1 has a list of names. The text in bold splits
the string into an array called str1Array. This is then printed out line by line using a for
loop.
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 50 of 73
Due to the fact that a date cannot be created using a tag or set of tags it must be created
in order to be used. If you cast your mind back to the point when objects were first
introduced you will remember that the word new was used to create new objects. Therefore
to create a date you must use the following syntax:
The date can accept 3 definitions which determine how the date is formatted:
The following example shows you how to set up dates and display them.
<HTML>
<HEAD>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
date1 = new Date("October 2, 2004 20:19:44");
date2 = new Date(2004,9,2);
date3 = new Date(2004,9,2,20,19,44);
document.write(date1 + "
");
document.write(date2 + "
");
document.write(date3);
</SCRIPT>
</BODY>
</HTML>
If you run the above example you will see that essentially all the dates are 2nd October,
2004. Now look at the definition for date2 and date3. They both have the month set to 9.
The month parameter starts at 0 and so January is 0, February is 1 etc.
The following table shows the methods available for your newly created dates.
Method Description
toGMTString() This will return the current Greenwich mean
time (GMT) which is the time zone where all
other times are measured from.
toLocaleString() This will return the current date and time for
the local time zone
getDate() This returns the day of the month
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 51 of 73
To display the local date and time use the toLocaleString() function:
For example the getDate() function returns the day portion of the date, the getMonth
function returns the month portion of the date and the getYear function returns the year
portion of the date.
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 52 of 73
From this you can create a function that will work out someone’s age
function agecheck(form)
{
cDate = new Date();
var cDays = cDate.getDate();
var cMonth = cDate.getMonth();
cMonth++;
var cYears = cDate.getYear();
var aDays = form.dy.value;
var aMth = form.mth.value;
var aYear = form.yr.value;
var yearsold = cYears - aYear;
if (aMth > cMonth)
{
yearsold--;
}
if (aMth == cMonth)
{
if (aDays > cDays)
{
yearsold--;
}
}
alert("You are " + yearsold + " years old");
}
Add this form to your <body> section and you will have an agecheck function
<form name="form1">
Enter your birthday (dd/mm/yyyy) <input type="text" name="dy"
size="2">/<input type="text" name="mth" size="2">/<input
type="text" name="yr" size="4">
<input type="button" onclick="agecheck(this.form)" value="Check
age">
In the above example the user enters an age. I have assumed that the user will accept the
correct age, there is no checking for invalid numbers etc. When the user pressed the button
the function agecheck gets called. This creates a new date which is the current date and
then this date is split into days, months and years and compared with the user’s entries to
work out their age.
The getHours(), getMinutes() and getSeconds() function returns the time portions of a date.
function startclock()
{
cTime = new Date();
var cHours = cTime.getHours();
var cMinutes = cTime.getMinutes();
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 53 of 73
Notice that in the above example a new string field was created for hours, minutes and
seconds. This was in case the hours, minutes or seconds were less than 10. If they were
less than 10 you could expect the input box to show 9:2:7 instead of 09:02:07.
For example imagine you wish to hold details of your wedding anniversary in a script so that
every time you ran the script you could not forget when that date is.
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 54 of 73
In the above example I have set the year to 2004 so that you will see the day of the week
it falls in the current year. Setting the time was unnecessary but was included to show it
could be done.
Time Zones
Earlier on you were shown how to display the current date and time for your local time
zone.
The function getTimezoneOffset() returns how far or behind you are to Greenwich Mean
Time in minutes.
The following example will work for you as long as you are not running Greenwich Mean
Time:
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 55 of 73
Maths is a fundamental part of programming but this section is more to do with real maths
than anything else. Skip it if you like but you may find some of the functions in this chapter
useful, especially if you are thinking of making a JavaScript calculator. More importantly is
the ability to generate random numbers which is very useful indeed.
There are a large number of methods associated to the maths object including abs(x), ceil
(x), floor(x), sin(x), cos(x), tan(x), log(x), min(x), max(x), pow(x,y), random() and sqrt(x).
Random Numbers
Remember way back when we created a guessing game between 1 and 100. It was a bit
dull because the number was set firmly in the script and so once the number was found that
was it.
If the number could have been created after each time the game was played then it could
be played over and over again.
The two main functions for generating random numbers are random() and floor().
The random() function returns a random number between 0 and 1 for example:
alert(Math.random());
As you can see the number generated is between 0 and 1 which is not overly useful. If you
multiply that number by another number then you get a value between 0 and that number.
For example to get a number between 0 and 40 look at the following example:
alert(Math.random() * 40);
This is where the floor function comes in. The floor function removes all the digits after the
decimal point and so:
Mathematical Constants
I have lulled you into a false sense of security by showing you the randomise function first.
It is by far the most interesting thing you will learn in this chapter.
This section deals with mathematical constants such as Euler’s constant, natural logarithms,
PI and Square Roots.
The best way to show how these are used is with an example as follows:
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 56 of 73
document.write("<H4>Mathematical Constants</H4>");
document.write("Eulers constant: " + Math.E + "<br>");
document.write("Natural logarithm of 10: " + Math.LN10 +
"<br>");
document.write("Natural logarithm of 2: " + Math.LN2 + "<br>");
document.write("Base 10 logarithm of Euler: " + Math.LOG10E +
"<br>");
document.write("Base 2 logarithm of Euler: " + Math.LOG2E +
"<br>");
document.write("PI: " + Math.PI + "<br>");
document.write("Square root of one half: " + Math.SQRT1_2 +
"<br>");
document.write("Square root of two: " + Math.SQRT2 + "<br>");
Trigonometry
Ok so now we are getting in deep. I remember this subject from school. We spent hours,
weeks, months working on it and I’m sure in a number of trades it is very useful. I rarely
use it myself but to make the tutorial as complete as possible here is how to use the
functions sin(), cos(), tan(), acos(), asin() and atan(). (Incidentally these are the least
pressed keys on my calculator).
All the aforementioned functions take one value and return an angular value in radians. For
those who don’t know a radian is a mathematical measure of an angle. 360 degrees is equal
to 2 Pi radians. You can calculate the more common angular measurement of degrees by
multiplying the number of radians by 57.3.
JavaScript also includes the trigonometric method atan() which takes 2 coordinate values as
parameters and returns an angular measurement.
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 57 of 73
The log() method takes a number as a parameter and returns the natural logarithm of the
number.
The exp() method takes a number as a parameter and returns the value of Euler’s constant
raised to the power of the number:
<form name="form1">
Value: <input type="text" name="val"><BR>
Log: <input type="text" name="res1"><BR> <>exp:
<input type="text" name="res2"><BR>
<input type="button" value="Compute"
onclick="document.form1.res1.value=Math.log
(document.form1.val.value);
document.form1.res2.value=Math.exp
(document.form1.val.value);">
</form>
Square Roots
The sqrt() function returns the square root of a number.
<form name="form1">
Value: <input type="text" name="val">
Square Root: <input type="text" name="res1">
<input type="button" value="Compute"
onclick="document.form1.res1.value=Math.sqrt
(document.form1.val.value);">
</form>
Squaring Numbers
The sqrt() function returns the square root of a number. The pow() function returns the
square, cube or power of a number for example 2 to the power of 2 is 4.
<form name="form1">
Value: <input type="text" name="val"><BR>
Power: <input type="text" name="power"><BR>
Result: <input type="text" name="res1"><BR>
<input type="button" value="Compute"
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 58 of 73
onclick="document.form1.res1.value=
Math.pow
(document.form1.val.value,document.form1.power.value);">
</form>
Rounding
If you have a number that includes a decimal point you may wish to round it up to make an
integer. Earlier on in the chapter you saw how the floor() function just dropped the digits
after the decimal point but this is not proper rounding.
<>The round() method will take a number for example 4.45 and round it to a single digit so 4.45
becomes 4. If the number after the decimal point is greater or equal to 5 for example 4.54 then
the number gets rounded up to the next number i.e 5. <>
The floor() function always rounds down because it loses the numbers after the decimal point.
The round function rounds up or down depending on the number after the decimal point. The
ceil() function always rounds up so 4.12 will become 5.
<form name="form1">
Value: <input type="text" name="val"><BR>
Ceil function: <input type="text" name="res1"><BR>
Floor function: <input type="text" name="res2"><BR>
Round function: <input type="text" name="res3"><BR>
<input type="button" value="Compute"
onclick="document.form1.res1.value=Math.ceil
(document.form1.val.value);
document.form1.res2.value=Math.floor
(document.form1.val.value);
document.form1.res3.value=Math.round
(document.form1.val.value);">
</form>
The max() function accepts two numbers and returns the largest of the two numbers.
<form name="form1">
Value 1: <input type="text" name="val1"><BR>
Value 2: <input type="text" name="val2"><BR>
Minimum: <input type="text" name="res1"><BR>
Maximum: <input type="text" name="res2"><BR>
<input type="button" value="Compute" onclick="document.form1.res1.value=Math.min
(document.form1.val1.value,document.form1.val2.value);
document.form1.res2.value=Math.max
(document.form1.val1.value,document.form1.val2.value);">
</form>
Absolute Values
The abs() function takes one parameter and returns the absolute value for example abs(-
24) returns 24.
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 59 of 73
In previous chapters you will have seen the text box used in a number of examples and to
access it you need to specify the form name and the name of the text box for example:
Document.form1.textbox1.value
The following table lists the properties available for a text box.
Property Description
DefaultValue The initial setting of the text box
Enabled Is the text box read only?
Form The name of the form that holds the text box
Name The name of the text box
Size The size of the text box on the screen
Type Text, Password, Hidden
Value The text that is in the text box
Disabled This prevents the text box being changed and
also takes it away from the tab order
The defaultValue and value are different. The value is the text currently occupying the text
box. The defaultValue was the original setting of a text box. This is useful if you want to
compare what used to be in a text box and what is actually there now.
The following table lists the methods available for a text box.
Method Description
Focus() This is an event that occurs when the user
enters the text box
Blur() This is an event that occurs after the user
has left the text box
Select() This highlights all the text in a text box for
copying and pasting
The text and password boxes all have the same properties and methods.
The hidden box only has the name, type and value properties and no methods. It is used to
hold data to send with the form that the user cannot see.
Textareas
In HTML <textarea> tags are used to create a large text box with multiple rows. You can
specify the size of the box using the rows and cols attributes. The cols attribute is similar to
the size attribute of a text box.
The following table lists the properties associated with the text area.
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 60 of 73
Property Description
DefaultValue The initial setting of the text box
Enabled Is the text box read only?
Form The name of the form that holds the text box
Name The name of the text box
Rows The number of rows for the text area
Cols The size of the text area across the screen
Type Text, Password, Hidden
Value The text that is in the text box
Disabled This prevents the text box being changed and
also takes it away from the tab order
The following table lists the methods available for the text area.
Method Description
Focus() This is an event that occurs when the user
enters the text area
Blur() This is an event that occurs after the user
has left the text area
Select() This highlights all the text in a text area for
copying and pasting
Buttons
Buttons can be defined in HTML using the <INPUT TYPE=”button”> tag or by using the
<BUTTON> tag.
Property Description
Enabled Is the button available to press or greyed
out.
Form The name of the form that holds the button.
Name The name of the button
Type Button
Value The text that is written on the button
Disabled This prevents the button being pressed and
also takes it away from the tab order
Method Description
Focus() You can force the button to hold the focus so
that if the user presses the return key the
button is pressed
Click() By using the click method you can simulate
pressing the button.
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 61 of 73
Property Description
Enabled Is the button available to press or greyed
out.
Form The name of the form that holds the button.
Name The name of the button
Type Button
Value The text that is written on the button
Disabled This prevents the button being pressed and
also takes it away from the tab order
Method Description
Focus() You can force the button to hold the focus so
that if the user presses the return key the
button is pressed
Click() By using the click method you can simulate
pressing the button.
Property Description
Enabled Is the button available to press or greyed
out.
Form The name of the form that holds the button.
Name The name of the button
Type Button
Value The text that is written on the button
Disabled This prevents the button being pressed and
also takes it away from the tab order
Method Description
Focus() You can force the button to hold the focus so
that if the user presses the return key the
button is pressed
Click() By using the click method you can simulate
pressing the button.
The Checkbox
The checkbox is used to get a user to decide whether something is true or false for example
would you like to join a newsletter? The checkbox is created in HTML using the <INPUT
TYPE=”checkbox”> tag.
The checkbox is accessed by using its name in the same way as text boxes and buttons for
example:
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 62 of 73
Document.form1.check1.value
Property Description
Enabled Is the checkbox available to press or greyed
out.
Form The name of the form that holds the
checkbox.
Name The name of the checkbox
Type Checkbox
Value The text that is sent if the box is checked
Checked This determines whether the checkbox is
checked or unchecked (true or false)
DefaultChecked This determines the initial state of the
checkbox which is checked or unchecked
(true or false)
Disabled This prevents the checkbox being changed
and also takes it away from the tab order
Method Description
Focus() You can force the checkbox to hold the focus
so that if the user presses the return key the
button is pressed
Click() By using the click method you can simulate
pressing the checkbox to turn it on or off
Radio buttons in a group should all have the same name. They are accessed by using the
radio button’s name and element number for example:
Document.form1.breakfast[0].value
Document.form1.breakfast[1].value
Property Description
Enabled Is the radio button available to press or
greyed out.
Form The name of the form that holds the radio
button
Name The name of the radio button or group of
buttons
Type Radio
Value The text that is sent with the form if the
radio button is checked
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 63 of 73
Method Description
Focus() You can force the radio button to hold the
focus so that if the user presses the return
key the button is pressed
Click() By using the click method you can simulate
pressing the radio button to turn it on or off
Selection Lists
Selections lists come in two forms. The first form is as a drop down list where only one item
can be selected and is used to select an item where radio buttons would take up too much
room. The second form is as a list box that enables multiple selections.
The first list is created using the HTML tag <SELECT > with a number of <OPTION> tags.
The second list is created using the HTML tag <SELECT MULTIPLE> with a number of
<OPTION> tags.
Property Description
Name The name of the select object
Length The number of options in the select list
Size The width of the list on the screen
SelectedIndex The index number of the selected item within
the box
Disabled This prevents the text box being changed and
also takes it away from the tab order
As mentioned before the <SELECT> tag has a number of <OPTION> tags and so the
<OPTION> tag is a sub-object of a select object and can be referenced in the following way.
Document.form1.select1.option[0]
Document.form1.select1.option[1]
Property Description
DefaultSelected This returns the index of the item that is
selected by default in a list
SelectedIndex This identifies which item in the list is
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 64 of 73
currently selected
Selected This can be accessed to determine whether
an item is selected or not
Text This returns the text between the <OPTION>
and </OPTION> tags
Index The index number of the option
Length The length of the object is size
Name The name of the option
Value This is sent with the form if the option is
selected at the time the submit button is
pressed
The option tag has no methods but the select object does have the following methods:
Method Description
Focus() You can force the radio button to hold the
focus so that if the user presses the return
key the button is pressed
Blur() You can force the focus to leave the select
list.
When you press the submit button the data is passed from the form to the place listed in
the action method of the <FORM> tag using the method specified.
The form therefore has properties that can be accessed using JavaScript such as:
Property Description
Action Where the data will be passed. This can be a
script or an email address
Method Get or Post
Target The target window where the form data will
be passed
Elements This enables you to access any item on the
form using the element number in the order
the form was created.
The elements property as mentioned above enables you to access the methods and
properties of all the elements on a form using the index of the element on the form. For
example if you had a form with a text box, a text area and a button then the text box would
be element 0, the text area element 1 and the button element 2 as this is the order they
were created on the form and so could be accessed as follows:
Document.form1.elements[0].value
Document.form1.elements[1].value
Document.form1.elements[2].value
The form also has methods that can be accessed using JavaScript as follows:
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 65 of 73
Method Description
Reset() This simulates the reset button on the form
being pressed
Submit() This simulates the submit button on the form
being pressed
<HTML>
<HEAD>
<TITLE>Example Form</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function validate()
{
var username = document.form1.username.value;
var password = document.form1.pass.value;
var address = document.form1.address.value;
if (username.length < 5)
{
alert("Username must be at least 5 characters");
}
if (password.length < 5)
{
alert("The password must be at least 5 characters");
}
if (address.length < 1)
{
alert("You must enter an address");
}
if (document.form1.newsletter.checked == true)
{
var newsletter = "You have signed up for the newsletter";
}
else
{
var newsletter = "You have not signed up for the
newsletter";
}
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 66 of 73
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="form1">
<TABLE WIDTH=100%>
<TR>
<TD>
Username
</TD>
<TD>
<input type="text" name="username" size=20 maxlength=20>
</TD>
</TR>
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 67 of 73
<TR>
<TD>
Password
</TD>
<TD>
<input type="password" name="pass" size=20 maxlength=20>
</TD>
</TR>
<TR>
<TD>
Address
</TD>
<TD>
<textarea name="address" rows=5 cols=30></textarea>
</TD>
</TR>
<TR>
<TD>
Would you like to join our newsletter?
</TD>
<TD>
<input type="checkbox" name="newsletter" checked=true>
</TD>
</TR>
<TR>
<TD>
Which of these search engines is the best?
</TD>
<TD>
<input type="radio" name="search" checked="yes"
value="Google">Google <input type="radio" name="search"
value="Yahoo">Yahoo <input type="radio" name="search"
value="Lycos">Lycos
</TD>
</TR>
<TR>
<TD>
What is your level of education?
</TD>
<TD>
<SELECT name="education">
<OPTION SELECTED>Uneducated</OPTION>
<OPTION>Completed high school</OPTION>
<OPTION>Completed further education</OPTION>
<OPTION>Absolute scholar</OPTION>
<OPTION>A complete credit to society</OPTION>
</SELECT>
</TD>
</TR>
<TR>
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 68 of 73
<TD>
Which of these things do you like most (you can select more than
1)
</TD>
<TD>
<SELECT MULTIPLE name="pastimes">
<OPTION>Football</OPTION>
<OPTION>Skiing</OPTION>
<OPTION>Basketball</OPTION>
<OPTION>Tennis</OPTION>
<OPTION>Cricket</OPTION>
</SELECT>
</TD>
</TR>
<TR>
<TD COLSPAN="2">
<CENTER>
<INPUT TYPE="submit" value="Validate" onclick="validate()">
<INPUT TYPE="reset" value="Reset">
</TD>
</TR>
</TABLE>
</FORM>
</BODY>
</HTML>
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 69 of 73
The frame object has the following properties frames, onBlur, onFocus, parent, self, top and
window. As well as these properties you can access all the attributes of a frame such as
name and src. There is also a length property which determines how many frames are in
the set.
The frames property is an array of all the frames for example if a frameset had 3 frames
the first frame could be accessed in the following way:
Document.frames[0]
You can also access the frame by its name. If you called a frame “toppane” then you can
use the following:
Document.frames[“toppane”]
Using this notation you can access the details of the page that the frame hold such as the
title.
Parent.toppane.document.title
OR
Parent.frames[“toppane”].document.title
Parent.frames.length
The current frame is called self and so to access the current frame you use:
Self.document.title
If you are in frame1 and want to access an element on frame 2 then you would use:
parent.frame2.document.form1.username.value
Using the above method you could also set values in a different pane.
The frame object has three events onBlur, onFocus and onResize.
You can print the contents of an individual pane by using the following:
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 70 of 73
Parent.frame1.print()
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 71 of 73
The navigator object however is very useful and gives you information such as the user’s
platform.
Here are some of the properties and the method of the navigator object:
Properties
AppCodeName, appName, appVersion, platform, userAgent
Method
JavaEnabled()
The appCodeName property returns the type of browser: This is usually called Mozilla.
The appName returns the actual browser name such as Internet Explorer.The appVersion
returns the version of the browser the user is running such as 5.1.
You can detect which operating system a user is running by checking the platform property.
The userAgent has the same information as the appVersion and appCodeName.
You can do this by running the javaEnabled() method. It returns true or false.
An example
The following is an example to show information about a user’s environment:
<HTML>
<HEAD>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 72 of 73
var namestart=document.cookie.indexOf("=");
</SCRIPT>
</BODY>
</HTML>
Cookies
You have probably seen references to cookies a number of times when using the web and
maybe you have wondered what they are. Obviously they are not the biscuit treat that we
love so much.
They are actually small files that hold the minimum of information necessary. They are
written to the user’s machine and contain information such as user preferences.
The above example asks for your name and writes it to a cookie. That cookie is now held on
your machine and can be accessed any time by using the document.cookie command.
file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 73 of 73
When programming it is good to write comments around code so that you know what it is
doing and so people reading you code know what it is doing. To add comments in
JavaScript the //, /* and */ marks are used.
Comment lines are also used to help find out where code is going wrong.
If you run a script and you get the message errors on page then comment out lines of code
or blocks of code and run it again to see if the error has gone away. This enables you to
determine which lines are causing the errors.
Sometimes you do not get an error but the script does not do what you expect.
In this case the alert() method enables you to display values of fields so that you can see
what is in a variable.
file://C:\newsite\wholejs.html 29/07/2005