Você está na página 1de 73

Newell Web Services Page 1 of 73

file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 2 of 73

The Javascript Tutorial


Introduction
This is the first in a series of javascript tutorials that will teach you the fundamentals of
javascript.

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 and External files


JavaScript can be embedded into your HTML documents or can be placed in an external file
and linked back into the HTML document

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

The Javascript Tutorial


Variables
In this chapter of the javascript tutorial you will learn what variables are, what they do and
how to manipulate the data within them.

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.

So what does a variable look like?

var name = “John Smith”

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

1. Integer - An integer is a whole number such as 1,2,3,4,5,6


2. Floating-point – A floating point is a number with a decimal point in it such as 54.30,
56.20
3. String – A string is a variable that holds character data such as “John Smith”
4. Boolean – A Boolean value is true or false.

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:

var iAge = 29;


var fPrice = 4.50;
var sName = “John Smith”;
var bMale = TRUE

Assigning values to variables


You have already seen one way to assign a value to a variable:

var name = “John Smith”;

At a later stage in your script you may wish to change the value of this variable.

var name=”John Smith”;


Name=”Gregory Jones”;

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:

var age = “21”;


var age = 21;

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:

var age = “21”;


var yourage = 35;
var totalage = 0;
totalage = parseint(age) + yourage;

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

var age = 35;


var ageasstring = “”;
ageasstring = age.toString();

Arrays

An array is probably termed best as a group of variables all with the same name.

Look at the following code:

var Jan = “January”;


var Feb = “February”;
var Mar = “March”;
var Apr = “April”;
var May = “May”;
var June = “June”;
var July = “July”;
var Aug = “August”;
var Sep = “September”;
var Oct = “October”;
var Nov = “November”;
var Dec = “December”;
document.write(jan + “ “);
document.write(feb + “ “);
document.write(mar + “ “);
document.write(apr + “ “);
document.write(may + “ “);
document.write(june + “ “);
document.write(july + “ “);
document.write(aug + “ “);
document.write(sep + “ “);
document.write(oct + “ “);
document.write(nov + “ “);
document.write(dec + “ “);

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.

var johnsnumber = “0192948384”;


var katesnumber = “0493954856”;

If you have hundreds of friends that would take a lot of effort to display them all using
document.write statements.

That is where arrays come in.

file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 7 of 73

Look at the following:

var months = new Array


