You are on page 1of 47

JavaScript

Introduction:

JavaScript is an interpreted programming language that can be embedded into an
HTML web page. Interpreted means that the entire web page is downloaded to the
browser and the JavaScript code is executed when an event is triggered. When the
code is executed it is interpreted one line at time. There are a number of events that
will trigger the execution of a JavaScirpt, like a click on a form button, or the
completion of a web page loading. It is platform specific.

JavaScript is a scripting language used in many websites. A scripting language is a
language, which is easy and fast to learn. A scripting language is interpreted in run-
time. It is not compiled like other languages as C++, C#, VB.NET etc. JavaScript is a
client side language and it runs on the client browser. JavaScript can be used on all
most known browsers. However JavaScript can be also used on the server-side. On
the server side you can use JavaScript for example to manage your database entry.
It can be easily used to interact with HTML elements. In other words, JavaScript is a
language that lets you make your pages interact with your readers and respond to
what they do. It is a programming language that can make your pages feel more
dynamic and give feedback to your user. You can validate text fields, disable
buttons, validate forms, or change the background color of your page. All this is
possible with JavaScript. Like each programming language, it contains variables,
arrays, functions, operators, objects and much more which can be help you to create
better scripts for your pages. JavaScript is an object-oriented scripting language that
lets you build interactions between page content, the state of the browser, and the
actions of the reader. JavaScript code can be inserted directly in the HTML or you
can place it in a separate file with the .js extension and link the web page with the .js
file.

The JavaScript language was developed by the Netscape Communications
Corporation and is a trademarked name. It is a cross-platform, object-based
scripting language that was originally designed for use in Netscape Navigator.
Indeed, versions 2.0, and later, of Navigator can interpret JavaScript statements that
are embedded within HTML code. When a request is made to see a page, the HTML
code that defines the requested page along with the embedded JavaScript
statements, are sent by the server to the client. Navigator interprets the HTML
document and executes the JavaScript code. The resultant page is displayed for the
client. It is important to understand that this interpretation occurs on the client-side
rather than the server-side.

After the success of JavaScript in Navigator 2.0, the Microsoft Corporation was quick
to create a clone of JavaScript, called JScript, which is a trademarked name that is
designed to run inside the Microsoft Internet Explorer. In truth, except for a few
minor differences, JScript is essentially a carbon copy of JavaScript.
JavaScript is a simple to comprehend, easy to use, general purpose scripting
language. When used in conjunction with a Web browser's Document Object Model
(DOM), it can produce powerful dynamic HTML browser-based applications which
also can feature animation and sound.

JavaScript code is placed within the <STYLE> and </STYLE> tags. Script tags can
be put into inside the Header or inside the Body tags. This tells the browser that the
flowing bunch of code bounded within <SCRIPT> and </SCRIPT> tags is not HTML
to be displayed but rather the code to be processed. One important attribute that is
used with <SCRIPT> tag is type and language. This tells the browser which scripting
language is used.

Basic format:
<HTML>
<HEAD>
<SCRIPT language=”JavaScript” type=”text/javascript”>
---------
---------
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT language=”JavaScript” type=”text/javascript”>
----------
----------
</SCRIPT>
</BODY>
</HTML>

Example:
<HTML>
<HEAD>
<SCRIPT language=”JavaScript”>
document.write = “Hello to JavaScript”;
</SCRIPT>
</HEAD>
</HTML>

The above example displays the text “Hello to JavaScript” in the browser.

JavaScript Vs Java:

JavaScript Java
Interpreted (not compiled) by client. Compiled bytecodes downloaded from
server, executed on client.
Object-oriented. No distinction between Class-based. Objects are divided into
types of objects. Inheritance is through classes and instances with all inheritance
the prototype mechanism, and properties through the class hierarchy. Classes and
and methods can be added to any object instances cannot have properties or
dynamically. methods added dynamically.
Variable data types not declared Variable data types must be declared
(dynamic typing). (static typing).
Code integrated with, and embedded in, Applets distinct from HTML (accessed
HTML. from HTML pages).

Core JavaScript

Client-side and server-side JavaScript have the following elements in common:
1. Keywords
2. Statement syntax and grammar
3. Rules for expressions, variables, and literals
4. Underlying object model (although client-side and server-side JavaScript
have different sets of predefined objects)
5. Predefined objects and functions, such as such as Array, Date, and Math

Client-Side JavaScript:

When the browser (or client) requests a page, the server sends the full content of
the document, including HTML and JavaScript statements, over the network. The
client reads the page from top to bottom, displaying the results of the HTML and
executing JavaScript statements as it goes. Client-side JavaScript statements
embedded in an HTML page can respond to user events such as mouse clicks. For
example, you can write a JavaScript function to verify that users enter valid
information into a form requesting a telephone number or zip code. Without any
network transmission, the embedded JavaScript on the HTML page can check the
entered data and display a dialog box to the user who enters invalid data.
Client side JavaScript accommodates the wide range of document object models
that are spread among numerous browser brands, operating systems, and versions.

Server-Side JavaScript:

JavaScript is also embedded in HTML pages on server-side. The server-side
statements can connect to relational databases, share information across users of
an application, access the file system on the server, or communicate with other
applications. JavaScript applications that use server-side JavaScript are compiled
into bytecode executable files. These application executables are run in concert with
a web server that contains the JavaScript runtime engine. When a page in the
application is requested by a client browser, the runtime engine uses the application
executable to look up the source page and dynamically generate the HTML page to
return. It runs any server-side JavaScript statements found on the page. The result
of those statements might add new HTML or client-side JavaScript statements to the
HTML page. It then sends the resulting page over the network to the client, which
displays the results

Server-side JavaScript during development

Server-side JavaScript during runtime
Client Side Vs Server Side JavaScript:

Client Side JavaScript Server Side JavaScript
Tags <SCRIPT> <SERVER>
Execution Client browser Server (compiled into SSJS byte code)
(interpreted)
Compilation Not compiled Application file (.web)
Client JavaScript-enabled Any browser
Server Any server JavaScript-enabled

When to Use JavaScript?

When faced with a Web application task, I look to client-side JavaScript for help with
the following requirements:
Data entry validation: If form fields need to be filled out for processing on the
server, I let client-side scripts prequalify the data entered by the user.
Serverless CGIs: I use this term to describe processes that were it not for
JavaScript, would be programmed as CGIs on the server, yielding slow performance
because of the interactivity required between the program and user. This includes
tasks such as small data collection lookup, modification of images, and generation of
HTML in other frames and windows based on user input.
Dynamic HTML interactivity: It’s one thing to use DHTML’s capabilities to precisely
position elements on the page—you don’t need scripting for that. But if you intend to
make the content play on the page, scripting makes that happen.
CGI prototyping: Sometimes you may want a CGI program to be at the root of your
application because it reduces the potential incompatibilities among browser brands
and versions. It may be easier to create a prototype of the CGI in client-side
JavaScript.
Offloading a busy server: If you have a highly trafficked website, it may be
beneficial to convert frequently used CGI processes to client-side JavaScript scripts.
Once a page is downloaded, the server is free to serve other visitors. Not only does
this lighten server load, but users also experience quicker response to the
application embedded in the page.
Adding life to otherwise dead pages: HTML by itself is pretty “flat.” Adding a
blinking chunk of text doesn’t help much; animated GIF images more often distract
from, rather than contribute to, the user interest at your site. But if you can dream up
ways to add some interactivity to your page, it may engage the user and encourage
a recommendation to friends or repeat visits.
Creating “Web pages that think”: You can make your web page think in the way
that they take the decision of their own on execution of some actions.

