You are on page 1of 107

^

JAVA SCRIPT

Table of Contents

Training Topics Page No.


Cycles

1 Introduction to JavaScript 1

2 Basic Programming Syntax in JavaScript 7

3 Function Object Oriented Concepts 15

4 Java script Objects 19

5 Window Objects 31

6 Frames 39

7 Forms interaction of html and Javascript objects 47

8 Understanding Event Handlers in JavaScript 60

9 Image Object 64

10 Layers 71

11 JavaScript Hover Buttons 76

12 Detecting Objects instead of browsers 81


Training Cycle -1
Javascript
Wintech Computers

Introduction to JavaScript

JavaScript is anew scripting language, which is being developed by Netscape. With JavaScript you
can easily create Interactive web pages.

What is needed in order to run scripts written in JavaScript? You need aJayaScrip -enabled bowser
-for example the Netscape Navigator (since version 2.0) or the Microsoft Internet Explorer (MSIE -
since version 3.0). Since these two browsers are widely spread many people are able to run scnpts
written in JavaScript. This is certainly an important point for choosing JavaScript to enhance your
acouarseSyou need abasic understanding of HTML before reading this tutorial. You can find many
really good online resources covering HTML. Best you make an online search for 'html' at Yahoo m
order to get more information on HTML.

Embedding JavaScript Into a HTML-page :


JavaScript code is embedded directly into the HTML-page. In order to see how th.s works we are
going to look at an easy example:

<html>
<body>
<br>
This is a normal HTML document.
<br>
<script language="JavaScript">
document.writeCThis is JavaScript!")
</script>
<br>

Back in HTML again.

</body>
</html>

At the first glance this looks like a normal HTML-file. The only new thing is the part:

<script language="JavaScript">
document.write("This is JavaScript!")
</script>

This is JavaScript. In order to seethis script working save this code as a normal HTML-file and load
it into your JavaScript-enabled browser. Here is the output generated by the file (if you are using a
1
Training Cycle 1
Wintech Computers
Javascript
JavaScript browser you will see 3lines of output):
This is a normal HTML document.
This is JavaScript!
Back in HTML again.

Imust admit that this script isn't very useful -this could have been written in pure HTML more easily
Ion.y wanted to demonstrate the <script> tag to you. Everything between the <script> and the ^'
scnpt> tag is interpreted as JavaScript code. There you see the use of
document.writeQ

one of the most important commands in JavaScript programming, documenting) is used in order
to write something to the actual document (in this case this is the HTML-document) So our little
JavaScript program writes the text This is JavaScript! to the HTML-document.
Non-JavaScript browsers :
What does our page look like if the browser does not understand JavaScript? Anon-JavaScript
browser does not know the <script> tag. It ignores the tag and outputs all following code as if it was
normal text. This means the user will see the JavaScript-code of our program inside the HTML-
document. This was certainly not our intention. There is a way for hiding the source code from older
browsers. We will use the HTML-comments <!-- ->. Our new source code looks like this-
<html>
<body>
<br>

This is a normal HTML document.


<br>
<script languagesJavaScript">
<!-- hide from old browsers
document.writefThis is JavaScript!")

</script>
<br>
Back in HTML again.
</body>
</html>

The output in a non-JavaScript browser will then look like this:

This is a normal HTML document.


Back in HTML again.

Training Cycle 1
Javascript
Wintech Computers

Without the HTML-comment the output of the script in anon-JavaScript browser would be:
This is a normal HTML document.

document.write("This is JavaScript!")
Back in HTML again.

Please note that you cannot hide the JavaScript source code completely. What we do here is to
prevent the output of the code in old browsers -but the user can see the code through View docu
ment source' nevertheless. There is no way to hinder someone from viewing your source code
(in order to see how a certain effect is done).

Events: u .
Events and event handlers are very important for JavaScript programming. Events are mostly caused
by user actions. If the user clicks on a button a Click-event occurs. If the mousepointer moves
across a link a MouseOver-event occurs. There are several different events.. We want our JavaScript
program to react to certain events. This can be done with the help of event-handlers. Abutton might
create apopup window when clicked. This means the window should pop up as areaction to aClick-
event. The event-handler we need to use is called onClick. This tells the computer what to do if this
event occurs. The following code shows an easy example of the event-handler onClick:

<form>
<input type="button" value="Click me" onClick="alert('Yo,)">
</form>

There are a few new things in this code - so let's take it step by step. You can see that we create a
form with a button (this is basically a HTML-problem so). The new part inCllck="alert('Yoy
inside the <input> tag. As we already said this defines what happens when the button is pushed. So
if a Click-event occurs the computer shall execute alert('Yo'). This is JavaScript-code (Please note
that we do not use the <script> tag in this case). alert() lets you create popup windows. Inside the
brackets you have to specify a string. In our case this is 'Yo'. This is the text which shall be shown in
the popup window. So our script creates a window with the contents 'Yo' when the user clicks on the
button.
One thing might be a little bit confusing: In the document.write() command we used double quotes "
and in combination with alert() we use only single quotes ' - why? Basically you can use both. But in
the last example we wroteonClicks-alertCYo')" - you can see that we used both double and single
quotes. If we wrote onClick="alert("Yo")" the computer would get confused as it isn't clear which
part belongs to the onClick event-handler and which not. So you have to alternate with the quotes in
this case. It doesn't matter in which order you use the quotes - first double quotes and then single
quotes or vice versa. This means you can also writaDnCHcks'alertCYo")'. There are many differ
ent event-handlers you can use.

If you are using the Netscape Navigator the popup window will contain the text JavaScript alert. This
Is- a security restriction. You can create a similar popup window with the prompt() method. This
window accepts an input. A malicious script could imitate a system message and ask for a certain

Training Cycle 1
Wintech Computers Javascript

password. The text in the popup window shows that the window comes from your web browser and
not from your operating system. As this is a security restriction you cannot remove this
message.

Functions :
We will use functions in most of our JavaScript programs. Therefore I will talk about this important
concept already now.Basically functions are a way for bundling several commands together. Let's
write a script which outputs a certain text three times. Consider the following approach:

<html>
<script language="JavaScript">
<!-hide
document.write("Welcome to my homepage!<br>");
document.write(MThis is JavaScriptkbo");
document.write("Welcome to my homepage!<br>");
document.write("This is JavaScriptkbo");
document.writefWelcome to my homepage!<br>");
document.write("This is JavaScript!<br>");
//-->
</script>
</html>

This will write out the text

Welcome to my homepagel
This is JavaScript!

three times. Look at the source code - writing the code three times brings out the right result. But is
this very efficiently? No, we can solve this better. How about this code which does the same:

<html>
<script language=HJavaScript">
<!-hide
function myFunction() {
document.write("Welcome to my homepage!<br>");
document.write("This is JavaScript!<br>");
}

myFunction();
myFunction();
myFunction();
// -->
</script>
</html>

Training Cycle 1
A Javascript
Wintech Computers

In this script we define a function. This is done through the lines:

function myFunction() {
document.write("Welcome to my homepage!<br>");
document.write("This is JavaScript!<br>");
}

The commands inside the {} belong to the function myFunction(). This means that our two
document.write() commands are bundled together and can be executed through a function call. In
our example we have three function calls. You can see that we write myFunction() three times just
below the definition of the function. These are the three function calls. This means that the contents
of the function is being executed three times. This is a very easy example of a function. You might
wonder why functions are so important. While reading this tutorial you will certainly realize the ben
efits of functions. Especially variable passing makes our scripts really flexible -we will see what this
is later on.

Functions can also be used in combination with event-handlers. Please consider this example:

<html>
<head>
<script language="JavaScript">
<!-hide
function calculation()
{ var x= 12;
var y= 5;
var result= x + y;
alert(result);
)

</script>
</head>
<body>
<form>
<input type="button" value="Calculate" onClick="calculation()">
</form>
</body>
</html>

Here you can test this example:

The button calls the function calculation(). You can see that the function does certain calculations.
For this we are using the variables x, y and result. We can define a variable with the keyword var.
Variables can be used to store different values - like numbers, text strings etc. The line var
results x + y; tells the browser to create a variable result and store in it the result of x + y (i.e. 5-1-12).

Training Cycle 1
Wintech Computers Javascript

After this operation the variable result is 17. The command alert(result) is in this case the same as
alert(17). This means we get a popup window with the number 17 in it.

Training Cycle 1
Training Cycle - 2
Wintech Computers Javascript

Basic programming syntax in Java script

Variables and Data-Types

Every programming language can handle various types of information. Such types of information
are known as data types.Javascript supports four different data types .
01) Number
02) Strings
03) Boolean
04) Null

In java script a variable is not required to be declared explicitly ,but rather implicit declaration takes
place initially when the variable is assigned the value

Type Desc Examples

Number Any number without quotes or 56.5 or 2e-16

String A series of character enclosed in quotes "hellO" or " 10 " or' or"
marks

Boolean Alogical value true or false

Null A keyword meaning : no value null

Number :
Numbers system can be further subclasses in two parts
i) integer
ii) floating point numbers.

Integer:
Integer is whole number that has no decimal point ex 56, 98, 0, -123, -23. It can be either positive or
negative. JavaScript supports three types of integer bases:

Base Desc Example

Decimal Base 10 integer.having no 0 prior to the num. 23,5,67,123,8,etc.

Octal Base 8 integer,.numbers written with a 043,0334,0544,etc.


leading 0
Hexadecimal Base 16 number.number starting with
leading Ox or OX, 0X12A , 0X542 , 0X45ab ,
0Xb5c , etc.

Trlining Cycle 2
7
Wintech Computers
Javascript
Floating num.:
Numbers having fractional parts.ie number having decimal points .Additionally afloatina point
number may include ab exponent specification of the form e+-exp. 9^
Ex -* var myvar = 12.345
myvar = 0.056
myvar = 4.2e12
myvar = -3.1e12
myvar = 2e-12

Boolean values
Boolean values also called logical values, are basically true or false. They are generally used in
conditional and logical expression Javascript officially uses the true and false values to express
boolean value, but 1and 0are acceptable, i.e true by 1, false by O.the true value can be replaced
by any non zero mteger.but it is better to avoid for netscape does not recognize it
myvar = true
myvar = false
myvar = 1
myvar = 0

The Null Value


The null is often used to initialize variable that do not have any special meaning.
Var name = null

The null value automatically converts the initial value of other data types such as
Number - 0
String - ""
Boolean - false

Type Conversion
In JavaScript the data types are automatically converted as needed during the course of script
execution .A variable may hold a numeric value at a time and a string at some other time.
Ex -* var myvar =12
myvar = "wintech"

Training Cycle 2
Javascript
Wintech Computers

Implicit conversion between types


In JavaScript automatic conversions take place as operations on different data types are being
performed, as shown in the table below.

String Integer Float logical logical null


Row + column
123 .123 true false
"12.34"

Test123 test. 123 testtrue testfalse testnull


String "test" Test12.34

246 123.123 124 123 123


Integer 123 12312.34

.12312.34 123.123 .246 1.123 .123 .123


Float .123

124 1.123 2 1 1
Logical true True12.34

.123 1 0 0
Logical false False12.34 123

Null12.34 123 .123 1 0 0


Null

Operators
Operators take one or more variables or va\ues(operands) and return a new value; e.g. the '+'
operator can add two numbers to produce a third. You use operators in expressions to relate values,
whether to perform arithmetic or compare quantities. Operators are divided into several classes
depending on the relation they perform:

Arithmetic or computational:
Arithmetic operators take numerical values (either literals or variables) as their operands and return
a single numerical value. The standard arithmetic operators are:

+ Addition

Subtraction

* Multiplication

/ Division

% Modulus: the remainder after division;


e.g. 10 % 3 yields 1.

++ Unary increment: this operator only takes one operand. The operand's value is increased by
1. The value returned depends on whether the ++ operator is placed before or after the
operand; e.g. ++x will return the value of x following the increment whereas x++ will return the
value of x prior to the increment.

Training Cycle 2
Wintech Computers
Javascript

- Unary decrement: this operator only takes one operand. The operand's value is decreased
by 1. The value returned depends on whether the - operator is placed before or after the
operand; e.g. -x will return the value of xfollowing the decrement whereas x~ will return the
value of x prior to the decrement.

Unary negation: returns the negation of operand.

Comparison:
Acomparison operator compares its operands and returns a logical value based on whether the
comparison is true or not. The operands can be numerical or string values. When used on string
values, the comparisons are based on the standard lexicographical (alphabetic) ordering.
== "Equal to" returns true if operands are equal.

!= "Not equal to" returns true if operands are not equal.

> "Greater than" returns true if left operand is greater than right operand.
>=
"Greater than or equal to" returns true if left operand is greater than or equal to right operand.
<
"Less than" returns true if left operand is less than right operand.
<=
"Less than or equal to" returns true if left operand is less than or equal to right operand.
Boolean:

Boolean operators are typically used to combine multiple comparisons into a conditional expres
sion. For example, you might want to test whether (totaMOO) AND (stateTax=true). A boolean
operator takes two operands, each of which is a true or false value, and returns a true or false result.

&& "And" returns true if both operands are true.

II "Or" returns true if either operand is true.

! "Not" returns true if the negation of the operand is true (e.g. the operand is false).
>=
"Greater than orequal to" returns true if left operand is greater than or equal to right operand.
"Less than" returns true if left operand is less than right operand.

<= "Less than or equal to" returns true if left operand is less than or equal to right operand.

String:
Strings can be compared using the comparison operators. Additionally, you can concatenate strings
using the + operator.

"dog" +"bert" y,elds "dogbert"

10 Training Cycle 2
Javascript
Wintech Computers

The assignment operator (=) lets you assign avalue to avariable. You can assign any value to a
variable including another variable (whose value will be assigned). Several shorthand assignment
operators allow you to perform an operation and assign its result to avariable in one step.
Assigns the value of the righthand operand to the variable on the
left.

Example:total=100; total = ( price+ tax +shipping)

+=

(also -=, *=, /=) Adds the value of the righthand operand to the lefthand variable.
Example: total+=shipping (adds value of shipping to total and as
signed result to total)

&=
(also l=) Assigns result of (lefthand operand && righthand operand) to lefthand
operand.

Special :
Several JavaScript operators, rarely used, fall into no particular category. These operators are sum
marized below.
Conditional operator

(condition) ? trueVal: falseVal Assigns a specified value to a variable if a condition is true,


otherwise assigns an alternate value if condition is false.
Example:
preferredPet = (cats > dogs)? "felines" : "canines"
If (cats>dogs), preferredPet will be assigned the string value
"felines," otherwise it will be assigned "canines".

typeof operand Returns the data type of operand.


Example ~ test a variable to determine if it contains a number:
if (typeof total=="number") ...

Training Cycle 2 11
Wintech Computers
Javascript
Assignment operator shortcuts:

If you write scripts that involve a lot of basic math operations (+-/) you'll want to know the assign-
ment operator shortcuts:

Operator:
Translation:

x++
x=x+1

x~
x=x-1

x+=y
x=x+y

x-=y
x=x-y

X*=y
x=x*y

x/=y
x=x/y

Using these operators, you can replace expressions like:


x=x+y with simply x+=y
Quite handy, wouldn't you say?

Statements

Conditional :

1) The if/else statement.

if (conditional statement)
{ JavaScript statements.
}
else
{ JavaScript Statements..
}

This statement is useful if you want to check for a variable value or a number of values. If the
statement in side the ( ) symbols is true, the commands that follow the if command inside the {}
symbols will be executed. Otherwise, the commands after the else statement are executed. Here is
an example:

12
Training Cycle 2
WintechComputers Javascript

var number=3;
var mymoney=0;
if (number > 2)
{ mymoney=100;
}
else
{ mymoney= -100;
}

This set of code decides the fate of the variable mymoney, based on the value of the variable
number. If number is greater than 2, then the value of mymoney will be changed to 100. If number is
not greater than 2, the mymoney is -100, and I'm in some trouble with my bank.

iterations:
Now, suppose you wanted to perform a set of commands a number of times, and end when you
have what you need. To do this, you can use a for loop or a while loop to repeat things. First, the for
loop:

for ( condition 1; condition2; command)


{
JavaScript Statements....
}