(“January”,”February”,”March”,”April”,”May”,”June”,”July”,”August”,”September

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.

You can also declare an array in the following way:

VAR months = new Array(12);

You access each element of the array in the following way.

var months = new Array(12);


months[0] = “January”;
months[1] = “February”;
months[2] = “March”;
months[3] = April”;
months[4] = “May”;
etc

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?

var months = new Array


(“January”,”February”,”March”,”April”,”May”,”June”,”July”,”August”,”September
document.write(months[0] + “ “);
document.write(months[1] + “ “);
document.write(months[2] + “ “);
document.write(months[3] + “ “);
document.write(months[4] + “ “);
document.write(months[5] + “ “);
document.write(months[6] + “ “);
document.write(months[7] + “ “);
document.write(months[8] + “ “);
document.write(months[9] + “ “);
document.write(months[10] + “ “);
document.write(months[11] + “ “);

I know what your thinking. Its not saved much effort has it.

Now look at the example below.

var months = new Array


("January","February","March","April","May","June","July","August","September","Oct
var idx = 0;

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.

Imagine that the array looks something like this:

var names = new Array(“Jim”,”Alison”,”Paul”,”Steve”,”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.

To do this you use the sort property.

var names = new Array(“Jim”,”Alison”,”Paul”,”Steve”,”Barney”);


var str1 = names.sort();
document.write(str1);

file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 9 of 73

The Javascript Tutorial


Arithmetic
Ok it’s the dreaded maths lesson time. Actually its not that bad. I’m sure if you have come
this far you can handle some basic addition and subtraction.

Arithmetic obviously only works with numerical variables.

var age1 = “24”;


var age2 = “35”;
var age3 = age1 + age2;

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.

Ok lets try another one.

var age1 = 24;


var age2 = “35”;
var age3 = age1 + age2;

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:

var age1 = 24;


var age2 = 35;
var age3 = age1 + age2;

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.

var age1 = 34;


var age2 = 59;
var age3 = age1 + age2;
var age4 = age2 – age1;
var age5 = age1 * age2;
var age6 = age1 / 2;

The above example shows all four arithmetic operators +, -, * and /.

Age 3 = Age 1 + Age 2 expands to 93 = 34 + 59.


Age 4 = Age 2 – Age 1 expands to 25 = 59 – 34.
Age 5 = Age 1 * Age 2 expands to 2006 = 34 * 59;
Age 6 = Age 1 / Age 2 expands to 17 = 34 / 2.

file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 10 of 73

Incrementing and decrementing variables


There are a number of times in programming when variables are used as indexes and
therefore need to go or down 1 at a time.

You could do this in the following way:

var age1 = 24;


age1 = age1 + 1;
age1 = age1 – 1;

The above would add 1 to age1 and then subtract 1 from age1.

There is a shorter way of achieving this as follows:

var age1 = 24;


age1++;
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

The Javascript Tutorial


Conditions

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?

In programming conditions are used to change the flow of a program.

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

In the example above num is set to 74.

There is a form with a place to enter a number.

file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 12 of 73

The user enters a number and presses enter.

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.

Depending on the number the user enters a different message is shown.

Lets take a closer look at the IF statement.

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 comparison operators


In the last section you saw how to build up an IF statement. The only part of the IF
statement not discussed were the use of the ==, < and the >.

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

The statement if (A < B) translates in English to IF A is smaller than B.

The statement if (A > B) translates in English to IF A is greater than B.

The statement if (A >= B) translates in English to IF A is greater or equal to B.

The statement if (A <= B) translates in English to IF A is less than or equal to B.

The statement if (A = B) translates to ?

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

Look at the following code:

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.

Look at the following table:

Operator Description
&& And
|| OR

How can you tell if a variable contains a numerical


value?
In the example at the beginning of this chapter the user is asked to enter a number but
what happens if he or she does not enter a number.

No message actually gets displayed.

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

There are two types of loop:

 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>

So how does it work?

First of all the for loop has the following structure:

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.

Lets look closer at the statement: idx=0;idx<15;idx++

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.

The while loop


The while loop could quite easily be used to do the same as the for loop as the following
code shows:

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

Lets analyse the above code.

The structure of a while loop is as follows:

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

Breaking out of loops


The above example was ok but what happens if the user is bored of trying to guess the
number.

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.

The continue statement


When running a loop a continue statement is used to skip the current pass through. The
following example prints out all the people whose age is over 65.

<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

The Javascript Tutorial


Functions
We have already looked at a number of functions already in this tutorial and you probably
haven’t realised it.

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.

Using functions it is possible to perform sections over and over.

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

A function is declared as follows:

Function functionname(arguments) { statements }

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.

The following is an example of an age checking function.

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

The function is called using checkage(age).

If no parameter was sent the script would have an error.

Global and Local Variables


You should by now totally understand what a variable is.

var age = 18;


var name=”Sarah”;

This section deals with global variables and local variables.

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

var age = prompt("Enter your age",0);


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>

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.

This is a very important thing to remember.

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.

Confused? Myage has been declared twice now hasn’t it.

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.

Functions and Hyperlinks


It is possible to get a hyperlink to run a JavaScript function by placing the text javascript: in
the HREF section.

<A HREF="javascript:seewizzy();">See a picture of WizzyPig</A>

file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 23 of 73

The Javascript Tutorial


Timers
Timers are used to make things happen on a web page at certain intervals.

The following example waits 5 seconds before displaying a picture of a crab.

<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 key to the timer is the window.setTimeout function highlighted in bold.

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.

The boo function just displays an image of a crab.

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

In this chapter you will learn about events.

Events are things that happen and can be triggered by the following occurrences:

 The mouse button is clicked, double-clicked or the mouse is moved.


 Somebody presses a key on the keyboard
 Somebody clicks inside a list box, a text box etc
 A page is loaded or someone presses submit or reset.

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.

Trapping mouse events


The title would suggest something rentokill would normally be called in for but it is in fact
about trapping what the user does with the mouse.

The following is an example of testing when a user clicks the mouse.

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

<div id="test" style="background: yellow" onclick="mclick()">

As well as a single click a double click can also be trapped as follows:

<div id="test" style="background: yellow" ondblclick="mclick()">

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

Detecting keyboard events


The keyboard event can be used to trap key presses.

A keypress occurs when a user presses a key.

A keydown event occurs when a user holds a key down.

A keyup event occurs when a user releases a key.

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.

First of all I have created the function:

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.

Give up? Press the "B" key.

This was achieved by testing the windows.event.keyCode. The windows.event.keyCode is a


numerical value that holds the value of which key was pressed.

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.

Therefore to achieve the effect above I used the following code.

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)">

Onfocus and Onblur


An onfocus event occurs when an element is clicked on or tabbed to. It is mainly used for
form controls.

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>

You get the following:

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.

The onchange event


The onchange event can be used to call a function when the value of a form changes.

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;
}

Then call the onchange event from the <select> tag:

file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 29 of 73

<form name="form5" method="post" action="">


<select name="select" onchange="changecol(this.form)">
<option>white</option>
<option>blue</option>
<option>red</option>
<option>cyan</option>
<option>green</option>
</select>
</form>

Onload and onunload


At the very beginning of this chapter you were shown an example that loaded a popup box
when the user left the page.

When a web page is first loaded it triggers the onload event and when the page is left it
triggers an onunload event.

Onerror and Onabort


There may be a time when a visitor to your site emails you and says “This function just
does not work”.

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 Javascript Tutorial


The document object model
The title of this chapter may seem fairly technical. This chapter will teach you all about
documents, windows and properties.

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.

Every single object, subobject and attribute can be accessed by JavaScript.

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.

To change the document title you can use:

document.title = "new title";

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

A checkbox is a subobject of a form therefore to access a checkbox you have to use:

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.

To create your own object you use the new keyword.

Var mydate = new date();

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.

The function accepts var1 as a parameter. Var1 is placed into welcomeObject.name.

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.

The current object (this)


You may have noticed in some of the examples the use of the word this. This stands for the
current object and is commonly used when accessing forms within functions as the following
example shows:

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

name on it and displays hello and the value of name.

The actual form code is as follows:

<form name="form1" method="post" action="">


Enter your name
<input type="text" name="name">
<input type="button" name="Button" value="click here"
onclick="hello(this.form)">
</form>

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 Javascript Tutorial


The Array Object
In an earlier chapter you learned how to create arrays. An array is a type of object.

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

The Javascript Tutorial


The Image Object
Images are stored in a document as part of an array of images. So you place an image onto
your HTML page it takes up position 0 in the array images. If you place another image on
the page then it takes up position 1 etc.

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.

To preload an image you create a new version of the image object.

<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

alert(“the picture is loaded”);


}

file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 38 of 73

The Javascript Tutorial


The Link Object
In the HTML tutorial there was a chapter about links and bookmarks. The bookmark is also
referred to as an anchor.

1. Bookmark/Anchor - <A NAME=?anchor1?>


2. Link - <A HREF=#anchor1>Anchor1</A>

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”)

