Anda di halaman 1dari 22


Welcome To
JavaScript for the Total Non-Programmer
This tutorial will take you step by step through the fundamentals of Javascript. You will learn how
to write functions, use data from text boxes, create IF-THEN conditionals, program loops, and
generally make your web page "smarter."
I teach computer classes for a living to corporate clients of all levels. After 2 years of teaching, I
have learned a lot about communication between people of various levels of computer
experience. This tutorial assumes that you have no prior programming experience, but that you
have created your own HTML pages.
If you find this tutorial helpful, please let me know (it's my only reward). Also, links are graciously
What is JavaScript?
Javascript is an easy-to-use programming language that can be embedded in the header of your
web pages. It can enhance the dynamics and interactive features of your page by allowing you to
perform calculations, check forms, write interactive games, add special effects, customize
graphics selections, create security passwords and more.
What's the difference between JavaScript and Java?
Actually, the 2 languages have almost nothing in common except for the name. Although Java is
technically an interpreted programming language, it is coded in a similar fashion to C++, with
separate header and class files, compiled together prior to execution. It is powerful enough to
write major applications and insert them in a web page as a special object called an "applet."
Java has been generating a lot of excitment because of its unique ability to run the same program
on IBM, Mac, and Unix computers. Java is not considered an easy-to-use language for non-
Javascript is much simpler to use than Java. With Javascript, if I want check a form for errors, I
just type an if-then statement at the top of my page. No compiling, no applets, just a simple
What is Object Oriented Programming?
Everyone that wants to program JavaScript should at least try reading the following section. If you
have trouble understanding it, don't worry. The best way to learn JavaScript is from the examples
presented in this tutorial. After you have been through the lessons, come back to this page and
read it again.
OOP is a programming technique (note: not a language structure - you don't even need an
object-oriented language to program in an object-oriented fashion) designed to simplify
complicated programming concepts. In essence, object-oriented programming revolves around
the idea of user- and system-defined chunks of data, and controlled means of accessing and
modifying those chunks.
Object-oriented programming consists of Objects, Methods and Properties. An object is basically
a black box which stores some information. It may have a way for you to read that information
and a way for you to write to, or change, that information. It may also have other less obvious
ways of interacting with the information.
Some of the information in the object may actually be directly accessible; other information may
require you to use a method to access it - perhaps because the way the information is stored
internally is of no use to you, or because only certain things can be written into that information
space and the object needs to check that you're not going outside those limits.
The directly accessible bits of information in the object are its properties. The difference between
data accessed via properties and data accessed via methods is that with properties, you see
exactly what you're doing to the object; with methods, unless you created the object yourself, you
just see the effects of what you're doing.
Other Javascript pages you read will probably refer frequently to objects, events, methods, and
properties. This tutorial will teach by example, without focusing too heavily on OOP vocabulary.
However, you will need a basic understanding of these terms to use other JavaScript references.
Objects and Properties
Your web page document is an object. Any table, form, button, image, or link on your page is also
an object. Each object has certain properties (information about the object). For example, the
background color of your document is written document.bgcolor. You would change the color of
your page to red by writing the line: document.bgcolor="red"
The contents (or value) of a textbox named "password" in a form named "entryform" is
Most objects have a certain collection of things that they can do. Different objects can do different
things, just as a door can open and close, while a light can turn on and off. A new document is
opened with the method You can write "Hello World" into a document by
typing document.write("Hello World") . open() and write() are both methods of the object:
Events are how we trigger our functions to run. The easiest example is a button, whose definition
includes the words onClick="run_my_function()". The onClick event, as its name implies, will
run the function when the user clicks on the button. Other events include OnMouseOver,
OnMouseOut, OnFocus, OnBlur, OnLoad, and OnUnload.

Chapter 1, The Message Box

This is a very simple script. It opens up an alert message box which displays whatever is typed in
the form box below.
Type something in the box. Then click "Show Me"


Here's the entire page, minus my comments. Take a few minutes to learn as much as you can
from this, then I'll break it down into smaller pieces.
<!-- Beginning of JavaScript -
function MsgBox (textstring) {
alert (textstring) }
// - End of JavaScript - -->

<INPUT NAME="text1" TYPE=Text>
<INPUT NAME="submit" TYPE=Button VALUE="Show Me" onClick="MsgBox(form.text1.value)">

First of all, remember that your HTML page is divided into 2 segments, the HEAD and the BODY.
You set up your page this way:
(Stuff about your page in general such as the title.)

(The actual contents of your page.)
In the <HEAD> area, a new pair of tags has been introduced: <SCRIPT> and </SCRIPT>
All browsers currently assume you are programming in JavaScript, but other programming
languages might come along in the future. As a result, it is standard form to open your scripting
area with:
The <!-- and --> tags are used to hide comments in HTML from the browser. Old browsers will not
understand the <SCRIPT> tags, so you need to include the comment tags to keep your
JavaScript from showing up on the Browser.
This is the standard open and close to the JavaScript section of your page.

< !-- Beginning of JavaScript -
(all of your JavaScript functions)
// - End of JavaScript - -->

You can name your functions anything you want. I chose to name mine MsgBox, but I could have
named it Kalamazu or something else.
A function is typed like this:
function MyFunction (variable) {
(stuff you want to do with the variable)
This animation shows how a number can be passed to the variable "data" and then used in a
function written for that variable.
The variable can be a number, a piece of text, or a date.
The curly brackets { } define the beginning and end of the function.
The alert command will create an message box displaying a piece of text or a number.
Alert("Hello World") will display Hello World in the box.
Alert(SomeText) will assume that SomeText is a variable, and will display whatever value it
contains. Notice that "Hello World" was in quotes and SomeText was not. If I put these two lines
SomeText="My Three Sons"
then My Three Sons will be displayed in the message box.

< !-- Beginning of JavaScript -
function MsgBox (textstring) {
alert (textstring) }
// - End of JavaScript - -->

The Form is a JavaScript user's best friend. Forms can be used to input text, to display results,
and to trigger JavaScript functions. The form in our example used 2 objects, a text box, and a

All forms start with the tag <FORM> and end with </FORM>.
The text box should include a NAME and a TYPE
The NAME will be used when we need to tell the function which box has the text we want.
TYPE is how the browser knows to create a text box, button, or check box.
For example:
<INPUT NAME="text1" TYPE=Text>
The button is how we tell JavaScript to run a particular function. The button should include a
The NAME could be used to refer to the button in JavaScript, but is usually not important.
The VALUE is the label which will appear inside the button.
The ONCLICK is followed by the name of a function, and the name of the text box containing the
For example:
<INPUT NAME="submit" TYPE=Button VALUE="Show Me" onClick="MsgBox(form.text1.value)">
<INPUT NAME="text1" TYPE=Text>
<INPUT NAME="submit" TYPE=Button VALUE="Show Me" onClick="MsgBox(form.text1.value)">

We ended the description of the form button with:

This means when the user clicks on this button, the program should run the MsgB ox function
from the top of the page, and use the value of the form object named text1 as its variable.
OK, there are 2 objects in the form, a text box and a button, right? Each object has a name, and
the text box is named text1. The text box's full name is form.text1. The number of characters
typed in the box is called form.text1.length. The value, or string of text that was typed is called
If this is getting too jargon-ish for you, just remember that you end your "submit" button with
onClick=function(form.textboxname.value) where function and textboxname will be
That's it! The value of text1 gets passed to the MsgBox function; the MsgBox function passes it to
the Alert command; and the alert command displays your text for all to see!
Show me how to do it
Here is a look at the script. See if you can trace how it works.
<!-- Beginning of JavaScript -
function changecolor(code) {
// - End of JavaScript - -->
<input type="button" name="Button1" value="RED" onclick="changecolor('red')">
<input type="button" name="Button2" value="GREEN" onclick="changecolor('green')">
<input type="button" name="Button3" value="BLUE" onclick="changecolor('blue')">
<input type="button" name="Button4" value="WHITE" onclick="changecolor('white')">
Explain how it works
function changecolor(code) {
This page is an excellent example of one function being used by several buttons in the same
document. Our function is called changecolor(code). It has only one line:
You probably guessed that bgColor stands for background color.
If I type document.bgColor="red" the background will turn red.
By writing the command document.bgColor=code I am allowing myself to define the variable
code as any color I want.
Later, in the form. I define a button with the command:
onClick="changecolor('green')" is telling the program 2 things:

1. Run the funtion named changecolor(code).

2. code='green'

The if-then statement.
OK, once again, here is the entire code. Give it a look, then we'll break it down.
This is a good example of an If-Then statement. Password scripts can also be
combined with an encryption function so that hackers can't break in simply by
viewing your source code. The purpose of this chapter, however, is to give you
some practice with if-then statements.
<TITLE>Chapter 3, If-then statements</TITLE>
<!-- Beginning of JavaScript -
function password() {
Ret = prompt('Type the word castle',"");
if(Ret=="castle") {
location = 'ch03_1.htm';
} else {
alert("Please try again")
// - End of JavaScript - -->
<A HREF="javascript:password()">
<IMG SRC="pict1.gif" NAME="pic1" ALT="about us!" BORDER="0"
<H3>Click the image to enter a password protected document. Try a wrong entry

function password() {
Ret = prompt('Type the word castle',"");
if(Ret=="castle") {
location = 'ch03_1.html';
The prompt
The first line of the function, password() is:
Ret = prompt('Type the word castle',"");
This command tells the computer to open a prompt box, and assign whatever the
user types to the variable, Ret. Therefore if the user types "chickensoup", the
computer will execute the command
I can then compare the variable Ret with other text to determine if the user typed
in the correct password.
The parentheses contain the message inside the prompt box, then the default
text. Look at this sample command, then click the show me button
prompt("Please type your name","Newt")
If you do not want a default, simply place 2 quotes after the comma like I did in
the original example.
if(Ret=="castle") {
location = 'ch03_1.html';
} else {
alert("Please try again")
The if-then statement
The second line of the function is an if-then statement. It tells the computer that if
the variable Ret equals "castle" then change the URL location to ch03_1.html.
Otherwise, show the alert box which says "Please try again."
Here is the format of an if-then statement:
IF (a comparison)
{ sequence if the comparison is true }

ELSE { sequence is the comparison is false }

For example, let's say you've just had the reader complete a form which included
their age. You want all Senior Citizens to get one message, and everyone else to
get another when they submit the form.
transfer the contents of the age box on the form to a
variable called age.
The if statement begins with the question in
if (age>=65)
{alert("Your form has been
The alert box will be displayed if the question is
submitted. Ask about our Senior
true, age IS greater or equal to 65
Discounts") }
The alert box command following the word ELSE
ELSE {alert("Your form has been
will only be displayed if the question is false, and
submitted.") }
age IS NOT greater or equal to 65.
The following is an example of the simple 'alphabet code.' Each letter in your word is offset by 1
letter, so that 'A' becomes 'B' and 'B' becomes 'C' etc. Try entering HAL, the computer from 2001.
Type your word

Show me how it's done

OK, once again. Here is the script for
you to look over before we go through it together.
<!-- Beginning of JavaScript -
function encode(text) { Ref="0123456789abcdefghijklmnopqrstuvwxyz.-
for (Count=0; Count<text.length; Count++) {
Char=text.substring (Count, Count+1);
Num=Ref.indexOf (Char);
EncodeChar=Ref.substring(Num+1, Num+2)
Result += EncodeChar
// - End of JavaScript - -->
<BODY bgcolor="beige">

<FORM name="form1">
<table border=0><tr><td>
Type your word<td><INPUT NAME="input" TYPE=Text><br><td>
<INPUT TYPE=Button VALUE="submit" onClick="encode(this.form.input.value)"><tr><td>
Result:<td><INPUT NAME="result" TYPE=Text>

function encode(text) { Ref="0123456789abcdefghijklmnopqrstuvwxyz.-

for (Count=0; Count<text.length; Count++) {
Char=text.substring (Count, Count+1);
Num=Ref.indexOf (Char);
EncodeChar=Ref.substring(Num+1, Num+2)
Result += EncodeChar
First we defined a variable to contain every letter and number
is just a variable named Ref which contains a very long sting of text, every possible letter or
number. The purpose of the Ref variable is to convert letters to numbers based on their position
withi n Ref. It can also be used to convert numbers back to text by locating the letter at a certain
position inside Ref.
For example, in the English alphabet, I could easily create a code such that A=1 and B=2
because A is the first letter, and B is the second. Ref allows me to create the same code, but it
includes all possible leters and number s. The letter 'a' returns a value of 10 because it is the 10th
letter in from the left. (Actually it's the eleventh, but JavaScript begins counting with zero just to
keep us on our toes).
Later we will use the command Num=Ref.indexOf(Char) to locate the letter Char inside Ref and
assign its position (how many places in) to the variable Num We'll discuss the indexOf property
in more detail later.
The second line of the function, Result="" is sometimes called "priming" a variable. This
statement establishes that a variable called Result does exist, and that it can contain text, but
does not conatin any right now. Later, I will tack letters on to the end of Result, so I need to have
it in place.
Tell me about the loops

The loop is a fantastic tool for any function that involves doing the same thing more than once. If I
wanted to write my name 10 times, I would write a loop like this:
Write my Name
Of course that's not how I would type it. To create a loop I need to use the FOR statement. It is
written like this:
for ( count=1; count <=10; count++ ) {
(stuff I want to do 10 times)
This statement would be read outloud:
"For count equals one, while count is less than or equal to ten, incrementing by one"
The FOR statement above will begin by creating a variable called count (you can choose any
variable name). Initially, count will equal 1. The computer will perform whatever commands are
between the curly bracket s, then upon reaching the end of the loop, count is incremented by 1,
and a question is asked: IS COUNT LESS THAN OR EQUAL TO 10? If the answer is YES, then
the loop repeats. If the answer is no, then the progr am exits the loop, and goes on with the

The LOOP - continued

Here is a function designed to display an alert box with the number 1 in it, then with the number 2,
then with a 3, then a 4, then a 5, and then stop.
for (count=1; count<=5; count++) {
How do we create the text code?
A few text properties
Here are a few of the text properties which we use in this function. There are properties for every
type of object on your page. After you are through with this tutorial, you will be able to look up
other properties from Netscape's Referenc e Page and understand how to use them.
You can extract information about a piece of text by referring to one of that variable's properties.
The length property tells me how many characters long a text string is. If I want to display an
alert box with how many letters I typed, I would type alert(text.length).
function DisplayLength() {
MyText=prompt("Type some text","")
alert ( MyText.length )
If I wanted to find the first character of a piece of text I would use the substring property. Unlike
length, the substring property needs additional information in parentheses, specifically how many
places in to start and stop. Remember t o alway s subtract 1 from how many characters places
you want, because JavaScript begins counting the first letter as zero.
var.substring ( start, stop )
function DisplayFirstChar() {
MyText=prompt("Type some text","")
alert ( MyText.substring(0,1) )
The opposite of Substring is the indexOf property. Instead of returning the text at a certain
position, it returns the position of a certain piece of text. For example, if I set MyText equal to
"Tupperware" then the property MyText. indexO f("r") would return a value of 5. "r" is the sixth
letter in, but again, JavaScript begins counting with zero.
function Display_r_position() {
MyText=prompt("Type some text containing an 'r'","")
alert ( MyText.indexOf("r") )
The += operator allows me to add text to the end of an existing variable. For example, if the
variable MyText="cat" then the command MyText+="erpillar" would result in MyText equalling
"caterpillar." This example will tack anything you type onto the word "cat."
function AddToCat() {
AddOn=prompt("Type something to go after cat","")
MyText += AddOn
alert ( MyText)
Put it all together
function encode(text) { Ref="0123456789abcdefghijklmnopqrstuvwxyz.-
for (Count=0; Count<text.length; Count++) {
Char=text.substring (Count, Count+1);
Num=Ref.indexOf (Char);
EncodeChar=Ref.substring(Num+1, Num+2)
Result += EncodeChar
Looking at the function above, you can see that I have created a loop. The loop uses Count as its
counting variable. It will repeat once for each letter in text.
Inside the loop I have written four commands to be executed every time the loop is repeated.
Take our initial example of HAL. Here is what would happen during each pass through the loop.
At the start of the loop:
Ref="01234567890abcdefghijklmnopqrstuvwxyz-~ABCDE...." etc.
Result="" (Result is an empty placeholder)
Loop 1 Loop 2 Loop3
Count=0 Count=1 Count=2
Char=text.substring (Count,
Char = "H". Char = "A". Char = "L".
Num=Ref.indexOf (Char); Num = 46. Num = 38. Num = 50.
EncodeChar=Ref.substring(Num+1, EncodeChar = EncodeChar = EncodeChar =
Num+2) "I" "B" "M"
Result =
Result += EncodeChar Result = "I" Result = "IB"

When you need to DO something, like open a window, write text to the screen, get the sin of a
number, isolate the 1st letter in a word, assign today's date to a variable, send the user back to
the previous page, or display an alert box you are using a method.
When you change the details about something which already exists, you are changing its
For example:
document.bgcolor="red" is a property because I'm changing the existing details about the
document. alert("Hello There") is a method because it creates something new, an alert box.
Here are a few types of commands that methods are useful for.

• Date Methods - set variables to the clock time in a variety of ways.

• Window Methods - used to open and close new windows
• Document Methods - Generate new documents on the fly.
• Form Methods - select form items, send the cursor to text boxes and submit forms.
• History Methods - Press the reader's 'Back' button and other tricks.
• Text Methods - Define the look of your text variables before your display them.
• Math Methods - sin, cos, round, random, absolute value, etc.
• MessageBox Methods - Alert, Prompt, and Confirm are all methods.

Let's Learn Methods

Type a message in the box,
it will become a link to close the new window.

You guessed it, here is the code

Look it over, then we'll break it on down
<!-- Beginning of JavaScript -
function MyWindow(message) {
//Define Date to display in local syntax
now = new Date();
LocalTime = now.toLocaleString();
//Define contents of page
'<body bgcolor="beige">'+
'Click on the message below to close this window<br>'+
'<A HREF="javascript:window.close()" >'+
message +
//Create new Window
options = "toolbar=0,status=0,menubar=0,scrollbars=0," +
"resizable=0,width=300,height=200";"","mywindow", options);
// - End of JavaScript - -->
<BODY bgcolor="white" onLoad="this.form1.text1.focus()">
<TABLE BORDER=1 bgcolor="beige"><tr><td><B>Type a message in the box, <br>it will
become a link to close the new window.</B>
<FORM NAME="form1">
<INPUT NAME="text1" TYPE=Text SIZE="50" MAXLENGTH="50"><br>
<INPUT TYPE=Button VALUE="Create my window" onClick="MyWindow(form.text1.value)">
Learn Methods
//Define Date to display in local syntax
now = new Date();
LocalTime = now.toLocaleString();

Date Methods
Before you can do anything which involves the current date/time, you have to set a variable equal
to the current date. now = new Date() is command to get the current date and time from the
user's computer, and assign it to the variable, now in one long string.

toLocaleString() is a method which converts the raw date/time string of text into the local
convention. Depending on what country JavaScript thinks the user is in, the toLocaleString()
may present the month first, or the day first.

now =
now.toLocaleString() =
Here are some other Date methods:

If now =
now.getDay()= Day of week (0=Sunday)
now.getMonth()= Month (0 to 11)
now.getDate()= Day of month
now.getYear()= Year
Note: IE returns a 4 digit year, Netscape returns the number of years since 1900. Use this syntax:
if (year<1900) {year+=1900};

now.getHours()= Hours
now.getMinutes()= Minutes
now.getSeconds()= Seconds
..........Milliseconds since January 1, 1990 at Midnight.
now.gettimezoneOffset()= minutes off from GMT
//Define contents of page
'<body bgcolor="beige">'+
'Click on the message below to close this window<br>'+
'<A HREF="javascript:window.close()" >'+
message +

Creating long strings of text

I can use the plus sign (+) to add text and variables together into one long piece of text. For
The command
result = "Hello " + "world"
Will cause result to equal Hello world
You can use the same technique to combine text with variables, like this.
mytext = prompt("what is your favorite color","")
result = "Your favorite color is " + mytext

result =
//Define contents of page
'<body bgcolor="beige">'+
'Click on the message below to close this window<br>'+
'<A HREF="javascript:window.close()" >'+
message +

Creating long strings of text

The example above shows an entire HTML page defined into one variable, named contents.
There are 2 reasons why I put a plus sign at the end of each line, instead of simply writing one
long line of text. First, the document is much easier to read and edit this way. Second, there is a
limit on how long a line of JavaScript can be. I don't know exactly what the limit is, but I know that
I get errors when I create very long lines in my script. The plus sign helps me break the definition
of con tents into 7 small lines instead of 1 big one.
Notice the bottom 3 lines. They create a HREF link around your text. message is the contents of
your sample text. If message="Hello" then the last 3 lines would read
<A HREF="javascript:window.close()"> Hello </A>
function myLink(text) {
result =
'<A HREF="mypage.htm">' +
text +
' </A>'
Type something and click the button

result =
As you can see, the <A HREF> tag can be used to trigger javascript events instead of creating a
link to another page. We will discuss this in more detail later.
More about windows
//Create new Window
options = "toolbar=0,status=0,menubar=0,scrollbars=0," +
"resizable=0,width=300,height=200";"","mywindow", options);

The method

When I want to open a new window, first I think of a name for the window, such as MyWindow.
Then I open the window with this command:
MyWindow =
The method can have 3 optional parameters. Parameters are things you can type
inside the parentheses to specify how you want the window to open. The 3 parameters are:

1. A URL so that the window contains a specific HTML document.

2. A title for the window
3. A set of options for the window's appearance, including height and width.

For example, let's say I created a page called mytest.htm. It might be as simple as this:
<TITLE>Test Page </TITLE>
This is only a test
I could open it into a new window like this.
NewWindow ="mytest.htm")
Next Page
//Create new Window
options = "toolbar=0,status=0,menubar=0,scrollbars=0," +
"resizable=0,width=300,height=200";"","mywindow", options);

The method

The second parameter is the default title of the window. The third parameter allows you to set a
long list of options about your new window. Here are the options you can set.
Option choice description
toolbar yes/no or 1/0 Display toolbar
status yes/no or 1/0 Display status bar at bottom of window
menubar yes/no or 1/0 Display menubar
scrollbars yes/no or 1/0 Display horizontal and vertical scrollbars
resizable yes/no or 1/0 Window can be resized
location yes/no or 1/0 Display location box
directories yes/no or 1/0 Display directory buttons
width # of pixels Exact width of new window
height # of pixels Exact height of new window
If I want to open the mytest document in a small, 100 x 100 pixel window I would type this:
NewWindow ="mytest.htm","mywindow","width=100,height=100")
As you can see, the command can get very long. One solution is to specify the
options in a seperate variable, which I call "options." Then your command would look like this:
options = "width=100,height=100"
NewWindow ="mytest.htm","mywindow",options)

More about Windows

The method

Let's try creating a larger list of options.
Experiment with different options in this table. A variable called options will be created below
with your list of window options. Then click Make my Window to see how your window looks.
Option choices your entry
toolbar yes/no or 1/0
status yes/no or 1/0
menubar yes/no or 1/0
scrollbars yes/no or 1/0
resizable yes/no or 1/0
location yes/no or 1/0
directories yes/no or 1/0
width # of pixels
height # of pixels
options = " "+
" ""mytest.htm","",options)
How do I write?

Writing to a document
You can create an HTML document 'on the fly' with JavaScript using the document.write()
method. Normally, you must open a new document first. Then you may write to that document,
and finally you must close the document so that the Browser can stop tryi ng to load it. Here is an
document.write("Hello There")
When I create a new window, I am also opening a new document. So I can write to a new window
with this series of commands.
NewWindow ="","","width=200,height=200")
NewWindow.document.write("Hello There")
The document.write() method can contain either text or a variable inside the perentheses. The
following example creates a variable, then writes the variable to a new document.
SampleText = "Hello there, " +
"It's nice to see you again."
NewWindow ="","","width=200,height=200")
I can even include HTML tags in the document.write() statement. Like this:
NewWindow ="","","width=200,height=200")
NewWindow.document.write("<CENTER><H1>Hello there</H1></CENTER>")
More about document.write()

Writing to a document
With just a little creativity, you can have JavaScript create fully formatted web pages on the fly.

Please enter your first name

What city/town do you live in?
How old are you?
Name another person in your house

Here is the code for that page generator.

function MakePage(name,town,roommate,age) {
var content = '<HTML><HEAD><TITLE>'+name+'\'s Page</title>' +
'</head><body background="images/space.gif" text="yellow" link="#FFBBBB" vlink="#FFBBBB">'
'<FONT COLOR="4EEA6C"><center><h1>' +
name + '\'s Page</h1></center></FONT>' +
'<IMG ALIGN=Left SRC="" WIDTH="72"
HEIGHT="72">Hello, and welcome to my page. I live in ' + town + ' and I am ' + age + ' years old.'
'<p>' + town + ' isn\'t a bad place to live, if you can stand ' + roommate + '\'s cooking <P>' +
'Some people think they\'re so cool just because they created a home page. <br> ' +
'They have fancy backgrounds and colors, but they just go on and on with nothing to say. <br> ' +
'<A HREF="">Click Here to search Yahoo</A><--Boy, there\'s a link I
never' +
' would have found on my own. Some people\'s pages are so boring I think my computer could do'
' a better job with a 10 line program.'
On to Chapter 6-Events

Every object on your page has certain 'Events' which can trigger your JavaScript functions. For
example, we use the 'onClick' event of the form button to indicate that a function will run when
the user clicks that object. We define the events in the same HTML tag which we use to place an
object on the screen. So a button which runs 'myFunction()' when clicked will be written this way.
<input type=button value="click me" onClick="myFunction()">
I could also use onMouseOver to make an event happen when the user's mouse is over certain
objects. For instance a message could appear in an alert box.

Images can't have events, but links can. So I added an onMouseOver event to the above image
by creating a link to nothing around it. Here is the code for the above image:
<A HREF="#" OnMouseOver="alert('hi')">
The following table outlines all of the event handlers in NetScape version 3.0

Event Applies to Occurs when handler
abort images User aborts the loading of an onAbort
image (for example by clicking a
link or clicking the Stop button)
blur windows, frames, and all User removes input focus from onBlur
form elements window, frame, or form element
click buttons, radio buttons, User clicks form element or link onClick
checkboxes, submit buttons,
reset buttons, links
change text fields, textareas, select User changes value of element onChange
error images, windows The loading of a document or onError
image causes an error
focus windows, frames, and all User gives input focus to window, onFocus
form elements frame, or form element
load document body User loads the page in the onLoad
mouseout areas, links User moves mouse pointer out of onMouseout
an area (client-side image map) or
mouseover links User moves mouse pointer over a onMouse-
link Over
reset forms User resets a form (clicks a Reset onReset
select text fields, textareas User selects form element's input onSelect
submit submit button User submits a form onSubmit
unload document body User exits the page onUnload
More about Events

There are 3 events which I find particularly useful when working in a form.

• onFocus
• onBlur
• onChange

FOCUS means the object where the cursor is currently blinking. OnFocus events occur
whenever the cursor enters that textbox or textarea. It doesn't matter whether the user placed the
cursor there with the mouse or with the TAB key. As soon as the cursor enters a box, an
OnFocus event attached to that box wil l occur.
<INPUT TYPE=TEXT SIZE=20 onFocus="window.status='Hi there';return true">

BLUR is the opposite of focus. Therefore an onBlur event will occur whenever a text object
loses focus. Here is the same example again, but the alert will occur when you try to leave the
<INPUT TYPE=TEXT SIZE=20 onBlur="window.status='Bye now';return true">
Try moving the focus from the second example to the first, and the message will appear twice,
once because you left the box with an onBlur event, and once because you entered a box with
an onFocus event.
More Events

onChange Events
Certain types of form objects, such as checkboxes and menus can't have a text cursor, so they
can't trigger an onBlur event when you make changes. You can use the onChange event to
trigger your functions when the user has make his/her selec tion on these items.
function getSelect(s) {
return s.options[s.selectedIndex].value
<SELECT NAME="list" SIZE=1 OnChange="location=getSelect(this)">
<OPTION value="#"> Choose a search engine
<OPTION value=""> Yahoo
<OPTION value=""> Lycos
<OPTION value=""> Excite

Since Netscape forgot to provide a function for getting the value of a select box, I wrote one
which I place in the <SCRIPT> tags of any page that has a selection list. Simply copy the
getSelect(s) function into your <SCRIPT> area, and getSelect(form.mylist) will return the Value
of the current mylist selection.
In this example we used the word this as a shortcut. We could have said getSelect(form.list),
however since the command was inside the <SELECT> tag, the word this automatically referred
to the current <SELECT> object. In this example, if Lycos was selected, then the event
onChange="location=getSelect(this)" would be interpreted as

Check Boxes
Since a checkbox is selected/deselected with a mouse click, the onClick event will trigger your
function whenever the checkbox is changed. Each checkbox has a property called checked
which is equal to true or false depending on whether the box is currently checked. This example
runs a function when the box is clicked, and displays a message if the box is checked.
function rushbox(checked) {
if (checked==true) {alert(" LIFT OFF! ")}
<INPUT TYPE=checkbox NAME="rush" OnClick="rushbox(form.rush.checked)"
Rush this order <FORM>
Rush this order
Page Load events

onLoad Events
Upon loading this page, a window appeared with a welcome message in it. The window stayed
for 5 seconds, then closed. If you want to see it again, click RELOAD
The onLoad event is placed in the <BODY> tag, and it is used to trigger events automatically
upon loading the page. You can use the onLoad to display a welcome message, place the focus
in a particular textbox, execute a special effect, o r prompt for a password. The <BODY> tag of
this page looks like this:
<BODY bgcolor="white" onLoad="MsgBox()">
MsgBox() is a function in the <SCRIPT> area which opens a window, then closes it after 5
seconds. We will discuss the setTimeout() method used to close the window automatically in
more detail later.
How about onUnload events?

onUnload Events
As you may have guessed, the onUnload() event handler will trigger an event when the user
exits the current page.
I had this page open into a new window so that you can experiment with the onUnload event
handler without losing your place in the tutorial.
Here is the <BODY> tag at the top of this document.
<BODY BGCOLOR="white" onUnload="alert('Please come back soon')"
Use any method you like to leave this page. Click the back button, type a URL into the location
box, reload, close the window, or follow a link like this one.
Click to see a cute animation.
No matter how you leave the page the onUnload() event will trigger.
Yes you can use onUnload to make a page difficult to leave, but this would quickly result in a very
lonely web site.

The SetTimeout() Method

This one is easy! You can make and JavaScript command execute after a delay by typing the
command like this:
setTimeout(" your function ", delay in milliseconds)
So for example, this function would make an alert box appear 5 seconds after you click the
function MsgBox() {
alert("Hello There");
<INPUT type=button value="try it"
So, when I made my welcome window a few pages ago, I simply had to use this function in the
<BODY onLoad=" "> statement.
function Welcome() {
NewWindow ="welcome.html","","width=200,height=200");

Bonus Chapter! Special Effects.

This 15 page chapter is available only as part of the downloaded zip file.
The cost for this entire tutorial is a very reasonable $7.75 US.
It also includes a printable text file of the entire tutorial,
and a cheat sheet (quick reference) of all the codes used in the tutorial.
Click Here to download this file.
Chapter 7, special effects!
The glowing button
A reasonably secure Replacing Images
password box. Enter the Using option menus
word 'scarlet.' The The Image Map
password does not exist
anywhere in the source
secure password
code. status bar messages

G.Yogeshwar Dayalb{A Virus ProgrammAr And Hacker}