OK, what this does is begin the loop with condition 1, end the loop with condition 2, and perform the
command each time through. So, if you want to change a variable value 10 times, you would do
something like this:

var count=1;
var mymoney=0;
for (count=1; count<11; count=count+1)
{
mymoney=mymoney+100;
}

The loop begins with count=1. Then the statement mymoney=mymoney+100 is executed the first
time. Then the command count=count+1 is executed, making count equal to 2. Once that is done,
the value of count is checked to be sure it is less than 11 (condition 2). Since count is 2, which is less
than 11, the loop statement is executed again, and count goes up to 3. This goes on and on until
count is equal to 11, thus not being less than 11. The loop will end before going through another
time. What did Iget out of this? Well, mymoney went from 0 to 1,000 really quickly! Now for the while
loop. It does pretty much the same thing as the for loop, but is written out differently:

Training Cycle 2
13
Wintech Computers Javascript

var count=1 ;
var mymoney=0;
while (count<11)
{
mymoney=mymoney+100;
count=count+1;
}

This example does the same thing as my last one. The only thing that is checked is whether count
is less than 11 or not. If it is, the statements are executed. If not, the loop ends. Remember to add
one to count within the statement section here, or you'll get the ever popular "infinite loop".

Training Cycle 2
14
Training Cycle - 3
Javascript
Wintech Computers

Functions

Defining Function:

Functions are multiline statements that are executed as per the requirement when it is called. Functions
may include looping statements, nested statements, etc. In javascript, functions are defined using
the keyword function, followed by the name of the function.
The syntax of a function defination is:

function functionname ([parameters])