The following is a list of properties available for links:

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

The JavaScript Tutorial


The History Object
When you visit websites it is held as history so that you can easily recall the pages you
have recently looked at. In JavaScript this is called the history object and you can access
the history object to find out where the user who is viewing your page has been previously.

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

The JavaScript Tutorial


Windows and Documents
You saw previously a diagram that showed that the top level object is a window and each
window has document, location and history objects. Each of these objects has sub-objects
such as images, links and arrays.

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.

It accepts text and html to display information to the screen as follows:

The document.write() method writes directly to the window and to add new lines you have
to use the tag
.

document.write("hello world")

Amending the status bar


At the bottom of the browser window you will see a status bar.

You can change the text on the status bar using the window.status property as follows:

<BODY onload="window.status='Welcome to the JavaScript


Tutorial'">

Changing the background colour


You have seen how to do this before using document.body.style.background= but there is a
quicker way as follows:

<BODY onload="document.bgColor='blue'" TEXT="WHITE">

Changing the text colour


As well as changing the background colour you can change the text colour.

<BODY onload="document.fgColor='blue'">

Changing link colours


The link colours can also be accessed and changed using JavaScript.

<BODY onload="document.linkColor='blue'" TEXT="WHITE">

file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 41 of 73

<A HREF="http://www.newellwebservices.com">The link is


blue</A>

You can change the visited link and active link using document.alinkColor or
document.vlinkColor etc.

Changing Page Titles


I have explained before how to change the page title but as it is part of the window here it
is again.

<BODY onload="document.title='Chapter 17'">

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:

document.write("This page was last modified on " +


document.lastModified);

The date can be formatted in various ways which will be covered in a later chapter.

Displaying the current web page address (URL)


Have you ever downloaded a page from the net and then needed to access the site again to
view more pages but do not know the address of the site. It can be very frustrating.

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.

Instead there is the document.URL property available.

document.write("<BR><A HREF='" + document.URL + "'>" +


document.URL + "</a>");

The referring page