Document Object Model
To help scripts control various objects/elements, the browser makers define a
Document Object Model (DOM). A model is like a prototype or plan for the
organization of objects on a page. Below fig. shows a map of the lowest common
denominator object model, which is safe to use on all browsers.

The relationship of all objects with each other is explained below:

Window object: At the top of the hierarchy is the window. This object represents the
content area of the browser window where HTML documents appear. In a multiple-
frame environment, each frame is also a window (but don’t concern yourself with this
just yet). Because all document action takes place inside the window, it is the
outermost element of the object hierarchy. Its physical borders contain the
document.

Document object: Each HTML document that gets loaded into a window becomes
a document object. Its position in the object hierarchy is an important one, as you
can see in Figure 4-6. The document object contains most of the other kinds of
objects in the model. This makes perfect sense when you think about it: The
document contains the content that you are likely to script. The biggest improvement
is that every HTML element becomes an object that scripts can manipulate.

Form object: Users don’t see the beginning and ending of forms on a page, only
their elements. But a form is a distinct grouping of content inside an HTML
document. Everything that is inside the <FORM>...</FORM> tag set is part of the
form object. A document might have more than one pair of <FORM> tags if dictated
by the page design.
Form control elements: Just as your HTML defines form elements within the
confines of the <FORM>...</FORM> tag pair, so does a form object contain all the
elements defined for that object. Each one of those form elements—text fields,
buttons, radio buttons, checkboxes, and the like—is a separate object.

Comments