{ statement 1;
statement 2;
statement 3;

statement n;

Parameters are local variables that are assigned values when the function is called , or can be
referred as the data that is passed to the function to process on, the square brackets "[" and "]"
denotes optional elements.the curly brackets denotes the multiple statements( or the body of the
function) that is always executed when the function is called.

Function call :
The function which are defined has to be called as per the requirement .the syntax of a function call
is :
functionname([arguments])

the arguments are the data that is send as parameters to the function to process on.

Variable scope:
All javascript variables have two attributes:

Scope
Storage class

Scope :
The scope of a variable describes the area of the script where the variable is valid. The scope of a
global variable is the entire script. You can access it anywhere between the <script> and </script>
tags and other scripts that are executed after the variable definition .in javascript, you can declare
global variables with or without the keyword var .it does not effect the scope of the variable at all.

Training Cycle 3 15
Wintech Computers
Javascript

Alocal variable is declared in afunction .it can only be referenced by statements inside that function
Alocal variable must be declared inside a function using the keywords,if. omitted, the variable is
assumed global.

Example:

<script>
function test()
{
age=43;
}
age=11;
test();
document.write(age+ "<br>");

</script>

Example 2:

<script>
function test()
{
var age=43;
}
age=11;
test();
document.write(age+ "<br>");

</script>

the output if the first script is 43,and the putput of the second script is 11.in the second script the var
word means that the variable age, which is defined insuide the function is local.it does not exit
beyond the boundaries of the function .the print statement prints the value of the global variable
.which is unchanged by the function.

Storage class :
The variable storage class may be either permanent or temporary, it depends only on the scope of
the variable local variable are temporary, while global variable are permanent permanent variable
exits throughoutthe script and even in other script, and it remains even after the script is terminated.and
is discarded only when the page is unloaded. Temporary variables ere allocated on the stack when
a function is called, and is returned to the stack at the end of the execution.
Function parameters are identical to local variables. They exit only inside the function, and do not
effect the variable outside the function.

16 Training Cycle 3
Javascript
Wintech Computers

Summary
Javascript scans the entire script before any execution begins, javascript evaluates Each line of
code testing it for syntax error and also determines the scope of the each variable ,if encountered
with the keyword var .it is considered local. Avariable has to be defined or intialized before using it.
Object Oriented Concepts

Class :
In cprogramming language, a user can define his own data types using structures, which is collection
of different standard data types, this is use to represent the different qualities of its member function.
In object oriented language like C++ or Java, these concepts are implemented using class. Aclass
can be defined as user defined datatypes that represent the properties and behaveour of the object.

Objects :
Objects are basically run time entities that are created and executed during runtime. Objects are
created using the class constructors of the respective class, from which the object has to be created.
Each object consists of properties (variable) and behaveour (methods). These properties are basically
global variables that are defined within the scope of the class only, the methods are the function
which is being declared within the class.
Hence class can be defined as a blue print which define the characteristics of the respective object.

Class constructor:
Constructors are similar to methods that do not return anything but are executed while creating
objects. Constructors are generally used for creating objects of the respective class. They have the
same name as the class. For ex: in javascript to create an array object we use as follows:

var myarr = new Array([parameters]);

Where the new operator is used along with constructor MArray([parameters])" to create an array
object.
Once the objects are created, the resources are allocated for each objects. Nos of objects can be
created from one class, and each object allocates a separate memory for.its properties.

Properties:
Every physical object has its own unique characteristics. A car, for example, has a size, a weight, a
color, a price, and many other attributes. The full set of attributes distinguish a car from all other
objects. These features are called properties. Properties are usually named according to their meaning.
An object properties hold its data, using the syntax:

objectReference.propertyname

Object reference is the name of the object that the properties belongs to, or any other valid reference
to the object, for ex: you can assign an object to a variable and then refer to its properties using this
variables and then refer to its properties using this variable , followed by the property specification,
property name is the name of the property . A dot seperates each object from its property, a property
belongs to an object.and only to one object.
Training Cycle 3 17
Wintech Computers Javascript

Methods :
During execution of a javascript, an object may invoke one or more methods to accomplish a task..
Objects consist of both data and functions that handle the data. These functions are called methods.
Methods enable an object to perform different actions mostly on its own properties
An object methods is called by getting hold of its reference variable and the properties name i.e.using
the syntax:

objectReference.methodnameflparameterft

Objectreference is the name of the object ,or any other reference


For ex:
document.write(" this is an example");
document.write (23);
Where the write method is the method of the document object.

Javascript - an object based language


Javascript is based on a simple object -oriented paradigm. This paradigm is often called object
based, as opposed to object oriented. Classes do not exist in javascript (all objects belong to one
"class"), nor do packages (because a package groups classes together). The object hierarchy as in
java and C++. That is, an object does not inherit from another object, but can be contained in other
object, if it is a property of that object. Javascript is completely based on dynamic binding. That is,
object reference are always checked at run time.

JavaScript supports two different types of objects:


predefined built-in objects, such as the math object
User-defined objects.
These objects and their properties will be discussed later

Object hierarchy :
An object can be a property of another object, thus creating an object hierarchical structure .in such
an hierarchical object structure .with objects and properties at different levels uses the same syntax
of dot seperator
An method can exist at different level of an objects hierarchy.

Syntax:

objectl .object2property1 .objectpropetry2.property3

objectl .object2property1 .method1([parameter])

18 Training Cycle 3
Training Cycle - 4
Wintech Computers
Javascript

JavaScript Objects

Arrays:
Def: Arrays are data structures, that are used to store data information using the same variable
name at subsequent memory location. Each data that is stored at the subsequent memory loca
tion is referred as an array element, and are accessed using an index.
Creating simple arrays:
Arrays in JavaScript are simple built in objects. You can create an array just like an instance of an
object. The general syntax is:

var arrayobjref =new Array();


var arrayobjref =new Array(arraylength);
var arrayobjref =new Array(1,23,5,76, "Roland " .true, 4.34);

Here arrayobjref'is the new Array object that is being created. Object can be created using any
one of the three different constructor. The first default constructor allows to create an default array
object with no elements in it.the second array allows us to create an blank array object of the
length equal to that of arraylength. The third constructor allows us to create an array automatically
of length 7,and assigning the values
FOR ex:

Var a =new Array(1,23,5,76, "Roland " .true, 4.34);

index Value
a[0] 1

a[1] 23
a[2] 5

a[3] 76
a[4] Roland
a[5] True
a[6] 4.34

Whenever an array is being created the values are allocated in their subsequent memory as
shown. The first element is stored in the Oth index of the memory location. To elements of the
array can be accessed using the array name and the index of the element for ex:
document.write( a[3] );

Will give the output: 76

Training Cycle 4
19
Wintech Computers Javascript

Unlike Java or C++, in JavaScript arrays are not bound to hold data of similar datatypes .they can
store value of different datatypes within a single array. These arrays are dynamic in nature, that
is the size of array may grow as the user enters the value within the array object. All elements in a
array are initialized to null

Since a array is an object they have properties and methods.

Array properties :
The array object has just one built in property i.elength. u can create your own properties .when
you create an instance of an object, the number of elements is stored in the length property. The
length property can also be modified, i.e. you can change the length of the array by assigning the
property a value for ex:

var arrlen= a.length;

Will assign the variable arrlen with numbers of elements present in the array.

Array methods:

JavaScript has three built-in methods

Join()
reverse ()
sort( )

join ():
The join method is built in one in JavaScript. It is equivalent to the same function in peri. It joins
the elements to an array into a single string an separates each element with a given delimiter. Its
general syntax is:

arrayinstance.join(delimiter)

The delimiter is automatically cast to a string if it is not already one. Here is an example using the
method :

var line =new array ("a", "b", "c", "d", "e")


document.write (line.join (":"))
var str= line.join (",")
document.write ("<br>" +str)

the output is:

a : b : c : d : e
a, b ,c , d , e

20 Training Cycle 4
Wintech Computers Javascript

reverse ():
The reverse method transpose the elements of the calling array object. If it was descending, now
it is ascending etc. The last element becomes the first one, and vice versa. This is a build-in one.
The general syntax is:

var names = new Array("Roland", "Amit", "Mark", "Tom")


names.reverse ()

here are some examples:

output will be as
Tom , Mark ,Amit, Roland

sort():
It sorts the element of an array. It is optional to supply a sorting function. If one is not supplied,
the array is sorted lexicographically (comparison order, dictionary order), according to the string
conversion of each element.
The general syntax of this method is as follows:

Arraylnstance.sort (compareFunction)

If compare function is not supplied, elements are sorted by converting them to a strings and
comparing them in strings in lexicographic order for ex: "10" comes before "9"

Multidimensional Array :
JavaScript does not feature multidimensional arrays, but they can be created via a con
structor function. Multidimensional array can be defined as arrays of array. Since a single dimen
sion array can be used to store objects or data in the subsequent locations, it is possible to store
an array objects in one of the indexed location of the another array for ex:

var b= new Array("this", "is", "multidimension", "array");


var orgarr=new Array( 5 );

orgarr [0] =12;


orgarr [1] =2312;
orgarr [2] =b;
orgarr[3]= "thank u";

Training Cycle 4 21
Wintech Computers Javascript

The created array will be as

Index Value

orgarr[0] 12

orgarr[1] 2312

orgarr[2] This is Multidimension Array


orgarr[3] Thank u

Here array b is stored in the 2nd indexed location of the orgarr array, now the individual element of
the 2nd array can be accessed as

for (i=0; i< b.length;i++)


{
document.write( orgarr[2][i]+ "<br>")
}

the output will be

this
Is
multidimension
array

Date Object: JavaScript Clock 1


Using the date object and its methods to create a clock

Now, you would like to have a clock for your web page- but how do you go about coding such a
clock with JavaScript? Using the date object and some of its methods, you can create your own
javascript clock customized to your needs. Our script here will create a fairly simple clock, but we
will also discuss some of the other methods of the date object you may wish to use to create and
customize your own clock.

To begin, we must discuss the javascript date object. This works a bit differently than the pre
defined functions we have used in past scripts. To use the method functions of the date object,
we must create what is called an instance of the date object. Think of an instance of the date
object as a variable or placeholder that allows us access to the member functions of the date
object. Why think of it as a variable? Well, to create an instance of the date object, you define it
as a new variable- but with a little twist:

var thetlme = newDateQ;

As you can see, we are not assigning the new variable a direct value. Instead, the code above
defines the variable as a new instance of the date object. This means we can use this variable in

22 Training Cycle 4
Wintech Computers Javascript

order to access the method functions of the date object. What are the. method functions? Well,
here a list of some of them:

Method Function:

What the Function Does

Methods Desc

getHours() Returns the current number of hours into the


day: (0-23)

getMinutes() Returns the current number of minutes into


the hour: (0-59)

getSeconds() Returns the current number of seconds into


the minute: (0-59)

getDay() Returns the number of days into the week:


(0-6)

getMonth() Returns the number of months into the year:


(0-11)

getYear() Returns the number of years into the cen


tury: (0-99)

These are not all of the method functions, but they are enough to create a decent clock. Our
example clock for this tutorial will only use the first three, but the rest might be useful to you to
customize your clock. Now, suppose we want to get the number of hours into the day. We could
do this by defining a variable and giving it the value of the getHours() method function. However,
the following line will give you an error:

var nhours=getHours();

Why? Well, remember that the getHours() function is a method function of the date object. In
order to get that value for our variable, we have to use our instance of the date object we created
earlier:

var thetime=new Date();


var nhours=thetime.getHours();

This is part of object-oriented programming. Once we have created an object, we are able to
access its member functions with what is called "the dot operator". By placing the dot between our
object name (thetime) and its member function, we are able to execute the member function. In
this case, the function simply returns a value (the number of hours into the day). We are using this
Training Cycle 4 ,23
Wintech Computers Javascript

value as the value of our new variable, nhours.


We have used the dot operator in the past, when we used the document.write() function. The
write() function is a member function of the document object, and the function writes text to the
screen.

An advantage of using objects is that objects can hold multiple values, where variables can only
keep one value at a time. An object can also use any member functions it may have, like we did
above. So, our date object named the time can use all of the member functions. Now we can start
getting the rest of the values for our clock. Let's get the hours, minutes, and seconds:

var thetime=new DateQ;


var nhours=thetime.getHours();
var nmins=thetime.getMinutes();
var nsecn=thetime.getSeconds();

See how we were able to use our object named thetime to grab three different values? It's almost
fun, then again...yes, a bit more complicated than having a pre-defined object to use.

With these values and a bit of extra coding, we can create a clock like the one below:

Current Time:

12: 57:01 pm

Not bad, but now we must get into the extra coding we need to get the clock running smoothly.
Remember, thetime.getHours() returns the number of hours into the day. This value is a number
between 0 and 23. What can we do if we do not want a 24 hour clock, if we don't want 11:24 P.M.
to be 23:24? To get around that, we need some code that will change any number over 12 back
to 1,2,3,4, and so on. We can do this by subtracting 12 from our variable nhours when it has a
value greater than 12:

if(nhours>=13) nhours-=12;

nhours-=12;

is shorthand for:
nhours=nhours-12;

Also, if the hour is 0, we know that is 12 A.M., so we need to make the zero into a 12.

if
(nhours==0) nhours=12;

Now, when the number of hours is 14, the script changes it to


14-12=2. Just what we needed.

24 Training Cycle 4
Wintech Computers Javascript

We don't have the same problem for the minutes and seconds, but they present a problem of
their own. Suppose the number of minutes into the hour is 32. This value is fine, the script will
display a 32. However, what if the value is 2? The script would display something like this:

11:2

What? Yes, we need a way to get a zero in there so the clock is readable. We want it to say
11:02. So now we need something to add in a zero before the 2 if the number of minutes (nmins)
is less than 10. Let's try this:

if(nmins<10)
nmins="0*+nmins;

This code will add in the character 0 in front of the 2 if the number of minutes is less than ten.
Another little problem out of the way, but we will also need to do this for the seconds:

if(nsecn<10)
nsecn="0"+nsecn;
if(nmins<10)
nmins="0'+nmins;

This clock still has another value we need to get. The clock displays A.M. or P.M. for morning and
evening hours. This isn't to terrible. We can define another variable, let's call it AorP. We need the
value to be "P.M." if the hour is greater than 12, and "A.M." otherwise.

Here we go:

\f (nhours>=12)
AorP=T.M.";
else
AorP=HA.M.u:

Training Cycle 4 25
Wintech Computers Javascript

One problem though. You need to place this section of code before our code that changes the
clock to a twelve hours system. Otherwise, the hours will never get past 12, and it will always read
A.M. Why? This is because when we change the clock to the twelve hours system, we change the
value of nhours so that it is 0-12 in all cases. So, we must get our AorP value before we change
the time system.

Now, I'll give you the code for the script:

<HTML>
<HEAD>
<SCRIPT language="JavaScript">
<!--
function startclock()
{
var thetime=new Date();

var nhours=thetime.getHours();
var nmins=thetime.getMinutes();
var nsecn=thetime.getSeconds();
var AorP=" ";

if (nhours>=12)
AorP="P.M.";
Else
AorP="A.M.";

if (nhours>=13)
nhours-=12;

if (nhours==0)
nhours=12;

if (nsecn<10)
nsecn="0"+nsecn;

if (nmins<10)
nmins="0"+nmins;

document.clockform.clockspot.value=nhours+":"+nmins+":"+nsecn+" "+AorP;

setTimeout('startclock()',1000);

26 Training Cycle 4
Wintech Computers Javascript

</SCRIPT>
</HEAD>
<BODY onLoad="startclock()">
<FORM name="clockform">
Current Time: <INPUT TYPE="text" name="clockspot" size="15">
</FORM>
</BODY>
</HTML>

The output will be as :


jCARolandUime Miciosolt Internet Lxpluiei urns

File d* View fio Favorite* Help

;^
Stop
W ffl
Refresh
Home
~r Seaich
W"Favorite*
a" Hatory
0" Channels
~~a -
; Fufccrean Mai
,Address |#] C:\Roland\Time html 3iJ|jri|u

Current Time |1:08:25 P.M.

d
gJDone JHJ My Computer

You may have noticed we are accessing a form value and changing it in this line:

Document.clockform.clockspot.value=nhours+":M+nmins+":"+nsecn+" "+AorP;

So, you now know we need a form in the body of the document. Here is the one that goes with
the
script:

<FORM name="clockform">
Current Time: <INPUT TYPE="text" name="clockspot" size="15">
</FORM>

Training Cycle 4 27
Wintech Computers Javascript

Also, you can see that we use the setTimeout() function to run our startclock() function again after
one second. In this way, the clock will refresh every second so that you get a constantly running
clock with the seconds ticking away.
Of course, how do we get the thing started to begin with? The browser won't just run the
startclockO function on its own. It needs some kind of event to happen. Well, how about when the
page loads? Excellent choice, let's use the onLoad event. The onLoad command is used as an
attribute in the body tag, much like defining a text color:

<BODY text="lime">

I'm not sure I could handle that text color for long, but now we can see how the onLoad command
will be put to work:

<BODY onLoad="startclock()">

Nice, isn't it? The command works like the other event handlers, we are able to use it to call our
javascript function. This is what gets the clock ticking. Now, you can go make use of this clock if
you need one. Otherwise, you have gotten a rather unorthodox introduction to objects and object-
oriented programming. Well, maybe

String Object
The string object type provides a set of methods for manipulating strings. These methods are
summarized in the Table given below, Any JavaScript string value or variable containing a string is
able to use these methods.

Table : String methods:

Method Description

anchor ( anchorName ) This display the string as a hypertext anchor


with the specified anchor name . The string
can be written to a document using the
document.write () or document.writeln()
methods.

big() Causes the string to be displayed using the


big HTML tags.

blink() Causes the string to be displayed using the


blink HTML tag.

bold() Causes the string to be displayed using bold


HTML tags Returns the string that consist of
the character at the specified index of the
string to which the mehtod is applied.

28
Training Cycle 4
Wintech Computers Javascript

fixed() Causes the string to be displayed using the


teletype HTML tags.

fontColor(color) Causes a string to be displayed in a specified


color.

fontSize(size) Causes a string to be displayed in a specified


font size.The size parameter must be in
between 1-7

italics() Causes a string to be displayed using italic


HTML tags.

links(HREF) Causes a string to be displayed as a


hypertext link to the URL specified by the
HREF parameter.

small() Causes a string to be displayed using the


small HTML tags

split(seperater) Separates a string into an array of substrings


based upon the seperater.

strike() Causes a string to be displayed using


strikeout HTML tags.

sub() Causes a string to be displayed using sub


script HTML tags.

sup() Causes a string to be displayed using the


superscript HTML tags.

toLowerCase() Returns a copy of the string converted to


lower case.

toUpperCase() Returns a copy of the string converted to


upper case.

Training Cycle 4 29
Wintech Computers Javascript

THE MATH OBJECT:


The math object provides a standard library of mathematical constants and functions.

Tablel : Math Properties.

Property description

E Eulers constant

LN2 Log of two

LN10 Log of ten

LOG2E Lof of E base two

LOG10E Log of E base 10

PI The constant pie

SQRT1_2 Square root of half

SQRT2 Square root 2

TABLE 2: MATH Methods

Method Description

abs(x) Absolute value of x

ceil(x) Return the least interger that


is greater or equal to x

cos(x) Returns the cossine of x

floor(x) Returns the greatest interger


that is less than or equal to x

log(x) Natural logof x

max(x,y) Greater of x and y

min(x.y) Lesser of x and y

pow(x.y) X raise to y

random() Random number between o-1

round(x) Closest integer next to x

sin(x) Sin of x

sqrt(x) Square root of x

tan(x) Tangent of x'

30
Training Cycle 4
Training Cycle - 5
Wintech Computers Javascript

Windows and on-the-fly documents

Creating windows :
Opening new browser windows is a great feature of JavaScript. You can either load a new document
(for example a HTML-document) to the new window or you can create new documents (on-the-fly).
We will first have a look at how we can open a new window, load a HTML-page to this window and
then close it again.
The following script opens a new browser window and loads a meaningless page:

<html>
<head>
<script language="JavaScript">
<!-hide

function openWin() {
myWin= open("bla.htm");
}

//-->
</script>
</head>
<body>

<form>
<input type="button" value="Open new window" onClick=:"openWin()">
</form>

</bpdy>
</html>

The output will be as:

Training Cycle 5 31
Wintech Computers Javascript

Netscape
|ie d* Vjew fio Communicator Help

3
Back Forward Reload Home Seajcti
^'Bookmark* ,& Locafertj(ie.///C|^oland/win.htrnl
a
fr*EU

You can control the appearance of the new window. For example you can decide if the window

Nelsctipe nRO
fite fid* yiew fio Communicator Help


Back
-^
Forwaid
m
Reload
i&
Horn* Swatch
(ttl
Natecapa Punt

NEW WINDOW

This is opened in new


window

r
liiliiiiijimii
The page bla.html is loaded into the new window through the open() method, shall have a statusbar,
a toolbar or a menubar. Besides that you can specify the size of the window.The following script
opens a new window which has got the size 400x300. The window does not have a statusbar,
toolbar or menubar.

32 Training Cycle 5
Wintech Computers Javascript

<html>
<head>
<script language="JavaScrlpt">
<!-hide

function openWin2()
{
myWin= open("bla.htm", "displayWindow",
"width=400,height=300,status=no,toolbar=no,menubar=no");
}

</script>
</head>
<body>

<form>
<input type="button"
t value="Open new window" onClick="openWin2()">
</form>

</body>
</html>

You can see that we specify the properties in the string


width=400,height=300,status=no,toolbar=no,menubar=no".

Please note that you must not use spaces inside this string!

Training Cycle 5
Wintech Computers Javascript

Here is a list of the properties a window can have:

Properties Value

Directories yeslno

Height Number of pixels

Location yeslno

Menubar yeslno

Resizable Yeslno

Scrollbars yeslno

Status yeslno

Toolbar yeslno

Width number of pixels

Height number of pixels

Some properties have been added with JavaScript 1.2 (i.e. Netscape Navigator 4.0). You cannot
use these properties in Netscape 2.x or 3.x or Microsoft Internet Explorer 3.x as these browsers do
not understand JavaScript 1.2. Here are the new properties:

Properties Value

AlwaysLowered yeslno

AlwaysRaised yeslno

Dependent yeslno

Hotkeys yeslno

InnerWidth number of pixels(replaces width)

InnerHeight number of pixels(replaces height)

34 Training Cycle 5
Wintech Computers Javascript

OuterWidth number of pixels

OuterHeight number of pixels

ScreenX position in pixels

ScreenY position in pixels

Titlebar yeslno

z-lock yeslno

You can find an explanation of these properties in the JavaScript 1.2 guide. I will have anexplanation
and some examples in the future. With the help of these properties you can now define at which
position a window shall open. You cannot do this with the older versions of JavaScript.

The name of a window

As you have seen we have used three arguments for opening a window:

MyWin= openfbla.htmr, "displayWindow",


"width=400,height=300,status=no,toolbar=no,menubar=no");

What is the second argument for? This is the name of the window. We have seen how to use the
target-property earlier. If you know the name of an existing window you can load a new page to itwith

<a href="bla.html" target="displayWindowM>

Here you need the name of the window (if the window does not exist, a new window is created
through this code). Please note that myWin is not the name of the window. You can just access the
window through this variable. As this is a normal variable it is only valid inside the script in which it is
defined. The window name (here displayWindow) is a unique name which can be used by all
existing browser windows.

Training Cycle 5 35
Wintech Computers Javascript

Closing windows :
You can close windows through JavaScript. For this you need the close() method. Let's open a new
window as shown before. In this window we load the following page:

<html>
<script language*"JavaScrlpt">
<!-hide

function clo8elt()
{
close();
}

</script>

<center>
<form>
<input type=button value="Close it" onClick="closelt()">
</form>
</center>
</html>

If you hit the button in the new window the window is being closed. open() and close() are
methods of the window-object. Normally we should think that we have to writwlndow.open() and
wlndow.close() instead of open() and close(). This is true - but the window-object is an exception
here. You do not have to write window if you want to call a method of the window-object (this is only
true for this object).

Creating documents on-the-fly :


We are coming now to a cool feature of JavaScript - creating
documents on-the-fly. This means you can let your JavaScript code create a new HTML-page.
Furthermore you can create other
documents - like VRML-scenes etc.. You can output these documents in a separate window or in a
frame. First we will create a simple HTML-document which will be displayed in a new window. Here
is the script we are going to have a look at now.

<html>
<head>
<script languages"JavaScript">
<!-hide

function openWin3()
{
myWin= open("\ "displayWindow",

36 Training Cycle 5
Javascript
Wintech Computers

"width=500,height=400,status=yes,toolbar=yes,menubar=yes");

// open document for further output


myWin.document.open();

// create document
myWin.document.write("<htmlxheadxtitle>On-the-fly");
myWin.document.write("<Aitle></headxbody>");
myWin.document.write("<centerxfontsize=+3>");
myWin.document.write("This HTML-document has been created ");
myWin.document.write("with the help of JavaScript!");
myWin.document.write("</fontx/center>");
myWin.document.write("</body></html>");

// close the document - (not the window!)


myWin.document.close();
}

//-->
</script>
</head>
<body>

<form>
<input type=button value="On-the-fly" onClick="openWin3()">
</form>

</body>
</html>

Let's have a look at the function winOpen3(). You can see that we open a new browser window first.
As you can see the first argument is an empty string "" -this means we do not specify an URL. The
browser should not just fetch an existing document - JavaScript shall create a new document. We
define the variable myWin. With the help of this variable we can access the new window. Please
note that we cannot use the name of the window (displayWindow) for this task. After opening the
window we have to open the document. This is done through:

// open document for further output

myWin.document.open();
We call the open() method of the document-object -this is a different method than the open() method
of the window-object! This command does not open a new window - it prepares the document for
further output. We have to put myWin before the document.open() in order to access the new win
dow. The following lines create the document with document.write():

37
Training Cycle 5
Wintech Computers
Javascript

// create document
myWin.document.write("<htmlxheadxtitle>On-the-fly");
myWin.document.write("</titlex/headxbody>");
myWin.document.write("<centerxfont size=+3>");
myWin.document.write("This HTML-document has been created ");
myWin.document.write("with the help of JavaScript!");
myWin.document.write("</fontx/center>");
myWin.document.write("</bodyx/html>");

You can see that we write normal HTML-tags to the document. We create HTML-code! You can write
any HTML-tags here.After the output we have to close the document again. The following code
does this:

// close the document - (not the window!)

myWIn.document.closeO;

As Itold you before you can create documents on-the-fly and display them in aframe as well If you
for example have got two frames with the names framel and frame2 and want create a new docu
ment in frame2 you can write the following in framel:

Parent.frame2.document.open();

Parent.frame2.document.write("Here goes your HTML-code");


Parent.frame2.document.close();

38
Training Cycle 5
Training Cycle - 6
Wintech Computers Javascript

Frames

Creating Frames :
An often asked question is how frames and JavaScript work together. First I want to explain what
frames are and what they can be used for. After this we will see how we can use JavaScript In
combination with frames. The browser window can be split up into several frames. This means a
frame is a square area inside the browser window. Each frame displays its own document (most of
the time HTML-documents). So you can for example create two frames. In the first frame you load
the homepage of Netscape and in the second frame you load the homepage of Microsoft.
Although creating frames is a HTML-problem Iwant to describe the basic things. For creating
frames you need two tags: <frameset> and <frame>. AHTML-page creating two frames might look
like this:

<html>
<frameset rows="50%,50%">
<frame src="page1 .htm" name="frame1 ">
<frame src="page2.htm" name="frame2">
</frameset>
</html>

This will produce twp frames. You can see that we use the rows property in the <frameset> tag.

!to <* yi*w So Camraunoatsi U*lp

J"'**
li lash
v"'" Raioad
a' &
Ham*
"**
tarct
tfii'":'*1
Mio>ti
'"*'
SmhiIIv a
l[| ^J"ookJOk. Ji. Lacman[lm///AI/iclantVliminMmt " ""Trn"nr'2j Gp-wh*.*?**

This is a sample page 1


>

This is a sample page 2


>

HH-a>t ioojBi*Oon " I .j^ 'j^j ^p* j( ^ |


atmtl u>JIpi*no-iincj ayMko^iw<d | Bgw^oaimow... |HBtH^.cp jjrj p.p.1nMe.d| pg<c<* nap. I ;fl| 9tw

This means the two frames lie above each other. The upper frame loads the HTML-page pagel .htm
and the lower frame displays the document page2.htm. If you push the button you can see what this
looks like:

If you want to have columns instead of rows you write cols instead of rows in the <frameset> tag.
The "50%,50%" part specifies how large the two windows are. You can also writS50%,*" if you do

Training Cycle6 39
Wintech Computers Javascript

not want to calculate how large the second frame must be in order to getOO%. You can specify the
size in pixels by omitting the % symbol.
Every frame gets an unique name with the name property in the <frame> tag. This will help us when
accessing the frames through JavaScript. You can have several nested <frameset> tags. I've found
this example in the documentation provided by Netscape (I just modified it a little bit):

<frameset cols="50%,50%">
<frameset rows="50%,50%">
<frame src="cell.htm">
<frame src="cell.htm">
</frameset>
<frameset rows="33%,33%,33%">
<frame src="cell.htm">
<frame src="cell.htm">
<frame src="cell.htm">
</frameset>
</frameset>

Have a look at this example:

Top of Form 2
You can set the size of the border through the border property in the <frameset> tag. border=0
means that you do not want to have a border (does not work with Netscape 2.x).
Frames and JavaScript
Now we want to have a look at how JavaScript 'sees' the frames in a browser window. For this we
are going to creat two frames as shown in the first example of this part. We have seen that JavaScript
organizes all elements on a webpage in a hierarchy. This is the same with frames.

The following image shows the hierarchy of the first example of this part:

At the top of the hierachy is the browser window. This window is split up into two frames. The window
is the parent in this hierarchy and the two frames are the children. We gave the two frames the
unique names framel and frame2. With the help of these names we can exchange information
between the two frames. A script might have to solve the following problem: The user clicks on a link

browser parent
window

/ \
framel frame2 children
pagel.htm page2.htm

in the first frame - butthe page shall be loaded in the second frame rather than in the first frame. This
can for example be used for menubars (or navigationbars) where one frame always stays the same
and offers several different links to navigate through a homepage. We have to look at three cases:

40 Training Cycle 6
Wintech Computers Javascript

parent window/frame accesses child frame


child frame accesses parent window/frame
child frame accesses another child frame

From the window's point of view the two frames are called framel and frame2. You can see in the
image above that there is a direct connection from the parent window to each frame. So if you have
a script in the parent window - this means in the page that creates the frames - and you want to
access the frames you can just use the name of the frame. For example you can write:

browser
window

/
framel
pagel.htm

frame2.document.write("A message from the parent window.");

Sometimes you want to access the parent window from a frame. This is needed for example if you
want to remove the frames. Removing the frames just means to load a new page instead of the page
which created the frames. This is in our case the page in the parent window. We can access the
parent window (or parent frame) from the child frames with parent. In order to load a new document
we have to assign a new URL to location.href. As we want to remove the frames we have to use the
location-object of the parent window. As every frame can load its own page we have a different
location-object for each frame. We can load a new page into the parent window with the command:

parent.location.href= "http://...";

browser
window

\
frame 2
page2.htm

Very often you will be faced with the problem to access one child frame from another child frame. So
how can you write something from the first frame to the second frame - this means which command
do you have to use in the HTML-page called page1.htm? In our image you can see that there is no
direct connection between the two frames. This means we cannot just call frame2 from the frame
framel as this frame does not know anything about the existence of the second frame. From the
Training Cycle 6
41
Wintech Computers
Javascript

parent window's point of view the second frame is called frame2 and the parent window is called
parent seen from the first frame. So we have to write the following in order to access the document-
object of the second frame:

parent.frame2.document.write('Hi, this is framel calling.');

browser
window

/ Sparertframr^s,.
framel frame2
pagel.htm page2.htm

Navlgationbars :

Let's have a look at a navigationbar. We will have several links in one frame. If the user clicks on
these links the pages won't show up in the same frame - they are loaded in the second frame.
Here is the example:

First we need a script which creates the frames. This document looks like the first example we had
in this part:

frames3.html

<html>
<frameset rows="80%,20%">
<frame src="start.htm" name="main">
<frame src="menu.htm" name="menu">
</frameset>
</html>

The staithtm page is the entry page which will be displayed in the main frame at the beginning.
There are no special requirements for this page. The following page is loaded into the frame

menu.html
<html>
<head>
<script language="JavaScript">
<!-- hide

function load(url) {
parent.main.location.href= uii;

42 Training Cycle 6
Wintech Computers Javascript

</script>
</head>
<body>

<a href="javascript:load('first.htm')">first</a>
<a href="second.htm" target="main">second</a>
<a href="third.htm" target=M_top">third</a>
</body>
</html>

Here you can see different ways for loading a new page into the frame?a/n. The first link uses the
function load(). Have a look at how this function is called:

<a href="javascript:load('first.htm')">first</a>

You can see that we can let the browser execute JavaScript code instead of loading another page -
we just have to usejavascript: in the href property. You can see that we write Y/rsf. Mm' inside the
brackets. This string is passed to the functionfoaoYJ. The function loadQ is defined through:

function load(url)
{
parent.main.location.href= url;
}

There you can see that we write url inside the brackets. This means that the string 'first1.htm' is
stored in the variable url. Inside \beload() function we can now use this variable. We will see further
examples of this important concept of variable passing later on.
The second link uses Xhetarget property. Actually this isn't JavaScript. This is a HTML-feature. You
see that we just have to specify the name of the frame. Please note that we must not put parent
before the name of the frame. This might be a little bit confusing. The reason for this is that target is
HTML and not JavaScript.The third link shows you how to remove the frames with the target property.
If you want to remove the frames with thdoadQ function you just have to write parent.location.href=
url inside the function. So which way should you choose? This depends on your script and what you
want to do. The target property is very simple. You might use it if you just want to load the page in
another frame. The JavaScript solution (i.e. the first link) is normally used if you want to do several
things as a reaction to the click on the link. One common problem is to load two pages at once in two
different frames. Although you could solve this with thetarget property using a JavaScript function is
more straightforward. Let's assume you have three frames ealledframe1,frame2 and frame3. The
user clicks on a link inframel. Then you want to load two different pages in the two other frames.
You can use this function for example:

Training Cycle 6 43
Wintech Computers Javascript

function loadtwo()
{
parent.framel .location.href- "first.htm";
parent.frame2.location.href= "second.htm";
}

If you want to keep the function more flexible you can use variable passing here as well. This looks
like this:

function loadtwo(url1, url2)


{
parent.framel .location.href= url1;
parent.frame2.location.href= url2;
}

Then you can call this function with loadtwoffirst.htm", "second.htm") or loadtwo("third.htm",
"forth.htm"). Variable passing makes your function more flexible. You can use it over and over again
in different contexts.

Event Handling:

The Concept
We've discussed objects and methods. Now let's start playing withevents, but first allow me to
throw a curve into the process. Events and Event Handlers are JavaScript, but they are "built-in" to
HTML code rather than standing alone like the last two scripts we created. Events are to be embedded
so they don't require the <SCRIPT> and </SCRIPT> commands. They themselves are not scripts
but rather small interfaces allowing for interaction between your page and your reader.
Think of Events as things that happen. They add life and interest to your Web Site. They're
things that make your viewers go "Ooooooo" without your having to create large JavaScripts. There
are multiple events and we'll get to them, but let's start with one of the most popular ones first,
onMouseOver.

The Script
<A HREF="http://www.htmlgoodies.com"
onMouseOver="window.status='Go to the Goodies Home Page';
return true">Click Here</A>
The text above should go all on one line. I broke it into these section to show it all.

Deconstructing The Script


Knowing what you already know, this one just about explains itself. So let's look at it quickly and then
start to play around with it.First off,"onMouseOver" (notice the capitalization pattern) is an Event
Handler of the hypertext Link. Does that make sense? I'm using it inside of a hypertext link.
The format for the hypertext link remains the same. You use the same commands and the
same double quotes. The Event Handler is stuck in right after the URL address. See that above?
The event is called for by denoting "onMouseOver=". The pattern should look somewhat familiar

44 Training Cycle 6
Wintech Computers Javascript

now, two items separated by a period. So far that has meant one is an object and one is a method.
Not here. In this case "window" is an object, it exists, "status" is what's known as a "property" of the
window. It is a smaller section of the window denoting where the following text should go. I usually
keep it all straight by thinking that a method will usually be in the form of a verb like "write" or "get".
A property is a noun that exists as a smaller part of the item before the dot. If "window" has a status
property, that must mean that other properties of the window can be altered. It does. But let's not get
ahead of ourselves here. We are currently concerned with the "window", and its "status" section.
The "window.status" is also followed by an equals (=) sign denoting what follows is what should
happen. In this case, what follows is text IN SINGLE QUOTES. That text will show up in the status
bar when you roll your mouse over the hypertext link.
Please notice once again that a semicolon ends the command line.return true Those extra two
words have quite a bearing on what will happen when the mouse rolls over the link. If the words are
present, then the script checks to see if a status bar is present. If the return is true, then the event
occurs. Notice when you roll your mouse over the link, the text in the status bar is locked in. It doesn't
change if you roll over the link again and again. (If you refresh the page, you'll be able to see that.)
But what if we lose those two words? Well, let's think it out. If there is no check of the status bar, then
the default will occur. If you remember your HTML, the default is to display the URL that the link is
pointing to. Then after the mouse is off the link, the event will take place. And since there is no
check, the event will occur every time you pass the mouse over the link. It's actually a better effect
in my opinion. Here's the same exact link as above. I just simply eliminated the two words "return
true". Reload the page, and then roll your pointer back and forth over this link:
Cool, huh?

Other Properties, Other Uses :


Let's get back to that "properties" thing we talked about earlier. If the window has properties,
other objects must have properties too. How about a page's background color? That would be a
property, wouldn't it? In HTML the command to change the background color is BGCOLOR. Same
here, except now we're concerned again with capitalization. In JavaScript, it's writtertbgColor".
(Capital "C") So let's think through creating a link that would change the window's background color
using an onMouseOver event.

1. First off, this is a link so it's a pretty good bet that the format is the same as the format above.
We'll keep it.
2. Are we changing the window or are we change our old standby, the document? Well, where
does the "bgcolor" command go when you write a web page? In the document. That must be the
object we're concerned with. Let's change out "window" now with "document".
3. We want to change the document object's background, so let's change out "status" with "bgColor".
4. We no longer want text to appear, so let's change that text with a color. We'll use "pink".
5. When we move the mouse over the link we probably want the color to stay no matter if the
mouse runs over the links again or not, so we'll need to re-enter the "return true" after the
semicolon.

Training Cycle 6 4-
Wintech Computers Javascript
Here's what we got...
<AHREF="http://www.htmlgoodies.com" onMouseOver="window.status='Go to the Goodies
HomePage'; return true">Click Here</A>
...andhere's what itgives us. Roll yourpointer over the link.

But IWant Both Effects OK, how do you think you'd do that? Let's think it through:

Common sense would suggest you write two onMouseOver commands. Let's try that.
The two commands are not separate from each other. We want them to occur at the same time
so we cannot separate then using a semicolon because we know a semicolon is a statement
terminator.
New Rule: Use a comma when separating multiple JavaScript events.
And what about all those pesky quotes? Remember the quotes go around single items like text.
Well, we want these two onMouseOver commands to happen as one so we only need quotes at
the very beginning of the first one and the very end of the second one. That way the quotes
surround it all showing it to the browser as if it's one event. With me?
We'll probably still need the single quotes though...

Here's what we got...


<AHREF="http://www.htmlgoodies.com"onMouseOver="document.bgColor='pink\
onMouseOver=window.status='Go to the Goodies Home Page'; return true">
Click Here</A>
...and here's what we get:

These Event Handlers are great and there are a slew of them. Next primer we'll go over a handful
and how to combine them to make multiple events.
You may have noticed that the primers are starting to "think things through." a bit. Please remember
that this language is very logical, later in this series, there will be a lesson just on the hierarchy of
items because the language is so logical. Just for now, try taking a few minutes before you write and
think out what must happen for your idea to come to life in script.

Your Assignment
Let's see if I can't trip you up on this one. I'm going to give you a new method, tMert(). What it
does is pop up a small dialog box with text written across an OK button. See if you can get the alert
box to pop up when your mouse rolls across a hypertext link. Here's the format:
alert('text that appears on the alert box');
Think it through, what must happen first, second, and so on. It's actually quite simple, not that that's
a hint or anything.

46 Training Cycle 6
Training Cycle - 7
Wintech Computers Javascript

Forms Interaction Of Html And Javascript Objects

Beginning With Forms


You can do many things with javascript using your forms. Great, you say, but where does one figure
out how to access those form elements with javascript?

You can access various parts of a form by naming them, in turn, you must give the form a name,
because it will be part of what you need to get to what you want. Take a look at the. following form
code:

<FORM name="coolform">
<INPUT type="text" name="cooltext" value="l am Cool!!!" size="20">
</FORM>

This code creates a little input box for text. The value="l am Cool!!!" attribute gave this box an initial
value, which can be changed if the viewer types something else OR if you were to change it
with javascript! Here is what the box looks like:

Now, recall from the code above that we gave this form and the box names. This is how we will get
to them with javascript. Now, the input box is part of the form, and the form is part of the document.
If you remember the document.location object from a previous section, you know we can access
parts of the document and change them, (document.location allowed us to change the url and go to
a different page). So, to access the form, we would use:

document.coolform

Remember, the name of our form is "coolform" from the name="coolform" attribute inside the form
tag. Now, to access the text box, you would add on the name of the text box:

document.coolform.cooltext

Again, the name of the text box was used. We had named it "cooltext". Now, we can access the
value of the text box, which is what is in the value=" " attribute. So, if we wanted to get to the value
of the box....the text "I'm Cool!!!", we would add the word "value" to the end of the list:

document.coolform.cooltext.value

Notice that each time we add something to the list, it is separated from the others by a dot. This is
because we are using "objects" to get what we need. The document, the form, and the text box are
all objects in the browser. The addition of the "value" at the end lets us access the value of the text
box object. The text box object was part of the form object, and the form object yes, it is part of
the document object!

Now that we can get to the value of the text box, we should be able to do something with it, right?....
Training Cycle 7 47
Wintech Computers Javascript

Getting the idea? Yes, let's try to change the text in the box! One way to do this is to let the viewer
click a button and change the text when the button is clicked. For the above form, we can simply add
a button at the end, and use the old "onClick" function to perform a javascript. Here is the sample
code:

<FORM name="coolform1">
<INPUT type="text" name="cooltext" value="l am Cool!!!" size="20">
&nbsp;&nbsp;
<INPUT type="button" name="change" value="Click to see new text!"
onClick="document.coolform1.cooltext.value='You are cool too!!'">
</FORM>

Notice that I gave this form a new name (coolforml). If you have more than one form on the same
page, be sure they all have different names. Otherwise when you try to access the form, the browser
won't know which form you want to go to, because they have the same name! So This gives you
the following box and button. If you are feeling rather cool today, click on the button to change the
text in the text box....

You can also change the text on a button that is clicked in the same way:

<FORM name="coolform2">
<INPUT type="button" name="coolbutton" value="Click Here and see what I have to say!"
onClick="document.coolform2.coolbutton.value='Who told you to Click ME?'">
</FORM>

Be sure to make the initial set of text in the value=" " attribute longer than the text you want to
change it to. The button will need the room to write your new text! Try out I

Validating form input:


Forms are widely used on the Internet. The form input is often being sent back to the server or via
mail to a certain e-mail account. But how can you be certain that a valid input was done by the user?
With the help of JavaScript the form input can easily be checked before sending it over the Internet.
First I want to demonstrate how forms can be validated. Then we will have a look at the possibilties
for sending information over the Internet.

First of all we want to create a simple script. The HTML-page shall contain two text-elements. The
user has to write his name into the first and an e-mail address into the second element. You can
enter anything into the form elements and then push the button. Also try to enter nothing and then
push the button.

48 Training Cycle 7
Wintech Computers
Javascript

Enter your name:

Enter your e-mail address:

Concerning the first input element you will receive an error message when nothing is entered Any
input is seen as valid input. Of course, this does not prevent the user from entering any wrong
name.The browser even accepts numbers. So if you enter '17' you will get 'Hi 17!'. ^ this might not
be agood check. The second form is alittle bit more sophisticated. Try to enter asimple string -your
name for example. It won't work (unless you have aOin your name...). The criteria for accepting the
input as avalid e-mail address is the o. Asingle @will do it -but this is certainly not very meaning
ful. Every Internet e-mail address contains a @so it seems appropriate to check for a here
What does the script for those two form elements and for the validating look like? Here it goes-
<html>
<head>
<script language="JavaScript">
<!-Hide

function testl(form)
{
if (form.textl .value == "")
alertfPlease enter a string!")
else {
alertfHi "+form.text1 .value+"! Form input ok!");
}
}

function test2(form) {
if (form.text2.value == "" II
form.text2.value.indexOf('@', 0) == -1)
alert("No valid e-mail address!");
else alert("OK!");
}
//-->
</script>
</head>

<body>
<form name="first">
Enter your name:<br>
<input type="text" name="text1 ">

Training Cycle 7
49
Wintech Computers Javascript

<input type="button" name="button1" value="Test Input" onClick^"test1 (this.form)">


<P>
Enter your e-mail address:<br>
<input type="text" name="text2">
<input type="button" name="button2" value="Test Input" onClick="test2(this.form)">
</body>
</html>

First have a look at the HTML-code in the body-section. We just create two text elements and two
buttons. The buttons call the functions test1(...) or test2(...) depending on which button is pressed.
We pass this.form to the functions in order to be able to address the right elements in the functions
later on. The function testl (form) tests if the string is empty. This is done via if (form.textl .value ==
"")... 'form' is the variable which receives the 'this.form' value in the function call. We can get the
value of the input element through using 'value' in combination with form.textl. In order to look if the
string is empty we compare it with "". If the input string equals "" then no input was done. The user
will get an error message. If something is entered the user will get an ok.
The problem here is that the user might enter only spaces. This is seen as a valid input! If you want
to, you can of course check for these possibilities and exclude them. I think this is quite easy with the
information given here. Now have a look at the test2(form) function. This function again compares
the input string with the empty string "" to make sure that something has been entered. But we have
added something to the if-command. The II is called the OR-operator. You have learned about it in
part 6 of this introduction. The if-command checks if either the first or the second comparison is true.
If at least one of them is true the whole if-command gets true and the following command will be
executed. This means that you will get an error message either if your string is empty or if there isn't
a @ in your string. The second operation in the if-command looks if the entered string contains a @.

Checking for certain characters


Sometimes you want to restrict the form input to certain characters or numbers. Just think of a
telephone number - the input should only contain digits (we assume that the telephone number
does not contain any characters). We could check if the input is a number. But most people use
different symbols in their telephone number - for example: 01234-56789, 01234/56789 or 01234
56789 (with a space inbetween). The user should not be forced to enter the telephone number
without these symbols. So we have to extend our script to check for digits and some symbols. This
is demonstrated in the next example which is taken from my JavaScript book:

Telephone:
Here is the source code:

<html>
<head>
<script language="JavaScript">
<!-hide

A*****************************************************
II
II ********** ********************************************

50 Training Cycle 7
Javascript
Wintech Computers

var a= new Array("1","2","3","4","5","6","7","8","9","0",T,"-","");


function check(input)
{
var ok = true;
for (var i = 0; i < input.length; i++)
{
var chr = input.charAt(i);
var found = false;
for (var j=0;j<a.length;j++)
{

if (chr==a[j])
{

found = true;
}
}
if (Ifound)
ok = false;
}

return ok;
}

function test(input)
{

if (icheck(input))
{

alert("lnput not ok.");


}
else

{
alert("lnput ok!");
}
}

// ->
</script>
</head>

<body>
<form>

51
Training Cycle 7
Wintech Computers Javascript

Telephone:
<input type="text" name="telephone" value="">
<input type="button" value="Check" onClick="test(this.form.telephone.value)">
</form>
</body>
</html>

The function test() specifies which characters are valid.

Submitting form input


What different possibilities do exist for submitting form input? The easiest Way is to submit the form
input via e-mail. This is the method we are going to look at a little bit closer.
If you want the form input to be handled by the server you need to use CGI (Common Gateway
Interface). This allows you to process the form input automatically. The server might for example
build up a database from the input received by some customers. Another example are index-pages
like Yahoo. They usually have a form for making a search in their database. The user gets a re
sponse quickly after the submit button was hit. He does not have to wait until the people maintaining
this server read the input and then look up the information requested. This is done automatically by
the server. JavaScript cannot do things like this.
You cannot create guestbooks with JavaScript because JavaScript isn't able to write to a file on the
server. You can only do this through CGI. Of course you can create a guestbook with the people
answering via e-mail. You have to enter the feedback manually though. This is ok if you don't expect
to get 1000 feedback mails a day. This script here is plain HTML. So no JavaScript is needed here!
Only, of course, if you want to check the input before the form is submitted you will need JavaScript.
I have to add that the mailto-command does not work everywhere - for example the Microsoft Internet
Explorer 3.0 does not support it.

<form method=post action="mailto:your.address@goes.here" enctype="text/plain">


Do you like this page?
<input name="choice" type="radio" value="1">Not at all.<br>
<input name="choice" type="radio" value="2" CHECKED>Waste of time.<br>
<input name="choice" type="radio" value="3">Worst site of the Net.<br>
<input name="submit" type="submit" value="Send">
</form>

The property enctype="text/plain" is used in order to send plain text without encoded parts. This
makes it much easier to read the mail. If you want to validate the form before it is sent over the net
you can use the onSubmit event-handler. You have to put this event-handler into the <form> tag.
This looks like this:

function validate() {
// check if input ok
II ...

if (inputOK)

52 Training Cycle 7
Wintech Computers Javascript

return true;
else
return false;
)

<form ... onSubmit="retum validate()">

With this code the form isn't being sent over the Internet if the form input was wrong.

Setting the focus to a certain form-element


With the help of the focus() method you can make your form a little bit more user-friendly. You can
define which element is in focus at the beginning. Or you could tell the browser to focus on the form
where the input was wrong. This means that the browser will set the cursor into the specified form-
element so the user does not have to click on the form before entering anything. You can do this with
the following piece of script:

function setfocus()
{
document.first.textl .focus();
}

This script would setthe focus to the first text-element in the script Ihave shown above. You have to
specify the name of the whole form - which is called first here - and the name of the single form
element -here textl. If you want to put the focus on this element when the page is being loaded you
can add an onLoad-property to your <body> tag. This looks like this:

<body onLoad="setfocus()">

We can extend this with the following code:

function setfocus() {
document.first.textl .focus();
document.first.text1 .select();
}

Drop Down Boxes: No Button


Now that you have seen the javascript drop box with the button, you may want to know how to make
a drop box change pages without requiring the viewer to click a button. Instead, you want it to
change pages as soon as a choice is selected.

Well, the code for this is actually shorter than the drop box with the button. All that is new here is that
Training Cycle 7
Wintech Computers Javascript

you will need to learn the onChange attribute. The onChange attribute is another way of calling
javascript when something happens. It is coded in much the same way as onClick or onMouseover.
The difference is that this attribute is used in form elements, select boxes. The onChange attribute
will perform javascript statements when something inside your form element is changed. In this case
we will be changing a select box. Here is a quick example of the onChange attribute. You can send
someone a message when they choose something:

<FORM>
<SELECT name="sport" onChange="alert('l\'m glad YOU can make choices!')">
<OPTION SELECTED>-Choose a Sport--
<OPTION>Football
<OPTION>Basketball
</SELECT>
</FORM>

You can try it out .It isn't very useful, but it works....

Now, we can get to the useful application. You can use the onChange attribute to do the same thing
that we did with the onClick in the button in the last section. In other words, the onChange attribute
will now load the new url when someone makes a selection.

Other than removing the button and moving the window.location code to the onChange attribute in
the Select tag, this is the same script:

<FORM name="guideform">
<SELECTname="guidelinks"
onChange="window.location=document.guideform.guidelinks.options[do
cument.guideform.guidelinks.selected(ndex].value">
<OPTION SELECTED value="jdrop2.htm">--Choose--
<OPTION value="jex15.htm">Page 1
<OPTION value="jex16.htm">My Cool Page
</SELECT>
</FORM>

Notice that the default option selected just tells you to choose something. It won't lead anywhere
unless someone tries to change back to it. I used the url of the page it was on for the value of it, so
the browser will stay on the same page if it gets selected later. This isn't likely to happen though. I
couldn't go back and change backto the default option from another option when Itried. The brows
ers just went back and loaded the page with the default selection already selected again.

Well, there is your drop box with no button. Go change the urls and have some fun with it!

54 Training Cycle 7
Wintech Computers Javascript

Using Buttons for JavaScript


To write scripts using buttons, we will first need to know how to place a button on the page. To do
this, you will need to use the <FORM> tags around the button tag. Here is an example of the HTML
that will place a button on the page:

<FORM>
<INPUT type="button" value="Click Me" name="button1">
</FORM>

This will place a button on your page, but if you click on it nothing will happen....

<FORM> This creates a form so we can use a button.

<INPUT> This tag allows us to create an input area of some kind.

type="button" This command declares our input area to be a button.

value="Click Me" This will be the text people will see on the button. Write whatever you want your
visitors to see.

name="button1" You can give the button a name for future reference and possibly for use in a
script.

Now, I know you don't just want to make buttons that don't do anything, so let's look at a javascript
command that will make the browser do something when a viewer clicks it:

onClick="javascript commands"

Just place this command inside the INPUT tag you created the button with, like this:

<INPUT type="button" value="Click Me" name="button1" onClick=" ">

Now, to add text to the status bar using a button to do this!

<FORM>
<INPUT type="button" value="See Some Text" name="button2"
onClick="window.status='You clicked the button!'; return true">
</FORM>

You can also allow your viewers to change the background color of your page. Just use the follow
ing command, rather than the window.status command:
document.bgColor='color'
Just insert this as your instructions for the onClick command, like this:

Training Cycle 7 55
Wintech Computers Javascript

<FORM>
<INPUT type="button" value="Change to Yellow!" name="button3"
onClick="document.bgColor='yellow'">
</FORM>

You can add as many of these buttons as you like, just be sure they have the option to change
backto the original color. The next script will give you three choices: yellow, red, and original color.

<FORM>
<INPUT type="button" value="Change to Yellow!" name="button3"
onClick="document.bgColor='yellow'"> <br>
<INPUT type="button" value="Change to Red!" name="button4"
onClick="document.bgColor='red'"> <br>
<INPUT type="button" value="Change back!" name="button5"
onClick="document.bgColor='white'"> </FORM>

The last script we will do in this section will allow you to use your button as a link. It's pretty fun to use
every now and then. Just use the following command in your onClick command:

window.location='url'

Here is a script that will send you to a page, made just for this example:

<FORM>
<INPUT type="button" value="Go to my other Page!" name="button6"
onClick="window.location='http://www.pageresource.com/jscript/newpage.htm'">
</FORM>

JavaScript Prompts
Well, let's say you wanted to get somebody's name before they saw the page, and then write their
name on your page right before their very eyes Well, you can do this using a javascript prompt.
Here's the command:

prompt('Your Question', ' ');

This will bring up a window asking the question of your choosing, with a space for the viewer to
answer. The second set of quotes allows you to enter a default answer. If you leave it blank, the
viewer will just see an empty box ready to be typed in. This is usually done before the page loads, so
that you can write the answer they give into your page. To view an example, click the link below. You
will get a prompt for your name, and your name will be written on the page!

Example
Now, for the script that made this work. Note how the prompt and if/else statements are in the
HEAD section, while the actual writing of the name occurs in the BODY section.

56 Training Cycle 7
Wintech Computers Javascript

<SCRIPT language="JavaScript">
<!--hide
var yourname= prompt('Please enter your name, so you can get a special greeting',' ')|;

if ((yourname=='') II (yourname==null))
{
youmame="Dude";
}

</SCRIPT>

</HEAD>

<BODY>

<SCRIPT languages"JavaScript">
<!--hide
document.write("<CENTER><H1>Hello," + yourname + "! Welcome to My Page! <VH ><V
CENTER>");

//-->
</SCRIPT>

</BODY>

The first thing that happens is that the variable yourname is assigned the value it receives from the
user from the prompt. So the variable yourname will be a string of characters that makes up the
person's name. The if/else statement assigns yourname a value of "Dude" if nothing is entered in
the prompt by the user. It checks for" " and for null, and both are pretty much nothing. Now, in the
BODY section, you again use the SCRIPT tags to set off the JavaScript from any HTML around it.
You will also see a new command called document.write(" "); . This is what allows the JavaScript
variable yourname to be written onto the HTML document. You are writing two strings plus your
variable, yourname. The variable yourname is not in quotes because it is a value and not itself a
string (it's value is a string). That's why we have the plus signs around it....It makes the browser write
the first string plus the variable plus the second string. Now, notice 1he HTML tags are inside the
strings! Since this is a javascript, the only way to write the HTML tags back to the page is by includ
ing them inside the quotes as part of the string. Also, you probably noticed the way the closing tags
were written differently. (</H1>). The backslash is there as the javascript escape character. It allows
you to write the toward slash without it being mistaken for a division sign! (Remeber / is division in
JavaScript). Thus using the backslash followed by a toward slash ultimately gives us our single
toward slash. Pretty nifty trick, isn't it?

Training Cycle 7 57
Wintech Computers Javascript

JavaScript Alerts
Well, you want to add one of those JavaScript alert boxes that come out of nowhere, don't you?
Okay, let's begin with the alert box that just tells the viewer something you want them to know. Here's
the alert command:

alert('your choice of text')

Now, to use it, we'll need to place it inside another command. Let's use one we are familiar with, the
onMouseover command. The following script will alert the user that you did not want them trying to
click this particular link when they move their mouse over it.

<A HREF="noplace" onMouseover="alert('Hey! I said not to try clicking this link!')"> Don't click this
link!</A>

Give it a try. Move your mouse over the link below:

Don't click this link!

Yes! Now you can drive your friends insane with a bunch of fake links! Here's what all the commands
are doing:

onMouseover=" " This tells the browser to execute the command or function inside the double
quote marks when the user moves their mouse over the link.

alert('Hey! I said not to try clicking this link!')


Instructs the browser to display the text inside the single quotes in an alert window.

That was nice, but could you make something a little more annoying? Of course!! It's called the "alert
as soon as you open the page!" alert. Just think, you could tell people stuff before they ever see
anything on the page! The trick: placing the alert command inside the <HEAD> </HEAD> tags! You
will now get to use the old SCRIPT tags 11 cloned a couple of sections ago to set off the JavaScript
from the other stuff. Here is the code:

<HEAD>
<TITLE>Cool JavaScripts</TITLE>

<SCRIPT language="JavaScript">
<!-- hide from old browsers

alert('Welcome to my Web Site!');

//-->
</SCRIPT>

</HEAD>

Training Cycle 7
58
Wintech Computers Javascript

This will display the alert before the page starts loading. When you hit "OK" the page will go on and
load normally.

Here's the breakdown:

<SCRIPT languages"JavaScripts This tag lets the browser know you are using JavaScript com
mands here.

<!-- hide script from old browsers This makes sure older browsers don't display your script as text
on the page. alert('Welcome to my Web Site!'); This is your alert. Put your mesage inside the
single quotes. Notice the semicolon at the end, this is what separates JavaScript commands.

//--> Stops hiding the script from old browsers.

</SCRIPT> Ends the JavaScript commands.

Example 1
SO, wanna get carried away? Place serveral of these alerts inside the SCRIPT tag, following each
with a semicolon. The viewer will have to say "OK" to every alert before the page will begin loading.
Try it out yourself and see if you go insane. Click the link below!

Example 2
<HTML>
<HEAD>
<TITLE>JavaScript Example 2</TITLE>

<SCRIPT languages"JavaScript">
<!--
alert('Please Sign My Guestbook, NOW!');
alert('l mean it, NOW!!!');
alert('Did I mention I had a gusetbook? Well SIGN IT!');
alert('Oh, remember....THE GUESTBOOK! O.K.?!!');
//-->
</SCRIPT>
</HEAD>
<BODY>
So, how about that? Pretty wild, isn't it? You can also use the alert with a button, so that it is not
such a surprise. Place the code where you want the button to be on your page. You won't need the
SCRIPT tag for this one.

<FORM>
<INPUT type="button" value="Click here to see what I think of YOUI"
onClick="alert('You are the greatest person I have ever metl')">
</FORM>
</BODY>
</HTML>

Training Cycle 7 59
Training Cycle - 8
Wintech Computers Javascript

Understanding Event Handlers In JavaScript

Introduction to Event Handlers


So, what are event handlers? Very powerful and useful! They are JavaScript code that are not
added inside the <script> tags, but rather, inside the html tags, that execute JavaScript when some
thing happens, such as pressing a button, moving your mouse over a link, submitting a form etc.
The basic syntax of these event handlers is:

name_of_handler="JavaScript code here"

For example:

onClick="alert('hello!')"

Event Handlers:

onClick: Use this to invoke JavaScript upon clicking (a link, or form


boxes)
onload: Use this to invoke JavaScript after the page or an image
has finished loading,
onmouseover: Use this to invoke JavaScript if the mouse passes by some
link
onmouseout: Use this to invoke JavaScript if the mouse goes pass some
link
onunload: Use this to invoke JavaScript right after someone leaves
this page.

onClick Event handler


Ok, lets see how the onclick event-handler can help us. Remember, any event handlers are added
inside html tags, not inside<scriptx/script> (there is an alternate way, which will not be discussed
in this section). First of all, does that mean we can simply dump event handlers anywhere within any
html tag? Noooo! onClick handlers execute something only when users click on form buttons, check
boxes, etc.or text links, therefore they can only be inserted in these tags, for example, <a>,<input
type=..>. Lets see an example of an onClick event handler:

Click the output:

<script>
function inform()
{
alert<"You have activated me by clicking the
grey button! Note that the event handler is
added within the event that it handles, in
this case, the form button event tag")
}
60
Training Cycle 8
Wintech Computers Javascript

</script>

<form>
<input types"button" namesMtest" values"Click
me" onclicks"inform()">
</form>

The function inform() is invoked when the user clicks the button.

All examples you have seen up to now use this handler, the onClick handler.to illustrate the ex
amples. Ok, let me show you another example that will make use of the checkbox element.

Try this: (it will change the background color of a document interactively)

<form names"go">
<input type="checkbox" names"C1"
onclick="document.bgColors'lightblue'">
<input type="checkbox" namesMC2"
onclick="document.bgColors'lightyellow'">
input type="checkbox" names"C3"
onclick="document.bgColor='lightgreen'">
</form>

We used the onclick handler to change the background color. Notice that we just wrote in plain
English the name of the bgcolor...you can do that, for most colors.
This is a crudely implemented bgcolor changer. Whenever you select additional checkboxes, the
previous one stays checked. You can use buttons or radio boxes to alter that.

onLoad Event handlers


The onload event handler is used to call the execution of JavaScript after a page /frameset /image
has completely loaded. It is added like this:

<body onloads"inform()">
//Execution of code
//will begin after the page has loaded.

<frameset onload="inform()">

//Execution of code //will begin after the current frame has


loaded.

<img srcs-whatever.gif" onload="inform()">


//Execution of code will begin after the
image //has loaded.

Training Cycle 8
Wintech Computers Javascript

Lets see an example of an onload handler:

<html>
<headxtitle>Body onload example</title>
</head>
<body onload="alert('This page has finished loading!')">
Welcome to my page
</body>
</html>

As soon as the page has finished loading, it will alert you saying so.

onMouseover.onMouseout

These handlers are used exclusively with links.. The following example writes something to the
status bar (at the bottom of your screen) whenever a mouse cursor hovers over the link, and deletes
it when the mouse moves
away.

<a href="blabla.htm" onmouseover="status='Do not click here, its empty!';return true"


onmouseout="status=' '">Don't Click Here</a>

Several new concepts arise here, so I'll go over each one of them, the "status" refers to window.status,
which is how you write to the status bar. Note that instead of calling a function, we wrote directly the
JavaScript code within the handler :"status='Do not click here, its empty!';return true" This is ok, but
it is important that you separate statements with ;. You could have, alternatively, written everything
up until "return true" as a function and then calling it:.

function writestatus()
{
status="Do not click here, its empty!"
}
and then: onmouseover="writestatus();return true"

So you're thinking, "what is return true?" Good question. You need to add this line of code to set the
status property with the mouseover effect. Uh? I know, don't worry so much now, it really isn't impor
tant. Just remember you need this to "activate" the status onmouseover effect.

onmouseout="status=''"
clears the status after the mouse leaves the link. Whenever the mouse moves away from the link,
the status bar is "reset" again. If you don't insert this code, the status bar will still have those words
you entered into it even after taking away the cursor. Whenever we have nested quotations, the
inner ones are always singled, le:

62 Training Cycle 8
Wintech Computers Javascript

onclick="document.write('hello')"

onUnload:
onunload executes JavaScript immediately after someone leaves the page. Acommon use (though
not that great) is to thank someone as that person leaves your page for coming and visiting.

<body onunload="alert(Thank you. Please come


back to this site and visit us soon, ok?')">

There are other event handlers, many belonging to forms. These event handlers are discussed
down. For convenient reference, here is a complete list of all the event handlers in JavaScript:

Event Handlers Can be used with these tags:

OnAbort Images

OnBlur Windows, all form elements, frames

OnClick Buttons, radio buttons,


Checkboxes, submit buttons,
Reset buttons, links

OnChange text fields, textareas, select lists

OnError windows, images

OnFocus windows, frames, and all form elements

OnLoad body, images

OnMouseover areas, links

OnMouseout links

OnReset forms

OnSelect text fields, textareas

OnSubmit submit button

OnUnload body

63
Training Cycle 8
Training Cycle - 9
Wintech Computers Javascript

The Image-object:

Images on a web-page
Now we are going to have a look at the Image-object which is available since JavaScript 1.1 (i.e.
since Netscape Navigator 3.0). With the help of the Image-object you can change images on a
web-page. This allows us for example to create animations. Please note that users of older brows
ers (like Netscape Navigator 2.0 or Microsoft Internet Explorer 3.0 - they use JavaScript 1.0) cannot
run the scripts shown in this part - or at least they cannot see the whole effect.
First, let's see how the images in a web-page can be addressed through JavaScript. All images are
represented through an array. This array is called images. It is a property of the document-object.
Every image on a web-page gets a number. The first image gets the number 0, the second image
gets the number 1 and so on. So we can address the first image through document.images[0].
Every image in a HTML-document is considered as an Image-object. An Image-object has got
certain properties which can be accessed through JavaScript. You can for example see which size
an image has with the properties width and height. document.images[0].w'idth gives you the width
(in pixel) of the first image on the web-page. Especially if you have many images on one page it gets
hard to keep count of all images. Giving names to the different images solves this problem. If you
declare an image with this tag

<img src="img.gif" name="mylmage" width=100 height=100>

you can address it through document.mylmage or


document.images["mylmage"].

Loading new images


Although it is nice to know how to get the size of an image on a web-page this is not what we wanted
to know. We want to change images on a web-page. For this purpose we need the src
property. As in the <img> tag the src property represents the address of the displayed image. With
JavaScript 1.1 you can now assign new addresses to an already loaded image on a web-page. The
result is that the image located at the new address is being loaded. This new image replaces the old
image on the web-page. Look at this example:

<img src="img1.gif" name="mylmage" width=100 height=100> I


The image img1.gif is being loaded and gets the name mylmage. The following line of code re
places the old image img1.gif with the new image img2.gif:

document.mylmage.src= "img2.src";

The new image has always got the same size as the old image. You cannot change the size of the
area in which the image is being displayed. You can test this example through clicking on the follow
ing button (works only once).'

64 Training Cycle 9
Wintech Computers Javascript

Preloading images
One drawback might be that the new image gets loaded after assigning a new address to the src
property. As the image is not preloaded it takes some time until the new image is retrieved through
the Internet. In some situations this is ok - but often these delays are not acceptable. So what can
we do about this? Yes, preloading the image is the solution. For this purpose we have to create a
new Image-object. Look at these lines of code:

hiddenlmg= new lmage();


hiddenlmg.src= "img3.gif";

The first line creates a new Image-Object. The second line defines the address of the image which
shall be represented through the object hiddenlmg. We have already seen that assigning a new
address to the src attribute forces the browser to load the image the address is pointing at. So the
image img2.gif gets loaded when the second line of this code is being executed. As the name
hiddenlmg implies the image is not being displayed after the browser finished loading it. It is just
kept in the memory (or better in the cache) for later use. In order to display this image we can now
use this line:

document.mylmage.src= hiddenlmg.src;

Now the image is being taken from the cache and displayed immediately. We have managed to
preload the image. Of course the browser must have finished the preloading for being able to dis
play an image without delay. So if you have many images specified for preloading there might be a
delay nevertheless because the browser has been busy to download all the other pictures. You
always have to consider the speed of the Internet - the downloading of the images doesn't go faster
with this code shown here. We only try to start the downloading of the images earlier - so the user
can see them earlier. This makes the whole process much smoother. If you have a fast Internet
connection you might wonder what all this talk is about. Which delay is this guy talking about all the
time? Well, there are still some people sitting behind a 14.4 modem

Changing images on user-initiated events


You can create nice effects through changing images as a reaction to certain events. You can for
example change images when the mouse cursor is being moved over a certain area. Just test the
following example through moving the cursor across the image (you will get an error message when
using a JavaScript 1.0 browser - we will see how to prevent this soon):

The source code for this example looks like this:

<a href="#"
onMouseOver="document.mylmage2.src='img2.gif"
onMouseOut="document.mylmage2.src='img1.gif'">
<img src="img1 .gif" name="mylmage2" width=160 height=50 border=0></a>

Training Cycle 9 65
Wintech Computers Javascript

This code causes some problems though:

The user might not use a JavaScript 1.1 browser.


The second image is not being preloaded.
We have to rewrite the code for every image on a web-page.
We want to have a script which can be used in many web-page over and over again
without large changes.

We will now have a look at a complete script which solves these problems. The script gets much
longer - but once it is written you do not have to bother about it anymore.

There are two requirements for keeping the script flexible:


Undefined number of images - it should not matter if 10 or 100 images are used
Undefined order of images - it should be possible to change the order of the images without chang
ing the code

Here you can see the code at work:

<html>
<head>

<script language="JavaScript">
<!-hide

var browserOK = false;


var pics;

//-->
</script>

<script language="JavaScript1.1">
<!-hide

// JavaScript 1.1 browser - oh yes!


BrowserOK = true;
Pics = new Array();

//-->
</script>

<script languages"JavaScript">
<!-hide

66
Training Cycle 9
Wintech Computers Javascript

var objCount = 0; // number of (changing) images on web-page

function preload(name, first, second) {

// preload images and place them in an array

if (browserOK) {
pics[objCount] = new Array(3);
pics[objCount][0] = new lmage();
pics[objCount][0].src = first;
pics[objCount][1] = new lmage();
pics[objCount][1].src = second;
pics[objCount][2] = name;
objCount++;
}
}

function on(name){
if (browserOK) {
for (i = 0; i < objCount; i++) {
if (document.images[pics[i][2]] != null)
if (name != pics[i][2]) {
// set back all other pictures
document.images[pics[i][2]].src = pics[i][0].src;
} else {
// show the second image because cursor moves across this image
document.images[pics[i][2]].src = pics[i][1].src;
}
}
}
}

function off(){
if (browserOK) {
for (i = 0; i < objCount; i++) {
// set back all pictures
if (document.images[pics[i][2]] != null)
document.images[pics[i][2]].src = pics[i][0].src;
}
}
}

// preload images - you have to specify which images should be preloaded


// and which Image-object on the wep-page they belong to (this is the first

67
Training Cycle 9
Wintech Computers Javascript

// argument). Change this part if you want to use different images (of course
// you have to change the body part of the document as well)

preload("link1", "img1f.gif", "img1t.gif");


preload("link2", "img2f.gif", "img2t.gif");
preload("link3", "img3f.gif", "img3t.gif");

// -->
</script>
<head>

<body>
<a href="link1.htm" onMouseOver="on('link1')"
onMouseOut="off()">
<img name="link1" src="link1f.gif"
width="140" height="50" border="0"></a>

<a href="link2.htm" onMouseOver="on('link2')"


onMouseOut="off()">
<img name="link2" src="link2f.gif"
width="140" height="50" border="0"x/a>

<a href="link3.htm" onMouseOver="on(*link3')"


onMouseOut="off()">
<img name="link3" src="link3f.gif"
width="140" height="50" border="0"></a>
</body>
</html>

This script puts all images in an array pics. The preload() function which is called in the beginning
builds up this array. You can see that we call the preload() function like this:

preload("link1", "img1f.gif", "img1t.gif");

This means that the script should load the two images img1f.gif and img1t.gif. The first image is the
image which should be displayed when the mousecursor isn't inside the image area. When the user
moves the mousecursor across the image area the second image is shown. With the first argument
"imgl" of the call of the preload() function we specify which Image-object on the web-page the two
preloaded images belong to. If you look into the <body> part of our example you will find an image
with the name imgl. We use the name of the image (and not its number) in order to be able to
change the order of the pictures without changing the script.
The two functions on() and off() are being called through the event-handlers onMouseOver and
onMouseOut. As images cannot react to the events MouseOver and MouseOut we have to put a
link around the images. As you can see the on() function sets back all other images. This is neces-
68
Training Cycle 9
Wintech Computers Javascript

sary because it could happen that several images are highlighted (the event MouseOut does not
occur for example when the user moves the cursor from an image directly outside the window).

Images are certainly a great way for enhancing your web-page. The Image-object lets you create
really sophisticated effects. But please notice not every image and JavaScript program enhances
your page. If you surf around the net you can see many examples where images are used in a
horrible way. It's not the quantity of images that makes your web-page look good - it's the quality. It
is really annoying to download 50 kB of bad graphics. Keep this in mind when creating image-effects
with JavaScript and your visitors/customers will come back more likely.

Some more Examples on Animation :

<html>
<head>
<title>
Animation
</title>

<script language="javascript">

imge=new Array(12);
for(i=0;i<12;i++)
{
imge[i]=new lmage();
}

imge[0].src= "runner1.gif";
imge[1].src= "runner2.gif";
imge[2].src= "runner3.gif";
imge[3].src= "runner4.gif";
imge[4].src= "runner5.gif";
imge[5].src= "runner6.gif";
imge[6].src= "runner7.gif";
imge[7].src= "runner8.gif";
imge[8].src= "runner9.gif";
imge[9].src= "runner10.gif";
imge[1Oj.src="runner11.gif";
imge[11].src="runner12.gif";

var i=0;
function go()
{

document.layers["myLayer"].document.images[0].src=imge[i].src;

Training Cycle 9 69
Wintech Computers Javascript

i++;
goagain();
}

function goagain()
{
if(i==12) i=0;
setTimeout("go()",100);

function animate()
{

var pos=0;

function anim()

pos+=10;
document.layers["myLayer"].left=1+pos;

if(pos>800) pos=0;
setTimeout("anim()",1);

</script>
<body onLoad="go()">
<ilayer name="myLayer" z-index=0 left="0" top="10">
<img name="runner" alt="javascript" src="runner1.gif height="200" width="200">
</ilayer>

<form name="frm">

70
Training Cycle 9
Training Cycle -10
Wintech Computers Javascript

Layers

What are layers?


Layers are one great new feature of the Netscape Navigator 4.0. This allows absolute positioning of
objects like images. Besides that you can move objects on your HTML-page. You can also hide
objects. Layers can easily be manipulated with the help of JavaScript. You can only use layers with
Netscape Navigator 4.0 at the moment!

What exactly are layers?


This can be explained quite easily: you take several sheets of paper. On one paper you write a text.
On another one you draw an image. Write some text besides an image on a third paper and so on.
Now, put these sheets of paper on a table. Let's say every paper is a layer. From this aspect a layer
is some kind of container. It can contain objects - i.e. in this case text and images. Now take a paper
with an image on. Move it around on the table. Watch the image following the movements of the
paper carefully. If you move the paper to the right the image will follow! What do we learn from this
fascinating experience?
Layers which can contain several different objects - like images, forms, text etc. - can be placed on
your HTML-page and can be moved around. If you move a layer all objects contained in this layer
will follow this movement. Layers can overlap each other like papers on a table. Every layer can
have transparent parts. Put a hole in one paper. Now put this paper above another paper. The hole
is a 'transparent part' of the first paper - the content of the underlying paper shines through.
Creating layers :
For creating a layer we need either the <layer> or <ilayer> tag. You can use the following
properties:

Properties Desc

Name="layerName" The name of the layer


left=xPosition The horizontal position of the top left
corner

top=yPosition The vertical position of the top left Corner


z-index=layerlndex Index number of layer
width=layerWidth Width of the layer in pixel

clip="x1_offset,y1_offset,x2_offset, y2_offset" Defines the area of the layer which Shall


be displayed

above="layerName" Defines above which layer this


layer will appear
below="layerName" Defines below which layer this
Training Cycle 10
71
Wintech Computers Javascript

layer will appear

Visibility=showlhidelinherit The visibility of the layer

Bgcolor="rgbColor" The background color - either


name of a standard color or
rgb-values

Background="imageURL" Background image

The <layer> tag is used for layers which can be explicitly positioned. If you do not specify a position
(with the left and top properties) the layer will be positioned in the top left corner of the window. The
<ilayer> tag creates a layer which position depends on the flow of the document. Now let's start
with an easy example. We want to create two layers. In the first layer we put an image and in the
second layer we put a text. What we want to do is to display the text above the image.

The text is displayed above the image


Here is the source code:

<html>
<layer name=pic z -index-=0 left=200 top=100>
<img src= "img.gif" width= 160 height=120>
</layer>
<layer name=txt z- index=-A left=200 top=100>
<font size =+4> <i> Layers-Demo </i> </font>
</layer>
</html>

x Nettcape rngnn
E* t<x i*

Re^w Home t-c-srh Hvtcw Pnn* Secifty

Cjl ;/e*lll |Bjj Gut,:' 'f Pe-ifM, P 'iVioi/F'age. ;l ln**k)J J Ojrk

Layem-Demo

,jf ..<]>.

You can see that we define two layers with the <layer> tag. Both layers are positioned at 200/
100(defined through left and top). Everything between the <layer> and the </layer> tag (or <ilayer>
and the </ilayer> tag) belongs to this layer. You can see that we use the property z-index. This

72 Training Cycle 10
Wintech Computers Javascript

defines in which order the layers appear - i.e. in our case you tell the browser if the text will appear
above or below the image. The layer with the highest z-index number will be displayed on top. You
do not have to use 0 and 1 for the z-index - every positive integer is ok.
If you write z-index=100 in the first <layer> tag the text will be displayed below the image - as the
text-layer has got a smaller z-index number (z-index=1). You can see the text through the image
because I used a transparent background (gif89a format).

The text is displayed below the image

Layers and JavaScript :


Now we are going to access layers through JavaScript. We want to start with an example where the
user can push a button in order to hide and show a layer. First we have to know how the layers are
represented in JavaScript. As usual there are several ways. The best thing is to assign a name to
every layer. If we define a layer with

<layer ... name=myLayer>

</layer>

we can access this layer through document.layers["myLayer"]. According to the documentation


provided by Netscape we can also write document.myLayer - but this lets my browser crash. This is
certainly only a problem of the preview version and will be solved in the final release
document.layersf'myLayer"] - so we are going to use this alternative. You can also access the layers
through an integer index. In order to access the bottommost layer you can write document.layers[0].
Please note that the index is not the same as the z-index property. If you have for example two
layers called layerl and Iayer2 with the z-index numbers 17 and 100 you can access these layers
through document.layers[0] and document.layers[1] and not through document.layers[17] and
document.layers[100].

There are several layer-properties which can be changed through JavaScript. The following example
presents a button which lets you hide and display one layer (Netscape Navigator 4.0 - or
higher - required!).

The source code looks like this:

<html>
<head>
<script language="JavaScript">

<!-hide
function showHide()
{ if (document.layers["myLayer"].visibility == "show")
document.layers["myLayer"].visibility= "hide"
else document.layers["myLayer"].visibility= "show";
}

Training Cycle 10 73
Wintech Computers Javascript

//-->
</script>
</head>
<body>
<ilayer name=myLayer visibility=show>

<font size=+1 color="#0000ff"xi>This text is inside a layer</ix/font>


</ilayer>

<form>
<input type="button" value="Show/Hide layer"
onClick="showHide()">

</form>
</body>
</html>

The button calls the function showHide(). You can see that this function accesses the property
visibility of the layer-object myLayer. Through assigning "show" or "hide" to
document.layers["myLayer"].visibility you can show or hide the layer. Please note that "show"
and "hide" are strings - not reserved keywords, i.e. you cannot write
document.layers["myLayer"].visibility= show.
Ihave used the <ilayer> tag instead of the <layer> tag because Iwanted to put the layer in the flow
of the document.

Moving layers :
The properties left and top define the position of the layer. You can assign new values to these
properties in order to set the position of the layer. The following line sets the horizontal position of
the layer to 200 (in pixel):

document.layers["myLayer2"].left= 200;

We are now going to program a moving layer - this looks like a scroller inside the browser window.

This text is inside a laver

The script looks like this:

<html>
<head>
<script language="JavaScript">
<!--hide
var pos=0;
var direction=true;
function move()

74 Training Cycle 10
Wintech Computers Javascript

{
if (pos <= 0)
direction= true;
if (pos >= 500)
direction= false;
if (direction)
pos=pos+50;
else
pos=pos-50;
document.layers["myLayer2"].left= pos;
}
//-->
</script>
</head>

<body onLoad="setlnterval('move()\ 500)">


<ilayer name=myLayer2 left=0>
<font size=+1 color="#0000ff"xi>This text is inside a layer</ix/font>
</ilayer>
</body>
</htmf>

We create a layer called myLayer2. You can see that we are using onLoad inside the <body> tag.
We need to start the scrolling of the layer as soon as the page is loaded. We use setlnterval() inside
the onLoad event-handler. This is a new method of JavaScript 1.2 (i.e. the JavaScript version that is
implemented in Netscape Navigator 4.0). This can be used to call a function over and over again in
a certain time interval. We can use setTimeout() for this also. setlnterval() works almost the same -
but you have to call it only once. Through setlnterval() we are calling the function move() every 20
milliseconds. The function move() sets the layer to a certain position. As we call this function over
and over again we get a fluent scrolling of the text. All we have to do in the function move() is to
calculate the position of the layer and assign this value todocument.layers["myLayer2"].left=
pos.

The following code will only be executed by browsers which understand JavaScript 1.2:

<script language="JavaScript1.2">
<!-hide
document.writefYou are using a JavaScript 1.2 capable browser.");
//-->
</script>

Training Cycle 10 75
Training Cycle -11
TT

Wintech Computers Javascript

JavaScript Hover Buttons

Change the image when a mouse moves over it


Using a javascript to change an image when someone moves their mouse over it has become quite
popularu may have heard it called many things: "hover buttons", "rollover", and "image highlighter"
are a few. What happens is that we use two images, a link, and a javascript to make a clickable
image link that is "highlighted" when a mouse passes over it. To begin, you will need to make
yourself two images of the same size, making whatever changes you would like to the second one.
Below is an example where I chose to make an image with blue text and one in red text. The red-text
image is what I want people to see when they move their mouse over the blue-text image. OK, that
the easy part. Now we have to have a script that will do all the work for us. I'm going to go ahead and put
the whole thing below, and explain the script in parts afterward. I got this scriptfrom a free script page, did
some formatting for readability, changed some variable names, and added a check for IE4. The script will
only work in Netscape 3 or 4 and IE 4. This would go between the HEAD tags of your HTML page:

<HEAD>
<SCRIPT language="JavaScript">

<!~hide

browserName=navigator.appName;
browserVer=parselnt(navigator.appVersion);

if ((browserName=="Netscape" && browserVer>=3) II (browserName=="


Microsoft Internet Explorer" && browserVer>=4))
version="n3";
else
version="n2";

if (version=="n3")
{
pidon= new lmage(100,25);
pid on.src="shoes2.gif";

pidoff= new lmage(100,25);


pidoff.src="shoes1 .gif";
}

function Hghtup(imgName)
{
if (version=="n3")
{
imgOn=eval(imgName + "on.src");
document[imgName].src= imgOn;

76
Training Cycle 11
"T

Wintech Computers Javascript

function turnoff(imgName)
{
if (version=="n3")
{
imgOff=eval(imgName + "off.src");
document[imgName].src= imgOff;
}
}

//-->

</SCRIPT>
</HEAD>

Part 1: Browser Check


All right, the first step is to check for a browser that supports all the functions and declarations we will
be using. This is done with the following lines:

browserName=navigator.appName;
This line is used to get the name of the browser.
browserVer=parselnt(navlgator.appVersion);
This line checks for the version of the browser.

if ((browserName=="Netscape" && browserVer>=3) II


(browserName=="Microsoft Internet Explorer" && browserVer>=4))
version="n3";
else
version="n2";

This is basically one long sentence that will define the variable "version". In plain wording, it reads
like this: "If the name of the browser is Netscape and the version is 3 or higher, or if the browser is
Microsoft Internet Explorer and the version is 4 or higher, then the.version is "n3\ Otherwise, the
version is "n". So, the n3 version will run the script, and n2 version will only see the first image.

Part 2: Define and Load Your Images


Now, we get the images involved in the scheme here:
If (version=="n3")
{
This checks for an "n3" browser so "n2" browsers don't try running the script (error city!). The "{"
opens the group of statements for "n3" browsers.

Training Cycle 11 77
Wintech Computers Javascript

plc1on= new lmage(100,25);


This defines a new image called "pidon" with a width of 200 and a height of 25.
pid on.src="shoes2.gif";
This gives the source, or url of the image. This allows it to load now so users don't wait for a new
image to load when they pass their mouse over it later. Be sure this is the url of yoBf image. This
is the one you want people to see when their mouse passes over.
pic1off= new lmage(100,25);
Now you define your default, or 1st imagepid off.src="shoes1.gif";
Give the url of your default image so it is loaded.
}: Ends the image defining and loading statements.

Function 1: The mouseover Function


Now we get to the function that will be triggered by the mouse moving over the image:

function lightup(imgName)
{
This defines a function named "lightup". It is reading in a parameter called "imgName". "imgName"
is going to be the name="pic1" attribute of the 2nd image from our HTML document. It is sent to this
function when we call it later in the HTML document (see below). imgName turns out to be "pid".
The "{" begips the group of statements for the function.
If (version=="n3")
{
Another browser check and beginning of statements for "n3" browsers.
imgOn=eval(lmgName + "on.src"); This defines the variable "imgOn" as the sum of the variable
"imgName" and the string "on.src". Remember, the function read in "imgName" as "pid", sothe sum
ends up as "pid on.src", which is defined earlier as the url of our 2nd image.
document[imgName].src= ImgOn;
Now, we define imgOn for the document, so it loads the correct image. By substituting what we got
for imgOn a moment ago, and substituting "pid" for imgName (which was sent to the function), we
get this:

document[pid ].src=pid on.src.

This is why we need to use the name="pid" attribute in the image tag in our HTML later. This makes
a reference to an image in the document by the name of "pid". The new source (url) for the image
is now the value of "pidon.src", which we defined earlier as "shoes2.gif", our 2nd image. Abit
complicated at first, but it works out nicely, doesn't it?
}} : These end the "n3" statements and the fuction statements.

Function 2: When the Mouse Leaves the Image


function turnoff(imgName)
{
if (version=="n3")
{

78
Training Cycle 11
Wintech Computers Javascript

imgOff=eval(imgName + "off.src");
document[imgName].src= imgOff;
}
}

//---->

</SCRIPT>
</HEAD>
This function does the same thing as the last one, except that it occurs when the mouse moves off
the image. Thus, I named the function "turnoff" since it turns the previous function "off" and returns
to the 1st image. After the function ends, the script and HEAD tags are closed.

Finally, the HTML!


Now, go down into your BODY section and find out where you would like your image to go. You will
then put in the following linked image code. You should place everything on one line, I have it this
way only for readability.
<A HREF="index.html" onMouseover="lightup('pid')" onMouseout="turnoff('pid')">
<IMG SRC=7images/shoes1 .gif" name="pid" width="100" height="25" border="0"x/A>
Notice how we call our function "lightup" with the parameter 'pid' on the Mouseover. We then call
the function "turnoff" with the parameter 'pid' on the Mouseout. The action is all done in our link tag.
You can link to any url you wish here, and that will be where the user goes if they click the image. In
the image tag, use your first (default) image as the image source. Also, be sure you use the
name="pid" attribute, as well as defining your height and width. This will make sure the script
knows the name, height, and width of your image and will run smoothly. The border attribute is up to
you. I chose zero for mine because I wanted the image to look like text.

The Final Product: A Changing, Linked Image


Yes, there it is. Move your mouse over it and see the text turn red! You can click it if you want, but
you'll end up back at the main JavaScript Page

But I Want to do this for Multiple Images!


No problem. You can use it for as many images as you wish. Just be sure to define your other
images along with your first. Remember, you need two images for every one you want to change. To
add extras, define them first back in the script in the HEAD section:
if (version=="n3")
{
pidon= new lmage(100,25);
pic1on.src="/images/shoes2.gif";
pic2on= new lmage(100,25);
pic2on.src="/images/story2.gif";

pidoff= new lmage(100,25);


pidoff.src="/images/shoes1 .gif";

Training Cycle 11 79
Wintech Computers Javascript

plc2off= new lmage(100,25);


plc2off.src=H/lmages/story1 .gif";
}
Now, be sure you name it correctly in the HTML in the BODY section. For the new image here, we
will name it "pic2". (For more, just use "pic3", "pic4", and so on). Then just link it to another page:
<A HREF="newpage.html" onMouseover="lightup('pic2')" onMouseout="turnoff('pic2')">
<IMG SRC="/images/story1.gir name="pic2" width="100" height="25" border="0"></A>

80
Training Cycle 11
Training Cycle -12
Wintech Computers Javascript

JavaScript Object Detection Detecting objects


instead of browsers

Do you remember the hover button script we worked on a while back? Then you probably remember
how much trouble it was to detect the browser type before we could run the script. Here was how we
had to do it:

browserName=navigator.appName;
browserVer=parselnt(navigator.appVersion);
if ((browserName=="Netscape" && browserVer>=3) II (browserName=="Microsoft internet Explorer"
&& browserVer>=4))
version="n3";
else
version="n2";

That is a lot of code to run through, and it can be much worse when you create a script that has alot
of browser differences. Well, instead of checking for the browser, we could have checked for the
javascript object that we needed for the script to work. Since we know that the hover button script
needed the document.images object to work, we could have shortened the above code to say:
if (document.images)
{ ...code...}'

In fact, this object just so happens to exist in the browsers we checked for, and not in the browsers
that were excluded. So, using this object detection code, we are checking for Netscape 3or higher,
and MS Internet Explorer 4 or higher! And as a bonus, if any other browser happens to recognize
the document.images object, the script will run for them too! (Opera perhaps?) You can also use a
couple of the new objects to check for version 4 browsers. If you are looking only for NS4 or better
check for the
Document.layers object:
if (document.layers)
{ ...code...}

If you want only IE4 or better, check for the document.all object. (May change when NS5 arrives)-
if (document.all) ''
{ ...code...}
Of course, if you just want it to work for either version 4browser, check to see if the browser has one
object or the other:
if (document.all II document.layers)
{ ...code...}
You can find some more uses for this as you are coding, so that you can avoid those pesky javascript
errors in older browsers. While you are at it, it will probably keep away those errors with the newer
browsers as well

Training Cycle 12
Wintech Computers Javascript

JavaScript Password Protection -I


Adding a password to your page

OK, I finally got around to writing the javascript password protection tutorial. You will see the ex
ample script here is pretty straightforward, but it is also pretty easy to get around. I'll tell you why and
give you links to more secure scripts
later in this tutorial.

Warning: These scripts are not totally secure and your page can be seen if someone gets
through. Do NOT protect anything important with a script like this. Try looking for a cgi
Script or ask your web host to set up an .htpassword file if you need to protect somethin j
important.

Below is a link that will show you an example of what we are about to create. Click the link. When
you are prompted for a password, enter: cool

Example Password Protected Page


OK, if you typed "cool" into the prompt, you were allowed to continue loading the example page. If
you typed anything else or nothing at all, you were taken right back to this page. That is pretty cool.
Now let's see the script that makes this work. You would place this script in the HEAD section tMe
page you want to protect. In this case, it was "jex8.htm". Here is the script:

<HEAD>
<SCRIPT language="JavaScript">
<!--hide

var password;

var pass1="cool";

password=prompt('Please enter your password to view this page!','');

if (password==pass1)
alertCPassword Correct! Click OK to enter!');
else

{
window.location="http://www.pageresource.com/jscript/jpass.htm";
}

//->
</SCRIPT>
</HEAD>

If you have been through the previous tutorials, most of the code will make sense to you. Let's get to
the details of what is going on with this thing:

82
Training Cycle 12
Wintech Computers Javascript
var password; This creates a variable named "password".
var passl ="cool"; This creates apassword that will be accepted by the script. We name it passl in
case we would like to have more than one acceptable password. ( ie pass2, pass3 etc. ).
password=prompt('Please enter your password to view this page!','');
This is what creates the prompt for the user to enter a password. Whatever the user enters in the
prompt will be the value of the variable "password". If you have not seen prompts before, go to the
prompts tutorial for more info.

if (password==pass1)
alert('Password Correct! Click OK to enter!');

This is where we verify the password. The variable "password" is what the user just typed into the
prompt. The variable "passl" is the only password we will accept. If they are the same, we send
them an alert that the password was OK and they can continue. If you haven't seen if/else state
ments yet, go to the if/else page. For more on alerts, see the alerts page,
else

window.location="http://www.pageresource.com/jscript/jpass.htm";

This is what happens when they type in an incorrect password. We send them to a page of our
choice. In IE4, it looks like nothing happened, it just reloads this page. In NS3 and 4 you will prob
ably see the protected page for a quarter of a second. I said it wasn't the most secure script out
there, so Iwould recommend the links at the end of the tutorial so you can get a more secure script.
Ichose to send it back to this page (jpass.htm), but you can type any url here you want. Maybe you
could use something like:
window.location="http://www.barbie.com"; Make them cringe a little All that's left after that is to
link to the protected page from another page, like my link above to the example. No problem. Now,
if you want more than one acceptable password, you can make a couple of modifications and you
will have it. First, add more variables for the accepted passwords. If you want three good passwords,
declare three variables. Since I had one named "passl" already, I will just use *pass2" and "pass3":

var passl ="cool";


var pass2="awesome";
var pass3="geekazoid";

Next, you will need to change your "if" statement to include the other two passwords. This is done
with the II (or) operator:

if (password==pass1 II password==pass2 II password==pass3)


alert('Password Correct! Click OK to enter!');

This means that if the user typed in the correct value for "passl OR "pass2" OR "pass3", the
password is correct and they can view the page. ;
Here is how the full code would look for this:

Training Cycle 12 83
Wintech Computers Javascript

var password;

var passl ="cool";


var pass2="awesome";
var pass3="geekazoid";

password=prompt('Please enter your password to view this page!',' ');

if (password==pass1 II password==pass2 II password==pass3)


alert('Password Correct! Click OK to enter!');
else

{
window.location="http://www.pageresource.com/jscript/jpass.htm";
}
If you want to see this in action, click the link for this example below. Enter one of the three correct
passwords (cool, awesome, or geekazoid) and you will see the next page!
Multiple Password Example So, why is it easy to hack the script? One way is for the viewer to
disable javascript. Not only will they get to the page this way, they can also view the source code to
see the passwords and use them later. Thus, if you are protecting somethfng important, you should
use something more secure.

JavaScript Password Protection -I


A script that is a little better

In the last section, I introduced javascript password protection, but the script had a slight problem:
Netscape browsers would show the protected page momentarily even if the password was incor
rect. In this section, I will show you the samescript, but the difference is that it will use an intermedi
ate page so that The protected page is not displayed.

Warning: These scripts are not totally secure and your page can be seen if someone
gets through. Do NOT protect anything important with a script like this. Try looking fo
a CGI Script or ask your web host to set up an .ht password file if you need to protect
something important.

Now that I have said that so boldly, let's take a look at how this version of the script works. Try out the
example below:

1) You will need to place a link to the intermediate page on one of your pages. In my example, the
intermediate page is "jex10.htm". I put the link on this page, "jpass2.htm". Example below:
"jpass2.htm"

<BODY>
<A HREF="jex10.htm">Click to Enter</A>
</BODY>

84 Training Cycle 12
Wintech Computers Javascript

2) Now you need to create your intermediate page. In my case, this is "jex10.htm". You will need the
following script on this page:
"jex10.htm"

<HTML>
<HEAD>
<TITLE>lntermediate Page</TITLE>
<SCRIPT language="JavaScript">
<!--hide
var password=prompt('Enter the password:',");
var mypassword="cool";
if (password==mypassword)
{
window.location="jex11 .htm";
}
else

{
window.location="jpass2.htm";
}
//-->
</SCRIPT>'
</HEAD>
<BODY>&nbsp;</BODY>
</HTML>

This intermediate page is what does all the work. As you can see, if the password is correct, it takes
the user to the protected page. In the example, the protected page was "jex11.htm". You can re
place that with the url of the page you wish to protect.
If the password is incorrect, the user gets sent back to the page that contains your link to the
intermediate page. In my case, that is the very page you are looking at, "jpass2.htm".
Well, give it a try and see if it works better for you. Have fun!
So, why is it easy to hack the script? One way is for the viewer to disable javascript. Not only will they
get to the page this way, they can also view the source code to see the password and use it later.
Thus, if you are protecting something important, you should use something more secure.

Training Cycle 12 85
Wintech Computers Javascript

07) Find the invalid identifier in Java sript


A. current Website
B. #of Island
C.return
D.all of above

9) Special characters like \t, \n, \d, etc do not take effect unless enclosed in
A- script tag
B- formatted block
C- both A and B
D- none

10) Which of the following is a variable type in a Java script


A- "boolean"
B- "function"
C- "object"
D- all the above

11) If you want the value of a variable to be modifiable only by the main script or a
single function, but you need to loose it in another function then:-
A- declare the variable as a global
B- declare the variable as a local
C- pass the variable as a agrument to that function
D- none of the above

12) Using the key word bar when declaring a variable in a function insures that
A- the variable is local to that function
B- the variable is global variable
C- the variable can be used in the main script
D- none of the above

13) Type of null returns of the string


A- "undefined"
B- "string"
C- "number"
D- "object"

14) which of the operator precidence is correct


A- ()D

*/%
+-
Wintech Computers Javascript

Javascript Objective Questions

01) JavaScript was developed by


A. Microsoft
B. Apple
C.IBM
D. Netscape

02) JavaScript was earlier was Known as


A. LiveScript
B. CgiScript
C. jScript
D. python

03) JavaScript is used as