When you click a link on a page you are sent to another page or bookmark. When you get
to the next page the first page is called the referring page and you can access this page
using document.referrer.

This is useful if you want a link back to the original page.

document.write("<BR><A HREF='" + document.referrer + "'>" +


document.referrer + "</a>");

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.

The window.open() method has 3 parameters.

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.

<a href="Close previous window" onclick="window1.close()">

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.

<a href="#move" onclick="openwindow()">Click to open the


window</a>
<a href="#move" onclick="movewindow()">Then click here to
move it</a>

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.

<a href=# onclick="window1.resizeTo(500,500)">Resize window


to 500 by 500</A>
<a href=# onclick="window1.resizeBy(100,100)">Make window
100x100 pixels bigger</A>

Alerts
There have been a few examples in this tutorial of alerts appearing on the screen.

An alert is a little message box that appears 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.

Maybe you wish to ask a user for their name as follows:

name = prompt("Enter your name","George");


document.write("How are you doing " + name + "?");

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.

Confirm dialog box


The alert dialog box is used to place a message on the screen. The prompt dialog box asks
the user to enter information.

The confirm dialog box is used to display a message with a yes/no answer.

likesblue = confirm("Do you like the colour Blue?");


if (likesblue == true)
{
document.bgColor = “blue”;

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

The JavaScript Tutorial


The String Object
At the very beginning of the tutorial you were shown what variables are and very loosely
you were shown how to create a string.

Var name = “Gary”;

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.

String and SubStr


Imagine you have a long string of text and you want to find out how many occurrences of
the word and there are.

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

The following example shows various methods of concatenating strings.

var txt = "This is string 1 ";


var txt2 = "and this is string 2 "

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);

Formatting text within strings


The following example shows all the ways in which text can be formatted such as bold,
italics, font sizes etc.

var txt = "This is a string";


document.write(txt.bold() + "<BR>");
document.write(txt.italics() + "<BR>");
document.write(txt.sup() + "<BR>");
document.write(txt.sub() + "<BR>");
document.write(txt.fontsize(6) + "<BR>");
document.write(txt.fontcolor("Blue") + "<BR>");
document.write(txt.toUpperCase());

Turning strings into anchors and links


Any text string can be changed to become an anchor (bookmark) or link.

var txt = "Click here for the Newell Web Services website";
document.write(txt.link("http://www.newellwebservices.com"));

How long is a string


As mentioned earlier there is only one parameter associated with a string object which is
length.

This determines the length of the string and so:

var name = “This is a JavaScript Tutorial”;


var lth = name.length;
document.write(“The length is “ + lth);

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());

Search and Replace

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.

var str = "This is a Newell Web Services Tutorial";


var ind = str.search("Services");
document.write(ind);

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.

The following example shows how to split a string.

var str1 = "Gary Susan Nadine Marjorie Harry Bob";