Text which is commented is ignored by the interpreter from that point to the end of
the line. There are two types of comments: those that run to the end of the current
line and those that span multiple lines. Single-line comments begin with a double
forward slash (//). For example:
var count = 10; // holds number of items the user wishes to purchase

Comments spanning multiple lines are enclosed between a slash-asterisk (/*) and
asterisk-slash (*/) pair. For example:
/*var count = 10;
var y = square(10);*/

Conventions

• JavaScript is case-sensitive.

• At the end of every JavaScript statement, semicolon is required which
indicates the end of statement. For eg:
var x = 0;

• The double quotation mark can be found within strings that start, and end with
(are delimited by) single quotes (‘He said, “JavaScript is an interesting language.”
‘)

• The single quotation mark can be used within a string delimited by double
quotation marks.

• JavaScript ignores spaces, tabs, and newlines that appear in statements.
However it recognizes spaces, tabs, and tabs that are part of string. For eg:
var x=0; is same as var x = 0;

• The backslash (\) is followed by another character that represents something
in a string that cannot be typed on keyboard. The \ tells the interpreter that in this
case it should print the character and not interpret as a delimiter. For eg:
‘You\nPressed\nEnter key’

‘\n’ represents carriage return and a line feed. The result of above eg. is :
You
Pressed
Enter key

These backslashes and letter combination is known as Escape Sequences.
Some common of them are listed below:
\b backspace
\f form feed
\n new line
\r carriage return (no line feed)
\t tab
\’ single quote
\” double quotes

Data Types

Various data types in JavaScript are as follows:
1. Numerical Data: This consists of numbers both integer and floating. For
example 17, 21.5 etc
2. Text: Also called String. This consists of text specified within single or double
quotes. For example “Hello”, ‘World’ etc
3. Boolean: This consists of Boolean value i.e. true or false.

Declaring and Initializing Variables

A variable can be declared by using var keyword. For example
var sum;
A variable can be assigned value as:
var name = “Hello”;

Every JavaScript variable has a data type, but the type is inferred from the variable’s
content. For example, a variable that is assigned a string value assumes the string
data type. A consequence of JavaScript’s automatic type inference is that a
variable’s type can change during script execution. For example, a variable can hold
a string at one point and then later be assigned a Boolean. Its type changes
according to the data it holds. There is no need to indicate type in variable
declarations.

To check the type of variable, typeof operator is used. For eg:
var x = “5”;
alert (typeof x);
The output is string. alert () function is used to display text in message box. It will be
explained later.
.
Data Type Conversion

JavaScript tries its best to perform internal conversions to solve data type
conversion, but JavaScript cannot read your mind. If your intentions differ from the
way JavaScript treats the values, you won’t get the results you expect.

A case in point is adding numbers that may be in the form of text strings. In a simple
arithmetic statement that adds two numbers together, you get the expected result:
3 + 3 // result = 6

But if one of those numbers is a string, JavaScript leans toward converting the other
value to a string—thus turning the plus sign’s action from arithmetic addition to
joining strings. Therefore, in the statement
3 + “3” // result = “33”
the “string-ness” of the second value prevails over the entire operation. The first
value is automatically converted to a string, and the result joins the two strings.
Look what happens when another number is added to the statement:
3 + 3 + “3” // result = “63”
This might seem totally illogical, but there is logic behind this result. The expression
is evaluated from left to right. The first plus operation works on two numbers,
yielding a value of 6. But as the 6 is about to be added to the “3,” JavaScript lets the
“string-ness” of the “3” rule. The 6 is converted to a string, and two string values are
joined to yield “63.”

Operators

Lots of operators are used in various expressions. Various categories are described
below:
Assignment Operator: the most basic operator is the assignment operator (=),
which is used to assign a value to a variable. Often this operator is used to set a
variable to a value. For eg:
var str = “Hello”;

Generally, the assignment operator is used to assign a value to a single variable, but
it is possible to perform multiple assignments at once by stringing them together with
the = operator. For eg:
var x = y = z = 7;

Assignments can also be used to set a variable to hold the value of an expression.
For eg:
var x = 12 + 5;

Arithmetic Operators: JavaScript supports all the basic arithmetic operators like
addition (+), subtraction (–), multiplication (*), division (/), and modulus (%, also
known as the remainder operator). For eg:
var x = 10 + 5;
Comparison Operators: these operators compare values in scripts—whether two
values are the same. These kinds of comparisons return a value of the Boolean type
—true or false. The operator that tests whether two items are equal consists of a pair
of equal signs to distinguish it from the single equal sign assignment operator. Other
comparison operators are listed below:
== Equals
! Not
!= Does not equal
> Is greater than
>= Is greater than or equal to
< Is less than
<= Is less than or equal to
For eg:
4<8

String Concatenation Using +: The addition operator (+) has a different behavior
when operating on strings as opposed to numbers. In this other role, the + operator
performs string concatenation. For eg:
document.write("JavaScript is " + "great.");

outputs the string "JavaScript is great" to the document.
You can join any number of strings or literals together using this operator.

Logical Operators: You can join any number of strings or literals together using this
operator. Various logical operators are listed below:
+ Addition
* Multiplication
- Substraction
/ Division
% Modulous
&& Logical AND
|| Logical OR

Bitwise Operators: Computers work with bits and bytes. These operators work with
bits i.e. zeros and ones. These operators are rarely used. These operators are listed
below:
` bitwise NOT
<< bitwise Shift Left
>> bitwise Shift Right
>>> Unsigned Shift Right
& bitwise AND
^ bitwise XOR
| bitwise OR
Ternary Operator: The ?: operator is used to create a quick conditional branch. The
basic syntax for this operator is
(expression) ? if-true-statement : if-false-statement;
where expression is any expression that will evaluate eventually to true or false. If
expression evaluates true, if-true-statement is evaluated. Otherwise, if-false-
statement is executed. In this example,
(x >> 5) ? alert("x is greater than 5") : alert("x is less than 5");

typeof Operator: typeof operator defines the kind of value to which a variable or
expression evaluates. Typically, this operator is used to identify whether a variable
value is one of the following types: number, string, boolean, object, function, or
undefined. For eg:
if (typeof myVal == “number”)
{
myVal = parseInt(myVal)
}

Increment & Decrement Operator: The ++ operator is used to increment—or,
simply put, to add 1—to its operand. For example, with
var x=3;
x++;
the value of x is set to 4.

Similar to the ++ operator is the -- operator, used to decrement (subtract one from)
its operand. So,
var x=3;
x--;
leaves a value of 2 in the variable x. Of course, this statement could also have been
written the “long” way:
x=x-1;

new Operator: Most JavaScript core objects have constructor functions built into the
language. To access those functions, you use the new operator along with the name
of the constructor. The function returns a reference to the object instance, which
your scripts can then use to get and set properties or invoke object methods. For
example, creating a new date object requires invoking the Date object’s constructor,
as follows:
var today = new Date()

this Operator: JavaScript includes an operator that allows script statements to refer
to the very object in which they are located. The self-referential operator is this. The
most common application of the this operator is in event handlers that pass
references of themselves to functions for further processing, as in
<INPUT TYPE=”text” NAME=”entry” onChange=”process (this)”>
Because this operator references an object, that object’s properties can be exposed
with the aid of the operator. For eg., to send the value property of a text input object
to a function, the this operator stands in for the current object reference and
appends the proper syntax to reference the value property:
<INPUT TYPE=”text” NAME=”entry” onChange=”process(this.value)”>
this operator also works inside other objects, such as custom objects. When you
define a constructor function for a custom object, using this operator to define
properties of the object and assign values to those properties is common practice.
Consider the following example of an object creation sequence:
function bottledWater(brand, size, flavor)
{
this.brand = brand
this.size = size
this.flavor = flavor
}
var myWater = new bottledWater(“Crystal Springs”, 16, “original”)

Control Structures

The kinds of statements that make decisions and loop around to repeat themselves
are called control structures. A control structure directs the execution flow through a
sequence of script statements based on simple decisions and other factors. An
important part of a control structure is the condition. A program sometimes have to
branch to an execution route if a certain condition exists. Each condition is an
expression that evaluates to true or false. JavaScript provides several kinds of
control structures for different programming situations. Three of the most common
control structures you’ll use are if constructions, if...else constructions, and for loops.

If Structure

if statement is JavaScript’s basic decision-making control statement. It allows your
program to perform a test and act based on the results of the test. The syntax is:
if (condition)
{
statement[s] if true
}
For eg:
var x = 5;
if (x >> 1)
{
alert("x is greater than 1");
}
alert("moving on ...");

The expression evaluates to true, displays the message “x is greater than 1,” and
then displays the second alert dialog afterward. However, if the value of variable x
were something like zero, the expression would evaluate false, resulting in skipping
the first alert and immediately displaying the second one.
if . . . else structure

In the plain if construction, no special processing is performed when the condition
evaluates to false. But if processing must follow one of two special paths, you need
the if...else structure. The syntax is as follows:
if (condition)
{
statement[s] if true
}
else
{
statement [s] if false
}
For eg:
if (sum ==0)
{
sum = x +y;
}
else
{
subtotal =sum ;
}

If sum equals to 0 then sum equals x plus y, or else subtotal equals sum.

if…else if structure

More advance than if..else is if…else if construct. You can evaluate your more than
more one conditions and can process it. The syntax is as follows:
if (expression1)
statement or block
else if (expression2)
statement or block
else if (expression3)
statement or block
...
else
statement or block
For eg:
If (x>5)
{
alert (“x is greater than 5”);
}
else if (x<10)
{
alert (“x is less than 10”);
}
else
{
alert (“unknown”);
}

The above code checks for the value of x. if it is greater than 5, 1 st block is executed.
If it is less than 10, 2nd block is executed. If both the conditions are false, last block is
executed.

switch
The switch statement is used when a variable may take a number of values and you
want to test for some of those values. The basic syntax of the switch statement is to
give an expression to evaluate and several different statements to execute based on
the value of the expression. The interpreter checks each case against the value of
the expression until a match is found. If nothing matches, a default condition will be
used. The syntax is as follows:
switch (expression)
{
case condition 1: statement(s)
break;
case condition 2: statement(s)
break;
...
case condition n: statement(s)
break;
default: statement(s)
}
The break statement indicates the end of that particular case. If they were omitted,
the interpreter would continue executing each statement. For eg:
var yourGrade='A';
switch (yourGrade)
{
case 'A': alert("Good job.");
break;
case 'B': alert("Pretty good.");
break;
case 'C': alert("You passed!");
break;
case 'D': alert("Not so good.");
break;
case 'F': alert("Back to the books.");
break;
default: alert("Grade Error!");
}
continue

The continue statement tells the interpreter to immediately start the next iteration of
the loop. When it’s encountered, program flow will move to the loop check
expression. The below example shows how the continue statement is used to skip
printing when the index held in variable x reaches 8:
var x = 0;
while (x << 20)
{
x = x + 1;
if (x == 8)
continue; // continues loop at 8 without printing
document.write(x+"<<br />>");
}

The break statement, is used to exit a loop early, breaking out of the enclosing curly
braces. The example below breaks out early once x reaches 8:
var x = 1;
while (x << 20)
{
if (x == 8)
break; // breaks out of loop completely
x = x + 1;
document.write(x+"<<br />>");
}
Loops

A loop is a structure that forces the statements contained within its delimiters to
execute over and again until a condition is met and at that point loop ends.

while

The purpose of a while loop is to execute a statement or code block repeatedly as
long as expression is true. Once expression becomes false or a break statement is
encountered, the loop will be exited. While loops are useful when you don’t know
how many times you have to loop, but you know you should stop when you meet the
condition. The syntax is as follows:
while (expression)
{
statement or block of statements to execute
}
For eg:
var count = 0;
while (count < 10)
{
document.write(count+"<<br />>");
count++;
}
document.write("Loop done!");

for

for loops are useful when you know exactly how many times you want the loop to
execute. The initialization statement is executed before the loop begins, the loop
continues executing until test condition becomes false, and at each iteration the
iteration statement is executed. The syntax is as follows:
for (initialization; test condition; iteration statement)
{
loop statement or block
}
For eg:
for (var i = 0; i < 10; i++)
document.write ("Loop " + i + "<<br />>");
It prints the numbers zero through nine.

Functions

Functions allow you to create bunch of code that perform specific task. JavaScript
has a number of built-in functions that are part of the language. It also allows the
user to create its own functions. A function is capable of returning a value to the
statement that invoked it, but this is not a mandatory. The function can return the
value using return keyword. When a function returns a value, the calling statement
treats the function call like any expression—plugging in the returned value right
where the function call is made. Function can return only one value. The syntax is as
follows:
function functionName ( [parameter1]...[,parameterN] )
{
statement[s]
}
A simple function that takes no parameters called sayHello is defined below:
function sayHello()
{
alert("Hello there");
}
To invoke the function somewhere later in the script, you have to write the statement
something like this:
sayHello();
You also can define functions so they receive parameter values from the calling
statement. Below eg. shows a simple document that has a button whose onClick
event calls a function while passing text data to the function.
<html>
<head>
<script language=”JavaScript”>
function showMsg(msg)
{
alert(“The button sent: “ + msg)
}
</script>
</head>
<body>
<form>
<input type=”button” value=”Click Me” onClick=”showMsg
(‘The button has been clicked!’)”>
</form>
</body>
</html>

When a function receives parameters, it assigns the incoming values to the variable
names specified in the function definition’s parentheses. Consider the following
script segment:
function sayHiToFirst(p, q, r)
{
alert(“Say hello, “ + a)
}
sayHiToFirst(“A”, “B”, “C”)
sayHiToFirst(“X”, “Y”, “Z”)
After the function is defined in the script, the next statement calls that function,
passing three strings as parameters. The function definition automatically assigns
the strings to variables p, q, and r. Therefore, before the alert() statement inside the
function ever runs, p evaluates to “A,” q evaluates to “B,” and r evaluates to “C.” In
the alert() statement, only the p value is used and the alert reads
Say hello, A
When the user closes the first alert, the next call to the function occurs. This time
through, different values are passed to the function and assigned to p, q, and r. The
alert dialog box reads
Say hello, D

Returning values from function is demonstrated as below:
function addThree(arg1, arg2, arg3)
{
return (arg1+arg2+arg3);
}
var x = 5, y = 7, result;
result = addThree(x,y,11);
alert(result);

Variable Scope
There are only two basic scopes: global and local. Variables defined outside of
functions are called global variables. They are known (“visible”) throughout a
document. Variables defined inside functions are called local variables. It is limited to
the particular block of code it is defined within. The body of a function has its own
local scope. Local scope allows for the reuse of variable names within a document.
For eg:
<html>
<head>
<script language=”JavaScript”>
var aBoy = “John // global
var hisDog = “Snoopy” // global
function demo()
{
// using improper design to demonstrate a point
var hisDog = “Tommy // local version of hisDog
var output = hisDog + “ does not belong to “ +
aBoy + “.<BR>”
document.write(output)
}
</script>
</head>
<body>
<script language=”JavaScript”>
demo() // runs as document loads
document.write(hisDog + “ belongs to “ + aBoy + “.”)
</script>
</body>
</html>
When the page loads, the script in the Head portion initializes the two global
variables (aBoy and hisDog) and defines the demo() function in memory. In the
Body, another script begins by invoking the function. Inside the function, a local
variable is initialized with the same name as one of the global variables—hisDog. In
JavaScript, such a local initialization overrides the global variable for all statements
inside the function. (But note that if the var keyword is left off of the local
initialization, the statement reassigns the value of the global version to “Tommy.”)
Another local variable, output, is used to store text which is to be written on the
screen. The accumulation begins by evaluating the local version of the hisDog
variable. Then it concatenates some hard text. Next comes the evaluated value of
the aBoy global variable—any global not overridden by a local is available for use
inside the function. The expression is accumulating HTML to be written to the page,
so it ends with a period and a <BR> tag. The final statement of the function writes
the content to the page. After the function completes its task, the next statement in
the Body script writes another string to the page. Because this script statement is
executing in global space, it accesses only global variables— including those
defined in another <SCRIPT> tag set in the document. By the time the complete
page finishes loading, it contains the following text lines:
Tommy does not belong to John.
Snoopy belongs to John.

What are Events?

Events are signals generated when specific actions occur. Scripts can be built to
react to these events. Various events available in JavaScript are as follows:
1. Abort:
This event is occurs when the user cancels loading of an image.

2. Blur:
This event occurs when input focus is removed from a form element or focus is
removed from a window.

3. Click:
This event occurs when the user clicks on a link or form element.

4. Double Click:
This event occurs when the user double clicks on a link or form element.

5. Change:
This event occurs when the value of a form field is changed by the user.

6. Drag Drop:
This event occurs when an icon is dragged and dropped into the browser.

7. Error:
This event occurs when an error occurs during loading of document or image.

8. Focus:
This event occurs when input focus is given to a form element or a window by
clicking on it or by pressing TAB key.

9. Load:
This event occurs when a page is loaded in the browser.

10. Mouse Down:
This event occurs when the user presses a mouse button.

11. Mouse Move:
This event occurs when the user moves the mouse.
12. Mouse Out:
This event occurs when the user moves the pointer off of a link or clickable area of
an imagemap.

13. Mouse Over:
This event occurs when the user moves the pointer over a hypertext link.

14. Mouse Up:
This event occurs when the user releases a mouse button.

15. Key Down:
This event occurs when the user presses any key.

16. Key Press:
This event occurs when the user presses or holds down a key.

17. Key Up:
This event occurs when the user releases a key.

18. Move:
This event occurs when the user moves the browser window or frame.

19. Resize:
This event occurs when the user resizes the browser window or frame.

20. Reset:
This event occurs when the user clears a form using the reset button.

21. Select:
This event occurs when the user selects text within the field.

22. Submit:
This event occurs when a form is submitted.

23. Unload:
This event occurs when the user leaves the page.

What are Event Handlers?

Event handlers are small JavaScript code placed inside an HTML tag. Event
Handlers are scripts in the form of attributes of specific HTML tags. They help in
handling (catching) events. The basic format of an event handler is:

<html_tag other_attributes event_handler=”Javascript Program;”>
Any JavaScript statements or functions can appear within the quotation marks of an
event handler. For example, if you have a form with a text field and want to call the
function checkField() whenever the value of text field changes, you should define as:

<input type=”text” onChange=”checkField();”>

Various event handlers are as follows:
onAbort onKeyDown
onBlur onKeyPress
onClick onKeyUp
onDblClick onMove
onChange onResize
onDragDrop onReset
onError onSelect
onFocus onSubmit
onLoad onUnload
onMouseDown
onMouseMove
onMouseOut
onMouseOver
onMouseUp

Below table shows which window and form elements have event handlers available
to them:

Sr. Object Event Handlers Available
No.
1 Selection List onBlur, OnChange, OnFocus
2 Text onBlur, OnChange, OnFocus, onSelect
3 Textarea onBlur, OnChange, OnFocus, onSelect, onKeyDown,
onKeyPress
4 Button onClick, onBlur, onFocus, onMouseDown, onMouseUp
5 Checkbox onClick, onBlur, onFocus
6 Radio Button onClick, onBlur, onFocus
7 Hypertext Link onClick, onMouseOver, onMouseOut, onKeyDown,
onKeyPress, onMouseDown, onMouseOut, onMouseOver,
onMouseUp

8 Clickable onMouseOver, onMouseOut
Image Area
9 Reset onClick, onBlur, onFocus
10 Submit onClick, onBlur, onFocus
11 Document onLoad, onUnload, onError, onClick, onDblClick,
onKeyDown, onKeyPress, onMouseDown, onMouseUp
12 Window onLoad, onUnload, onBlur, onFocus, onDragDrop, onError,
onResize
13 Framesets onBlur, onFocus, onMouseMove
14 Form onSubmit, onReset, onLoad
15 Image onLoad, onError, onAbort, onKeyDown, onKeyPress,
onMouseOut, onMouseOver

Arrays

In JavaScript arrays are considered as an Object. An array is stored in a variable, so
when you create an array you assign the new array object to the variable. A special
keyword new preceding a call to the JavaScript function that generates arrays
creates space in memory for the array. An optional parameter to the Array() function
enables you to specify at the time of creation how many elements (rows) of data
eventually will occupy the array. You can change the size of an array at any time.
Therefore, you can omit a parameter when generating a new array. For example

var arr1 = new Array();
var arr2 = new Array(10);

Statement 1 in the above example will declare arr1 as an array with no data limits.
While in statement 2 arr2 is declared as array with 10 data elements.

Vales in an array can be assigned as given below:

arr1[0] = “1”;
arr1[1] = “2”;
……..
……..
arr1[9] = “10”;

The array index is the key to accessing an array element. The name of the array and
an index in square brackets evaluates to the content of that array location. For
example:

arr1[0];
arr1[1];
………
………
arr1[9];
Example:
<html>
<head>
<title>Single Dimension Array Example</title>
</head>
<body>
<script language=”JavaScript”>
var myArray = new Array();

myArray[0] = “Bob”;
myArray[1] = “Peter”;
myArray[2] = “Paul”;

document.write (“myArray[0] = “ + myArray[0] + “ <br>”);
document.write (“myArray[1] = “ + myArray[1] + “ <br>”);
document.write (“myArray[2] = “ + myArray[2] + “ <br>”);

myArray[1] = Changed”;
document.write (“myArray[1] changed to = “ + myArray[1]
+ “ <br>”);
</script>
</body>
</html>

Although not explicitly included in the language, most JavaScript implementations
support a form of multidimensional arrays. A multidimensional array is an array that
has arrays as its elements.

Example:
<html>
<head>
<title>Multi Dimension Array</title>
</head>
<body>
<script>
var personnel = new Array();

personnel[0] = new Array();
personnel[0][0] = ‘Name0’;
personnel[0][1] = ‘Age0’;
personnel[0][2] = ‘Address0’;

personnel[1] = new Array();
personnel[1][0] = ‘Name1’;
personnel[1][1] = ‘Age1’;
personnel[1][2] = ‘Address1’;

personnel[2] = new Array();
personnel[2][0] = ‘Name2’;
personnel[2][1] = ‘Age2’;
personnel[2][2] = ‘Address2’;

document.write(“Name:” + personnel[1][0] + “<br>”);
document.write(“Age:” + personnel[1][1] + “<br>”);
document.write(“Address:” + personnel[1][2] + “<br>”);
</script>
</body>
</html>

The length property retrieves the index of the next available (unfilled) position at the
end of the array. Even if some lower indices are unused, length gives the index of
the first available slot after the last element. Consider the following:
var myArray = new Array();
myArray[1000] = "This is the only element in the array";
alert(myArray.length);
Even though myArray only has one element at index 1000, as we see by the alert
dialog myArray.length, the next available slot is at the end of the array, 1001. The
length property is automatically updated as new elements are added to the array.

Setting length to a value greater than the index of the last valid element has no
effect on the array contents, though it will increase the number of undefined slots in
the array. Consider, for example, the result of the following script,
var myArray = ["red", "green", "blue"];
myArray.length = 20;
alert("myArray="+myArray);
the output is:

Array has various methods. They are described as follows:
1. push(), pop(), shift(), unshift():
push() method appends the element to the end of the array and increases the
length property accordingly. pop() method removes the array element from end
and decreases the length property accordingly. For eg:
var stack = [ ]; // [ ]
stack.push("first"); // ["first"]
stack.push(10, 20); // ["first", 10, 20]
stack.pop(); // ["first", 10] Returns 20
stack.push(2); // ["first", 10, 2]
stack.pop(); // ["first", 10] Returns 2
stack.pop(); // ["first"] Returns 10
stack.pop(); // [ ] Returns "first"
unshift() and shift() methods work same as push() and pop(), except that they add
and remove data from the front of the array. Invoking unshift() inserts its arguments
(in order) at the beginning of the array, shifts existing elements to higher indices, and
increments the array’s length property accordingly. For example,
var myArray = [345, 78, 2];
myArray.unshift(4,"fun");
alert(myArray);
adds two more elements to the front of the array, as shown below:

2. concat():
The concat() method returns the array resulting from appending its arguments to the
array on which it was invoked. For eg:
var myArray = ["red", "green", "blue"];
alert(myArray.concat("cyan", "yellow"));
the output is shown here:

3. join():
The join() method converts the array to a string and allows the programmer to
specify how the elements are separated in the resulting string. When you print an
array, the output is a comma-separated list of the array elements. You can use join()
to format the list separators as you like. Fro eg:
var myArray = ["red", "green", "blue"];
var stringVersion = myArray.join(" / ");
alert(stringVersion);
4. reverse():
Objects

1. Document

The Document object provides access to the elements in an HTML page from within
your script. This includes the properties of every form, link and anchor (and, where
applicable, any sub-elements), as well as global Document properties such as
background and foreground colors.

Example:
<HTML>
<HEAD>
<TITLE>Document Object Example</TITLE>
<SCRIPT type="text/JavaScript">
function documentPropertiesMethods(form)
{
document.alinkColor = "Red";
//document.linkColor = "Green";
document.vlinkColor = "Blue";
//alert("links" + " " + document.Links);
alert("anchors" + " " + document.anchors.length);
document.bgColor = "00ffff";
//document.fgColor = "Red";
alert("forms" + " " + document.forms.length);
alert("images" + " " + document.images.length);
alert("lastmodified" + " " + document.lastModified);
alert("title" + " " + document.title);

var myPage = "all HTML coding here";
document.open();
document.write(myPage);
document.writeln("2nd time");
document.close();
}
</SCRIPT>
</HEAD>
<BODY>
<FORM name="form1">
<A href = "Alert.html">Hello</A>
<A name = "anchor1">World1</A>
<A name = "anchor2">World2</A>
<BR>
<IMG src = "E:\Neeta\Images\cyto.jpg" height=200
width=200>
<INPUT type="submit"
onClick="documentPropertiesMethods(this.form);">
</FORM>
</BODY>
</HTML>

Properties

• alinkColor:

Syntax: document.alinkColor = "colorinfo"

This property defines the color of an active link. The "color info" argument is a string
that can contain either the hexadecimal definition of the color or its literal description.
If you use the hex definition of a color it must be in the format rrggbb - for example,
the hex value for the named color 'forest green' is '228B22'.

• anchors:

This property is an array containing references to all the named Anchor objects in
the current document. These references are stored in the array in the order in which
they are defined in the source code. The "anchorID" argument is used to access
items in the array and this can either be a string containing the anchor name as
defined within the <A></A> tags in the HTML source, or an integer (with '0' being the
first item in the array).

Both examples below return the same results; the first uses the defined names of
the anchors and the second uses their reference number within the array.

• applets:

Syntax: document.applets["appletID"]

This property is an array containing references to all the Applet objects in the current
document. These references are stored in the array in the order in which they are
defined in the source code. The "appletID" argument is used to access items in the
array and this can either be a string containing the applet name as defined within the
<APPLET> tags in the HTML source, or an integer (with '0' being the first item in the
array).

• bgColor:

Syntax: document.bgColor = "colorinfo"
This property defines a document's background color. The "colorinfo" argument is a
string that can contain either the hexadecimal definition of the color or its literal
description. If you use the hex definition of a color it must be in the format rrggbb -
for example, the hex value for the named color 'forest green' is '228B22'.

• fgColor:

Syntax: document.fgColor = "colorinfo"

This property defines a document's foreground (text) color. The "colorinfo" argument
is a string that can contain either the hexadecimal definition of the color or it's literal
description. If you use the hex definition of a color it must be in the format rrggbb -
for example, the hex value for the named color 'forest green' is '228B22'.

• formName:

Syntax: document.formname

Every form in a document has a separate document object property, the name of
which is taken from the value assigned to the form with the <FORM NAME =
"formID"> tag. Any form in the document can then be referred to with the syntax
below.

• forms:

Syntax: document.forms["formID" ]

This property is an array containing references to all the Form objects in the current
document. These references are stored in the array in the order in which they are
defined in the source code. The "formID" argument is used to access items in the
array and this can either be a string containing the form name as defined within the
<FORM> tag in the HTML source, or an integer (with '0' being the first item in the
array).

• images:

Syntax: document.images["imageID"]

This property is an array containing references to all the Image objects in the current
document. These references are stored in the array in the order in which they are
defined in the source code. The "imageID" argument is used to access items in the
array and this can either be a string containing the image name as defined within the
<IMG> tag in the HTML source, or an integer (with '0' being the first item in the
array).

lastModified:

Syntax: document.lastModified

This property returns the date that the document was last modified. This property
returns a string relating to the date that the document was last modified, which is
usually, but not always, contained in the HTTP header of a document. When this
data is supplied, the server from which the document originated interrogates the file
for its 'last modified' date and includes this in the header information of the
document. If a particular server doesn't do this, and no 'date last modified' data
exists in the HTTP header, JavaScript will return a value of '0', which it interprets as
'January 1, 1970 GMT'

• linkColor:

Syntax: document.linkColor = "colorinfo"

This property defines the color of any hyperlinks in the document. The "colorinfo"
argument is a string that can contain either the hexadecimal definition of the color or
it's literal description. If you use the hex definition of a color it must be in the format
rrggbb - for example, the hex value for the named color 'forest green' is '228B22'.

• links:

Syntax: document.links["linkID"]

This property is an array containing references to all the Area and Link objects in the
current document. These references are stored in the array in the order in which
they are defined in the source code. The "linkID" argument is an integer relating to a
link defined within a <A HREF = " "> or <AREA HREF = " "> tag in the HTML source.

title:

Syntax: document.title

This property returns the document's name as defined between the
<TITLE></TITLE> tags.
url:

Syntax: document.URL

This property is used to retrieve the document's full URL.

vlinkColor:

Syntax: document.vlinkColor = "colorinfo"

This property defines the color of any visited links in the document. The "colorinfo"
argument is a string that can contain either the hexadecimal definition of the
color or its literal description. If you use the hex definition of a color it must be
in the format rrggbb - for example, the hex value for the named color 'forest
green' is '228B22'.

Methods

close:

Syntax: document.close( )

This method closes an output stream previously opened with the document.open
method and forces data collected from any instances of the document.write or
document.writeln methods to be displayed.

Example:

function newWindowTest()

{
var message1 = "Hello, world!"
var message2 = "This is a test."
newWindow.document.open("text/html", "replace")
newWindow.document.writeln("message1)
newWindow.document.write("message2)
newWindow.document.close()
}

newWindow=window.open('','','toolbar=no,scrollbars=no,width=200,height=150'
)
newWindowTest()

Output:

"Hello, world! This is a test."

This example demonstrates this and displays the output stream in a new window.
getElementById:

Syntax: document.getElementById(id)

This element receives a string containing the id of a specific element and returns a
reference to it. After obtaining a reference to the object, you can use the
getAttribute and setAttribute methods to modify the element's attributes.

Example:

<p id="myID" attr="my attribute value">
...
<script>
var pTag1 = document.getElementById('myID');
document.write(pTag1.getAttribute('attr') + '<br>\n');
pTag1.setAttribute('attr', 'my new attribute value');
document.write(pTag1.getAttribute('attr'));
</script>

Output:

my attribute value
my new attribute value

open:

Syntax: document.open([mimeType[, replace]])

This method is used to open a stream to collect the output from any write or writeln
methods. The first of the optional parameters is mime Type which determines
the type of document you are writing to; if this parameter is not used, the
default value is "text/html". The second parameter is replace, also optional,
which causes the history entry for the new document to inherit the history entry
from the document from which it was opened.

Example:

function newWindowTest()

{
var message1 = "Hello, world!"
var message2 = "This is a test."
newWindow.document.open("text/html", "replace")
newWindow.document.writeln(message1)
newWindow.document.write(message2)
newWindow.document.close()
}
newWindow=window.open('','','toolbar=no,scrollbars=no,width=200,height=150'
)
newWindowTest()

Output:

"Hello, world! This is a test."

The following code demonstrates this method and displays the output stream in a
new window.

write:

Syntax: document.write("expression1", [expression2, [...]])

This method is used to write HTML expressions to the specified document in a
current or new window. Multiple arguments, ("expression1", [expression2,
[...]]), can be listed and they will be appended to the document in order of
occurrence. They can be of any type supported by JavaScript (string, numeric,
logical), but all non-string expressions will be converted to a string before being
appended.

In general, it is not necessary to open the document using the document.open
method; since the document.write method will automatically open the file and
discard (erase) the contents. However, after the write is complete, you need to
close the document by using the document.close method. In some browsers,
the results of the write may not be completely displayed, due to buffering, until
the close occurs.

Example:

newWindow = window.open('', 'newWin')
var tagBoldOpen = "<b>"
var tagBoldClose = "</b>"
newWindow.document.write(tagBoldOpen)
newWindow.document.write("This is some bold text.", tagBoldClose)
newWindow.document.close()

writeln:

Syntax: document.writeln("expression(s)")

This method is identical to the write method detailed above, with the addition of
writing a new line character after any specified expressions.

Form:
Forms allow us to prompt a user for input using elements such as radio buttons,
checkboxes and selection lists. Data gathered in this manner can then be
posted to a server for processing. A form is created by enclosing HTML
controls and other elements within <form></form> tags. A page can contain as
many forms as required, but they cannot be overlapping or nested (the closing
</form> tag of a form must precede the opening tag of any subsequent form).

Example:
<HTML>
<HEAD>
<TITLE>Form Object Example</TITLE>
</HEAD>
<BODY>
<FORM name="form1" action = "PromptBox.html" method =
"POST">
Enter your name: <INPUT name = "FName"><BR>
Favorite Ice Cream Flavor:
<SELECT name = "Flavor">
<OPTION value = "Chocolate">Chocolate
<OPTION value = "Strawberry">Strawberry
<OPTION value = "Vanilla" selected>Vanilla
</SELECT>
<SCRIPT>
alert(form1.length);
</SCRIPT>
<P><INPUT type = "submit">
</FORM>
</BODY>
</HTML>

Properties

action:

Syntax: object.action = URL

This property specifies the URL address to which the data gathered by the form will
be submitted. An email address can also be specified using the
'mailto:anybody@anywhere.com' syntax.

elements:
Syntax: object.elements

This property is an array containing an object for each element on the form. These
objects (checkboxes, radio buttons, etc.) are added to the array in the order
that they appear in the document's source code.

length:

Syntax: object.length

This property returns the number of elements in a form.

method:

Syntax: object.method

This property is a string specifying how information input in a form is submitted to the
server. This should return either 'get', which is the default, or 'post'.

name:

Syntax: object.name

This property sets or returns the name of the form. Initially contains the name
attribute of the <form> tag.

target:

Syntax: object.target

The name of the frame or window the form submission response is sent to by the
server. Possible values are:
name The name of the target window or frame.
_blank Load the linked document into a new blank window. This window is not
named.
_media Load the linked document into the HTML content area of the Media Bar.
Available in Microsoft Internet Explorer 6 or later.
_parent Load the linked document into the immediate parent of the document the
link is in.
_searc Disabled in Windows Internet Explorer 7, see Security and Compatibility in
h Internet Explorer 7 for details. Otherwise, loads the linked document into
the browser search pane in Internet Explorer 5 or later.
_self Default. Load the linked document into the window in which the link was
clicked (the active window).
_top Load the linked document into the topmost window.

Methods
reset:

Syntax: object.reset( )

This method resets the default values of any elements in a form. Emulates the
clicking of a Reset button (although it is not necessary to have a reset button in
a form to use this method).

submit:

Syntax: object.submit( )

This method submits a Form. This is the same as clicking a Submit button.

History:

The History object is a predefined JavaScript object which is accessible through the
history property of a window object.

The window.history property is an array of URL strings which reflect the entries in
the History object. The History object consists of an array of URLs, accessible
through the browser's Go menu, which the client has visited within a window. It
is possible to change a window's current URL without an entry being made in
the History object by using the location.replace method.

Example:
1. <HTML>
<HEAD>
</HEAD>
<BODY>
<SCRIPT type=text/javascript>
function doIt()
{
var _p1 =
'"historyWindow","width=500,height=300,menubar,resiza
ble"';
var w=window.open("",_p1);
var d=w.document;

netscape.security.PrivilegeManager.enablePrivilege("Uni
versalBrowserRead");
for(var i=0;i<history.length;i++)
{
d.write('<A target="new" href="'+history[i]+'">');
d.write(history[i]);
d.writeln('</A>');
}
d.close();
return w;
}
doIt()
</SCRIPT>
<BR>
<CENTER>
<A href="#">JS-Examples.com</A>
</CENTER>
</BODY>
</HTML>

2. <HTML>
<HEAD>
<TITLE>History Object Example</TITLE>
<SCRIPT language="JavaScript">
function historyPropertiesMethods(form)
{
alert(history.current);
alert(history.length);
alert(history.next);
alert(history.previous);

alert(history.back());
alert(history.forward());
alert(history.go(1));
}
</SCRIPT>
</HEAD>
<BODY>
<FORM name="form1">
<INPUT type="submit"
onClick="historyPropertiesMethods(this.form);">
</FORM>
</BODY>
</HTML>

Properties

current:

Syntax: history.current

The current property contains the complete URL of the current History entry.

length:
Syntax: history.length

The length property contains the number of elements in the History list.

next:

Syntax: history.next

The next property contains the complete URL of the next element in the History list,
and is the equivalent of the URL the user would go to if they selected Forward
in the Go menu.

previous:

Syntax: history.previous

The previous property contains the complete URL of the previous element in the
History list, and is the equivalent of the URL the user would go to if they
selected Back in the Go menu.

Methods

back:

Syntax: history.back()

The back method loads the previous URL in the History list, and is equivalent to the
browser's Back button and to history.go(-1).

forward:

Syntax: history.forward()

The forward method loads the next URL in the History list, and is equivalent to the
browser's Forward button and to history.go(1).

go:

Syntax: history.go(delta)

history.go(location)

The go method loads a specified URL from the History list.

Image:
Syntax: new Image([width,] [height])

The Image object is an image on an HTML form, created by using the HTML 'IMG'
tag. Any images created in a document are then stored in an array in the
document.images property, and it is from here that they are accessed. If you
have specified a name for an image created using the HTML 'IMG' tag, you can
use that name when you index the image in the images array. You can also
use the Image constructor and the new operator to create an image object
which can then be displayed within an existing cell. The main use of this is to
load an image from the network so that it is in cache before it needs to be
displayed.

When one Image object replaces another, it cannot change the width and
height properties of it (these are read-only for this object) and the browser
displays the image with the dimensions set in the IMG tag. JavaScript can also
be used to create animation by repeatedly changing the value of the src
property.

This isn't as fast as GIF animation because Javascript has to load each individual
frame as a separate file, whereas with GIF animation all the frames are
contained in one file.

NOTE: The event handlers onClick, onMouseOut and onMouseOver can also
be used with the Internet Explorer browser, but not with Netscape. You can,
however, use these event handlers in conjunction with the Image object with
Netscape, if you define an Area object for the image, or if the IMG tag is placed
within a Link object.

Examples:
<HTML>
<HEAD>
<TITLE>History Object Example</TITLE>
<SCRIPT language="JavaScript">
function imagePropertiesMethods(form)
{

}
</SCRIPT>
</HEAD>
<BODY>
<FORM name="form1">
<INPUT type="submit"
onClick="imagePropertiesMethods(this.form);">
<IMG src = "E:/Neeta/Images/DEPT1.jpg" name = “img1”
border=1 width=150 height=150 hspace=5 vspace=5>
</FORM>
</BODY>
</HTML>

myImage = new Image()
myImage.src = "C:/Personal/Mountain.gif"

The above two lines will create an Image object called MyImage.

Properties

border:

Syntax: Image.border

The border property is read-only, and is a string stating the width of the border of an
image in pixels. For an image created using the Image constructor, this is 0.

complete:

Syntax: Image.complete

The complete property is read-only and returns a Boolean value indicating whether
or not the browser has completed loading the image.

constructor:

Syntax: Object.constructor

This specifies a function to create an object's property and is inherited by all objects
from their prototype.

height:

Syntax: Image.height

The height property is read-only, and is a string stating the HEIGHT attribute of an
IMG tag in pixels. Where an image has been created using the Image
constructor, the height is of the image itself, not the HEIGHT value of the
display.

hspace:

Syntax: Image.hspace

The hspace property is read-only and specifies the HSPACE value of the IMG tag,
which is the number of pixels space between the left and right margins of an
image and surrounding text. For an image created using the Image constructor,
the value of this property is null.
lowsrc:

Syntax: Image.lowsrc

The lowsrc property specifies the URL of a low-resolution version of an image
relating to the LOWSRC attribute of an IMG tag. A browser first loads a low-
resolution version before replacing it with the high-resolution version of the src
property.

name:

Syntax: Image.name

The name property is read-only and reflects the NAME attribute of an IMG tag. If the
Image object has been created by using the Image constructor, the value of
this property is null.

src:

Syntax: Image.src

The src property is a string representing the URL of an image and reflects the SRC
attribute of an IMG tag. The src property can be altered at any time, but when
you do so the new image (if not the same size) is scaled to fit the height and
width attributes of the IMG tag. Also, the loading of any other image into that
cell is aborted, so the Lowsrc property should be altered before setting the src
property.

vspace:

Syntax: Image.vspace

The vspace property is read-only and specifies the VSPACE value of the IMG tag,
which is the number of pixels space between the top and bottom margins of an
image and surrounding text. For an image created using the Image constructor,
the value of this property is null.

width:

Syntax: Image.width

The width property is read-only, and is a string stating the WIDTH attribute of an
IMG tag in pixels. Where an image has been created using the Image
constructor, the width is of the image itself, not the WIDTH value of the display.
Methods:

handleEvent:

Syntax: Image.handleEvent(event)

The handleEvent method is used to evoke the handler for a specified event.

Window:

As the top level object in the JavaScript client hierarchy, every browser window and
frame has a corresponding Window object, created automatically with every
instance of a <BODY> or <FRAMESET> tag.

Example:
<HTML>
<HEAD>
<TITLE>Window Object Example</TITLE>
</HEAD>
<BODY>
<FRAMESET rows = "25%,50%,25%>
<FRAME src = "alert.html">
</FRAMESET>
<SCRIPT>
window.defaultStatus = "Hello World";
alert(window.document.alinkColor);
alert(window.frames.length);
//alert(window.history.go(1));
window.name = "ExampleWindow";
alert(window.name);
alert(window.location);
//alert(window.parent);

if("Hello World")
{
window.status = "Changed";
}
//window.back();
//window.blur();
window.open('http://www.yahoo.com', 'yahoo', 'toolbar =
1, resizable = no, height = 500, width = 500, scrollbars =
yes');
window.alert("Alert Property");
window.confirm("Question");
window.prompt("Enter ur name:");
//window.scrollTo(1000,1000);
window.close();
</SCRIPT>
</BODY>
</HTML>

Properties

closed:

Syntax: window.closed

This property is used to return a Boolean value that determines if a window has
been closed. If it has, the value returned is true.

defaultStatus:

Syntax: window.defaultStatus( = "message")

This property is used to define the default message displayed in a window's status
bar.

document:

Syntax: window.document

This property's value is the document object contained within the window. See
Document object.

frames:

Syntax: window.frames("frameID")

This property is an array containing references to all the named child frames in the
current window.

history:

This property's value is the window's History object, containing details of the URL's
visited from within that window. See History object.

location:

Syntax: window.location

This property contains details of the current URL of the window and its value is
always the Location object for that window.
name:

Syntax: window.name

This property is used to return or set a window's name.

parent:

Syntax: window.parent

This property is a reference to the window or frame that contains the calling child
frame.

status:

Syntax: window.status= ( "message")

This property, which can be set at any time, is used to define the transient message
displayed in a window's status bar such as the text displayed when you
onMouseOver a link or anchor.

Methods

alert:

Syntax: window.alert("message")

This method displays an alert box containing a message and an o.k. button.

back:

Syntax: window.back()

Using this method is the same as clicking the browser's Back button, i.e. it undoes
the last navigation step performed from the current top-level window.

blur:

Syntax: window.blur( )

This method is used to remove focus from the current window.

close:

Syntax: window.close( )
This method is used to close a specified window. If no window reference is supplied,
the close() method will close the current active window. Note that this method
will only close windows created using the open() method; if you attempt to
close a window not created using open(), the user will be prompted to confirm
this action with a dialog box before closing. The single exception to this is if the
current active window has only one document in its session history. In this case
the closing of the window will not require confirmation.

confirm:

Syntax: confirm("message")

This method brings up a dialog box that prompts the user to select either 'o.k.' or
'cancel', the first returning true and the latter, false.

forward:

Syntax: window.forward()

Using this method is the same as clicking the browser's Forward button, i.e. it goes
to the next URL in the history list of the current top-level window.

open:

Syntax: window.open(URL, name [, features])

This method is used to open a new browser window.

prompt:

Syntax: window.prompt(message[, defaultInput])

This method displays a dialog box prompting the user for some input.

scrollTo:

Syntax: window.scrollTo(coordsPixels)

This method is used to scroll the window to the supplied co-ordinates.

Frame:

A Frame object is created by using the HTML <FRAME> tag in a Window that
contains the <FRAMESET> tag. A frame is an independent window within a
parent window (in other words, you can display multiple frames, or windows, on
a single screen). It has its own URL and is treated, with a few exceptions, as a
Window object by JavaScript (this includes having all the same methods and
properties of a Window object). For more information on Frame objects, go to
the Window object page.
Properties

• length:

Syntax: [windowReference.].frames.length

[frameReference.].frames.length

Reflects the number of child frames within a frame.

• parent:

Syntax: parent.propertyName

The parent of the current frame. It’s a string indicating the name of the window
containing the frameset tag.

• self:

Syntax: self.propertyName

A synonym for the current frame.

Methods

• blur:

Removes focus from the frame

• open:

Same as Window object open method.

• close:

Closes the window

• alert:

Contains the string argument to display message.