A. Client Side Scripting LAng.
B. Server Side Scripting LAng.
C . both a and b
D. none

04) Which one is true


A. JavaScript has no user InterFace, it relies on HTML yo provide means of
Interaction with user
B. javaScipt is Object Oriented Language
c. javaScipt is Browser independant
D. All of the above

05) JavaScript is
A.lnterpreted language
B. compiled language
C. both a and b
D. none

06) When you write JavaScript into a seperate file and call this file from a html
document on the file script tag line.you save the Javascript file with
A. .html
B. .ess
C. .js
d. Any of the above

07) The Default Scripting language of the browser which support Scripting language is
A. VBscript
B. jSCRIPT
C. JavaScript
D. python
Wintech Computers Javascript

B- ()[]
*/%
!++--
+-

c- on
*/%
+-

!++--
D- none

15) Javascript automatically converts the boolean value false to


A- 1
B- 1
C-0
D- none

16) Which of the following is a conversion function


A- oval()
B- Parselnt()
C- ParseFlo,at()
D- All the above

17) Which of the following is a complex variable type


A- arrays
B- objects
C- both A and B
D- none

18) x=5, y=7, then z=(x>y)? 5:7 will return


A-5
B-7
C-12
D- none of the above

19) which of the following is true


A- a function can get passed more agruments then were specified in the declaration
b- a function can get passed less agruments then were specified in the declaration
C- both A and B
D- none