document.write(str1 + "
");
str1Array = str1.split(" ");
for (var ind=0;ind {
document.write(str1Array[ind] + "
");
}

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

The JavaScript Tutorial


The Date Object
A date is not part of a web page. You cannot use a tag to display a date and yet it is part of
the default JavaScript syntax.

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:

CDate = new Date();

The date can accept 3 definitions which determine how the date is formatted:

Cdate = new Date(“month day, year hours:minutes:seconds”;


Cdate = new Date(“year, month, day”);
Cdate = new Date(“year,month,day,hours,minutes,seconds”)

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

getDay() This returns the number of the day of the


week for example 1 is Monday, 2 is Tuesday
etc
getMonth() This returns the month of the year.
Remember 0 is January, 1 is February etc
getYear() This returns a 2 year number representing
the current year for example 96 is 1996.
getHours() This returns the hour of the date in 24 hour
format.
getMinutes() This returns the number of minutes.
getSeconds() This returns the number of seconds
setDate() This sets the day of the month between 1
and 31
setMonth() This sets the month of the year between 0
and 11.
setYear() This accepts a 2 digit year and sets the year
of the date
setHours() This sets the hour of the date.
setMinutes() This sets the minutes of the date.
setSeconds() This sets the seconds of the date.
getTime() This gets the number of milliseconds that
have passed since January 1, 1970
setTime() This sets the number of milliseconds that
have passed since January 1, 1970
parse() The parse method accepts a month, day and
year and returns the number of milliseconds
between January 1, 1970 and that date.
getTimezoneOffset() Returns the number of minutes between GMT
and the local time zone.

Displaying the current date and time using Greenwich


Mean Time
The toGMTString() function returns the current Greenwich Mean Date and Time. The
Greenwich Mean Date and Time is the date that all other clocks are set. So if you are said
to be 4 hours ahead then you are 4 hours ahead of Greenwich Mean Time.

date1 = new Date();


document.write("The date and time is " + date1.toGMTString());

Display the local date and time


More useful to your page viewers is the use of the local date and time.

To display the local date and time use the toLocaleString() function:

date1 = new Date();


document.write("The date and time is " + date1.toLocaleString());

Getting the date and time


There are various functions that enable you to interrogate each part of the date and time.

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.

The following is an example of a simple clock:

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

var cSeconds = cTime.getSeconds();


var mindisplay = "";
var secdisplay = "";
var hourdisplay = "";
if (cMinutes < 10)
{
mindisplay = "0" + cMinutes;
}
else
{
mindisplay = cMinutes;
}
if (cSeconds < 10)
{
secdisplay = "0" + cSeconds;
}
else
{
secdisplay = cSeconds;
}
if (cHours < 10)
{
hourdisplay = "0" + cHours;
}
else
{
hourdisplay = cHours;
}
document.form1.clock.value = hourdisplay + ":" + mindisplay + ":"
+ secdisplay;
setTimeout("startclock()",1000);
}

You need to add this form to your section

<form name="form1"> <br> <input type="text" size=8


name="clock"> <br> </form>

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.

Setting the date and time


Earlier on in this section you saw how to set up the date using three different formats. It
may become necessary to set up the date after you have created it. The setDate(),
setMonth(), setYear(), setHours, setMinutes and setSeconds methods enable you to have
full control over the setting of dates.

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

cDate = new Date();


cDate.setDate(13);
cDate.setMonth(09);
cDate.setYear(2004);
cDate.setHours(14);
cDate.setMinutes(00);
cDate.setSeconds(00);
document.write("I must remember my anniversary, it is on the " +
cDate);

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.

The getTime(), setTime() and parse() methods


These two functions are very curious. The getTime function returns the number of
milliseconds since January 1, 1970 and the setTime function sets the number of
milliseconds since January 1, 1970. The parse() method accepts a date in one of the three
standard formats and returns the number of milliseconds since January 1, 1970.

cDate = new Date();


document.write("There have been " + cDate.getTime() + "
milliseconds since January 1, 1970
");
cDate.setTime(4000);
document.write("Now there have only been " + cDate.getTime() +
" milliseconds since January 1, 1970");

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:

cDate = new Date();


document.write("You are " + cDate.getTimeZoneOffset() + "
minutes away from GMT");

file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 55 of 73

The JavaScript Tutorial


The Maths Object
Yawn Yawn I here you cry. Do we have to?

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);

Note that the number 40 is non-inclusive so it is actually a number between 0 and


39.999999999. The above example is ok but the number still has a decimal point and for
our guessing game it would be a bit hard to expect someone to guess a number with a
decimal point for example 39.454554.

This is where the floor function comes in. The floor function removes all the digits after the
decimal point and so:

rannum = Math.floor(Math.random() * 101) + 1;

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.

<H2>For a right angle triangle</H2>


<form name="form1">
Opposite side: <input type="text" name="opp"
onchange="document.form1.sin.value=document.form1.opp.value/document.form1.
document.form1.tan.value=document.form1.opp.value/document.form1.adj.value">

Adjacent side: <input type="text" name="adj"


onchange="document.form1.cos.value=document.form1.adj.value/document.form1.h
document.form1.tan.value=document.form1.opp.value/document.form1.adj.value">

Hypotenuse side: <input type="text" name="hyp"


onchange="document.form1.sin.value=document.form1.opp.value/document.form1.
document.form1.cos.value=document.form1.adj.value/document.form1.hyp.value">
<BR>
<HR>
Sine: <input type="text" name="sin">
<BR>
Cosine: <input type="text" name="cos">
<BR>
Tangent: <input type="text" name="tan">
</form>

file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 57 of 73

For a right angle triangle


The above example enables you to enter a value into any of the opposite, adjacent or
hypotenuse fields and it will return the angular value in radians.

Logarithmic and Exponential functions


Javascript includes two functions for working with natural logarithms and exponentials based
on Euler’s constant.

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>

Minimum and Maximum values


<>The min() function accepts two numbers and returns the smallest of the two numbers.

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

The JavaScript Tutorial


Forms
This chapter deals with accessing form values and methods.

Text Boxes, Hidden Text Boxes and Passwords


The text box has a number of attributes defined in HTML using the <input> tag and setting
the type to text.

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.

The following table lists the properties available for a 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

The following table lists the methods available for a button:

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 Reset Button


The reset button is a special button that sets all the values of the other elements on a form
to their default value. The reset button is set up using the <INPUT TYPE=”Reset”> tag.

The reset button has the following properties:

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

The reset button has the following methods:

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 Submit Button


The submit button is a special button that when pressed will call the URL specified in the
action part of the <FORM> tag. The submit button is created using the <INPUT
TYPE=”submit”> tag.

The submit button has the following properties:

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

The submit button has the following methods:

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

The following properties are available for a checkbox:

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

The checkbox has the following methods:

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

The Radio Button


Radio buttons are used to get a user to pick an option for example what do you want for
breakfast, Eggs, Toast or Cereal? The radio button is created in HTML using the <INPUT
TYPE=”radio”> tag.

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

The following properties are available for a radio button:

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

Checked This determines whether the button is


checked or unchecked (yes or no)
DefaultChecked This determines the initial state of the radio
button which is checked or unchecked (yes or
no). Only one radio button in a group can be
checked
Length This returns the number of radio buttons in
the group
Disabled This prevents the radio button being changed
and also takes it away from the tab order

The radio button has 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
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.

The select object has the following properties:

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]

The <OPTION> tags have the following properties:

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.

Resetting and submitting forms


When you press the reset button the form will return the form to all of its original settings.

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

An example using forms


This whole chapter has been created with no physical examples and that is because it is
easier to show an example all in one.

The following example validates the input of a form:

<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

var searchengine = "";


for (var ind=0;ind<document.form1.search.length;ind++)
{
if (document.form1.search[ind].checked == true)
{
searchengine = document.form1.search[ind].value;
}

var education = document.form1.education.options


[document.form1.education.selectedIndex].text;
var pastimes = "";
for (ind=0;ind<document.form1.pastimes.length;ind++)
{
if (document.form1.pastimes.options[ind].selected ==
true)
{
pastimes = pastimes + " " +
document.form1.pastimes.options[ind].text;
}
}

document.write("<H1>Here is the information you


entered</H1>");
document.write("Your name is: " + username + "<br>");
document.write("You password is: " + password + "<br>");
document.write("You live at: " + address + "<br>");
document.write(newsletter + "<br>");
document.write("Your favourite search engine is: " +
searchengine + "<br>");
document.write("You were educated to " + education + "
standard<br>");
document.write("Your favourite pastimes are " + pastimes);

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

The focus and blur events


When an item receives the focus an onfocus event is raised and when the focus leaves an
item the onblur event is raised. The onfocus event can be accessed for all elements on a
form but the onblur only occurs for select, option, text, password and textarea.

file://C:\newsite\wholejs.html 29/07/2005
Newell Web Services Page 69 of 73

The JavaScript Tutorial


Frames
This chapter looks at how JavaScript can be used to access different frames. If you have
studied the HTML tutorial then you will know that frames are used to display different HTML
pages on the same screen.

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

To find out how many frames are in a set use:

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 JavaScript Tutorial


The Navigator Object
The last chapter about frames was very brief because frames are cumbersome objects that
not everyone can access and so I did not want to dwell on them too much.

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()

Detect the User's Browser


You can use the navigator object to find out which browser a user is running. This is useful
when running scripts so that you know if an option is not available for a particular browser
you can code around it.

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.

Is the browser Java Enabled?


Java is used on the web to program applications that work with the browser. If Java is not
enabled then the application will not run. Therefore before attempting to run an application
it is good to check whether the user has java disabled or not so you can tell them to turn it
on.

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 name=prompt("Enter your name");


document.cookie = "Name=" + name + ";";

var namestart=document.cookie.indexOf("=");

document.write("Your name is : " + document.cookie.substring


(namestart + 1,document.cookie.length) + "<br>");

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

To create a cookie you use the document.cookie object

var name=prompt("Enter your name");


document.cookie = "Name=" + name + ";";
var namestart=document.cookie.indexOf("=");
document.write("Your name is : " + document.cookie.substring
(namestart + 1,document.cookie.length) + "<br>");

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

The JavaScript Tutorial


Comments

Errors and Comments


Thus far all the commands that you have learned make the user’s browser do something.

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.

The // comments out a single line.

The /* and */ comment out a block.

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.

© 2005 - Newell Web Services

file://C:\newsite\wholejs.html 29/07/2005

Você também pode gostar