20) the with statement is provided


A- as a convenience to eliminate retyping the name of an object that is to be
referenced in a series of property references and mehtod of invocation
B- to iterate a set of statement based on a loop condition and an update statement
C- both A and B
D- none
Wintech Computers Javascript

Solution box

Solution : 1-D, 2-A, 3-c, 5-A, 6-c, 7-b, 8-D, 9-c, 10-D, 11-c, 12-a, 13-D, 14-a, 15-c, 16-
17-c, 18-B, 19-c, 20-a

Javascript Subjective Questions

Q-1. What is the difference between Javascript and Jscript?


A-1. Javascript is a scripting language created by Netscape to allow programmers to rapidly create
code giving activity and functionality to webpages, above and beyond what is intrinsically
allowed in HTML. Netscape has continued to pustthe envelope of Javascript with Image
arrays and Layers and numerous other new features. Jscript is the common term used to
refer to Internet Explorer's bastardized version of Javascript. Jscript does not currently sup
port the more interesting features of Javascript, and improperly uses many of the common
Javascript features. The problems encountered in making Javascript programs work in both
browsers has led some to blame Javascript. The blame lays with Internet Explorer. Many
excellent sites simply will not work in Internet Explorer. We should not condemn these sites
because they are more interesting and useful than other sites.

Q-2. Can I use Javascript to see who is browsing to my pages?


A-2. No. At least not in Netscape 3.x, unless the user has turned off the security features. This is
on purpose for very good reasons. You as the user should not be harassed by merchants
and spies who home in on the fact that you simply visited a certain site. No one wants their
e-mail box filled with unwanted junk mail. If you browse to the more questionable sites, you
surely don't want blackmailers making your tastes public. There was a way in Netscape 2.0
to have the browser send silent e-mail to the webmaster. This method was deleted in NN
2.01 and above. If the user has the security alert checkbox set to OFF in NN2.X or3.x , then
it is possible to send mail without his knowledge, but I always leave mine on. It is possible
with CGI(Common Gateway Interface) or SSI(Server Side Includes) to record the domain
name of the browser you are using, but I know of no way to record the particulars of your
personal identity. This may or may not be true in Internet Explorer. There are some reported
security leaks in that program.

Q-3. Can you print out from Javascript?


A-3. Not from NN3.01. For security reasons, the browser cannot automatically access Windows
functions. You cannot make the browser do things like push buttons on the browser(unless
they were created by the html or Javascript program), print, access the computer's file struc
ture, start other windows programs, or affect other non-browser functions. NN4+ has the
ability to use signed scripts which allows the user to allow certain signatures to do special
actions like printing. Browsers which do not have these special signatures set cannot perform
these operations.

Q-4. Can I access functions in a frame or window from another frame or window?
A-4. Sure. The parent object is the way to access functions in other frames or windows.
Wintech Computers Javascript

Q-5. Is there a way to make the label on a button change when I put a mouse over the
button?
A-5. Not on a button, however, you can use an Image as a link and change the Image dynami
cally. Create multiple Images resembling buttons and use them in reference links. Then use
an onmouseover handler to change the Image.

Q-6. How do I make lines of text in alert boxes wrap properly?


A-6. Use \n where you want the line to break.

Q-7. How do I refresh my page?


A-7. Use the location object. Be aware that if you are letreshing the page you are on, any code
after the refresh statement will not be executed.

Q-8. Can I preload images?


A-8. Sure. Use
Imagel = new Image;
Image1.src="url";

Q-9. Can I use text files that can be written to the page by Javascript?
A-9. Sure. Netscape allows a feature called External files that can be loaded as a package of
Javascript functions or objects. The way to use them is

<SCRIPT SRC="filename.JS">
default text or html if the load fails
</SCRIPT>

Q-10. Can JavaScript Communicate With Java?


A-10. Yes. Within JavaScript you can create Java objects, call Java methods, and change Param
eter values in <EMBED> and <APPLET> tags. Built-in methods can generally be called
directly by using the full reference of packagename.classname.methodname. Applets with
public methods can be called with a reference to document.applet_name.method. Param
eter values can be referenced with document.applet_name.parameter. Netscape has more
information on LiveConnect

Q-11. Can Java Communicate With JavaScript?


A-11. Yes. Several methods exist within netscape.javascript.JSObject. From Java, you can call
JavaScript methods, evaluate JavaScript expressions, retrieve JavaScript objects, and set
the value of JavaScript objects. Netscape has an extensive discussion of the
netscape.javascript.JSObject object

Q-12. What are cookies and how do I use them?


A-12. The client can store relatively short bits of information in a file, called a cookie for no real
reason. Cookies are set from the server via HTTP headers in the format:

Set Cookie: name=value; expires=date; path=directory_path;


Wintech Computers
Javascript
domain=your_domain; secure
You set acookie by assigning a"Set Cookie" siring to the document.cookie object If an
unexpired cookie ,s found for the domain and path, your browser responds ^Cookie
name=value; name=value . You can then assign the document.cookie object to avaTbt.'
Q-13. How can Iuse quote marks inside a string?
A-13. In two ways. Quotes can be escaped like this: alertfThe girl yelled V'Over there.V The bear
^1-"
Over there! ^
ThehUt
bearf " Where,to,) come
seemed "V0UoutCanofUS6no Shg,e
where.')qUOt6S instead- al*^' Jri ye ed
0-14. Write aprogram of JS-Alert asking for astring input like the username?
A-14. ret = prompt("message","default_text");

Q'15' anArray[1].name
IT 'm6 anArray[1] =documentfo^1'"PutFieldName; Later, when Itry to use
or [1].value, its undefined
A-15 You have to first create the array using a constructor
var anArray = new Array();
Don Benish

Q'16' ?oirVret
Form? 2) Can ittV WHte mV
be written to a'Ppage?
addreSS? 1) Can *be Wrltten to a* box in say a
(reg html)
A-16. Use var a= location.hostname
You can use it anywhere you can use a string
Q-17.
when we try to write to my form fields WIndow.document.form.selectI has no prop
erty named selectedlndex' K p
A-17.
If there is more than one form you have to refer to it by name or by index
a=document.form1 .selectl .selectedlndex
a=document.form[0].select1 selectedlndex
Always name your forms and refer to them by name if possible.
Q-18. can Isupport real audio, and is any way to detect if the user supports realaudio? Can
we include sound effects as "onMouseOver" events?
A-18. Per "Using Javascript" This is accomplished by very briefly opening a sub window and
attempting to open a file of the given mime type in that window. If the plugin exists then the
script returns true. This code only checks to see if your browser has any plugin that reads that
mime type, not a specific plugin."

You can use the following code:


function probeplugin(mimetype){
var haveplugin=false;
var tiny = window.openf ","teensy","width=1,height=1")
if(tiny !=null){
if(tiny.document.open(mimetype) != null
haveplugin=true
tinyclose()
Wintech Computers
Javascript

}
return haveplugin
}

Q-19. If there is a JavaScript function that works with NN, but notwith MSIE. it can't be made
to work with MSIE, so how to get it to display in Netscape only.
A-19. Use the navigator object to choose what to display where.
Here is a sample of how to use this,
function choose(){
if(navigator.appName == "Netscape") location = "Cv ..start.htm";
else {location = "le start.htm";}
self.location}

Q-20. If a pagehas number of links listed on it and I want to be able to determine what links
people clicked on,how do io do it?
A-20 Make all your links set a variable like this:
var Iindex1=0;
var Iindex2=0;
<a href="blahblah" onClick="lindex1=1">
<a href="blahblah" onClick="lindex2=1">
or

var lindex= new Array(0,0,0,0,0,0,0,0);


<a href="blahblah" onClick="lindex[0]=1">
<a href="blahblah" onClick="lindex[1]=1">

Q-23. Is there a command to split a string?


A-23 . Use substring and indexOf methods.

firsthalf = whole.substring(0, whole.indexOf(':'));


secondhalf = whole.substring( whole.indexOf(':')+1,whole.length);

Q-24. Is there a way to change the text of a select box?


A-24. In the Javascript
formname.selectname.option[index].text = "Text";
history.go(O);
You could change all the entries this way. The important feature is thai you then
reload the page to get it to display the new values.

Q-25. I'm looking for a way so that when the i.iouse cursor is brought over an image, a sound
will play (perferably without opening another window).
A-25. Yes, it can be done in Navigator 3.0 or greater by using LiveConnect to manipulate
LiveAudio plug-in settings.
Check out:
http://webreference.com/javascript/960916/part02.html
(And for more excellent ideas, also check out:
http://webreference.com/javascript/tip_week_past.html
Wintech Computers
Javascript

You don't need to open other windows, or even use frames. (Just make sure you have both
Java and JavaScript enabled.) A brief example:
<embed src = "mysound.wav" name="mysound" hidden=true autostart=false mastersound>
<a href="#" onMouseOver="document.mysound.play(true)"
onMouseOut="document.mysound.stop()">
<img src="myimage.jpg">

Alternatively, you could remove the name attribute and refer to the embedded
object like this:

document.embeds[0].play(true)
and

document.embeds[0].stop()

Q-26. What Iwant to do is have aperson press abutton in frame 1, which causes aJavascript
function in frame 2 to redraw the screen. That seems pretty simple just reload the
page, but what if you want to pass some parameter to the function in frame 2 which
causes it to redraw differently?
A-26. Send your new variables as arguments to your location command. You can then
Use location.search to recover these arguments. Look at
http://web2.airmail.net/dbenish/javscrpt/Mconv020.htm or
http://web2.airmail.net/dbenish/javscrpt/jstest.htm
to see how this is done. The second link also demonstrates how to use .js files.

Q-27. When I have a child window opened I can look at it with my parent windpw to get a
value. If the child window is not open, how do Imake the function in the parent window
not give an error message when it tries to look for the value.
A-27. In the body tag of the child window use onLoad and onUnload set or reset a vaue in the
parent window.
<BODY onLoad-"opener.statdex=1" onUnload="opener.statdex=0">

Q-28. How do I pick a random image everytime anybody tries to load my page.
A-28. Dynamically write an image tag, inserting the randomly generted URL of the
image. You can do this with the background also by writing the whole body tag.
Q-29. I have a function that determines a value and then writes a string depending on the
value. When I place the function outside of a table it works fine, but when it is inside
the table it doesn't work.
A-29. This is a known problem with javascript.
The way to get around it is to dynamically write the whole html including the table.

You might also like