You are on page 1of 169

JavaScript Tutorial

Developed initially by Netscape in 1995 for use with HTML pages, JavaScript is now a widely used scripting language supported by the majority of Web browsers and diverse Web tools. A registered trademark of Sun Microsystems, Inc., JavaScript works with HTML pages, adding interactive functions that developers can use to create dynamic Web Pages. JavaScript is a less powerful version of Java that is easy to learn and use as it contains simpler syntax and rules . JavaScripts source code is embedded into the header of the HTML page on the client side and compiled into intermediate language (bytecode) on the server side. There are no licensing issues with JavaScript. JavaScript functions as both a procedural language and an object-oriented language. With JavaScript, a developer or programmer can create objects and attach methods and properties. JavaScript reduces the load on the server because most of the data is processed on the client side, resulting in faster processing time for millions of web pages on the Internet. JavaScripts main functionality is in the development of web pages and web sites that are easily interactive and user-friendly. Because of the popularity of JavaScript, career opportunities for JavaScript web developers are available all over the world. Online tutorials on JavaScripts features are available for beginners as well as advanced developers.

Training Index

1.

JavaScript Browser Objects Part 2


JavaScript Browser Objects Part 2 In this JavaScript tutorial you will learn about Browser Objects viz button object properties of button object form name value Methods of button object checkbox object properties of checkbox object - checked defaultChecked form name type value Methods of checkbox object - blur click and focus . button

2.

JavaScript Frame object


JavaScript Frame Object In this JavaScript tutorial you will learn about frame object its properties and methods in detail with example. frame object properties of frame object frames self name length parent methods of frame object blur focus setInterval clearInterval setTimeout expression milliseconds clearTimeout and events

3.

JavaScript Form Object


JavaScript Form Object In this JavaScript Tutorial you will learn about JavaScript form object properties of form object action - elements encoding length method name target button checkbox FileUpload hidden password radio reset select submit text textarea and methods of form object. Form Object form object is a Browser object

4.

JavaScript FileUpload Object

JavaScript FileUpload object In this JavaScript tutorial you will learn about FileUpload object FileUpload properties accessKey disabled form name type value FileUpload methods - blur focus select handleEvent click and event handlers - onblur onchange and onfocus. FileUpload object FileUpload represents an element

5.

JavaScript Event Object Properties and Methods


JavaScript Event Object Properties and Methods In this JavaScript tutorial you will learn about event object properties and methods like keycode layer offset modifiers page reason returnValue screen srcElement target srcFilter and type. keycode The keycode property of event object is used to indicate the keycode associated with the key

6.

JavaScript Event Object


JavaScript Event Object In this JavaScript tutorial you will learn about JavaScript event object properties of event object altKey ctrlKey and shiftKey button integer value action representation cancelBubble clientX and clientY fromElement and toElement height and width. event Object The event object is a browser object used to get information

7.

JavaScript Elements and Embed Objects


JavaScript Elements and Embed Objects In this JavaScript tutorial you will learn about browser objects - elements and embed properties of elements object length type embed object properties of embed object along with syntax and examples. elements object The elements object is used in JavaScript to access all form elements such as fields

8.

JavaScript Applet Objects


JavaScript Applet Objects In this JavaScript tutorial you will learn about applet object properties and methods of applet object Methods of applet object area object Properties of area object viz. hash host hostname href pathname port protocol search and target. applet object The applet object is used in JavaScript to access a Java

9.

JavaScript Browser Objects


JavaScript Browser Objects In this JavaScript tutorial you will learn about browser objects in JavaScript categories of browser-based objects additional browser objects anchor object link object properties of link object and methods of link object. JavaScript supports a number of browser-based objects. When a webpage loads by a browser that

10.

JavaScript Object Oriented Features

JavaScript Object Oriented Features In this JavaScript tutorial you will learn about JavaScript Object Oriented Features object type object instantiation using object properties using object methods and achieving object instantiation. Object-oriented capabilities make any language or application powerful. This section outlines the object oriented

11. JavaScript

Window Object Open Method Part 2

JavaScript Window Object Open Method Part 2 In this JavaScript tutorial you will learn about JavaScript Window Object Open Method features of window object open method - scrollbars status titlebar toolbar top width innerHeight innerWidth outerHeight outerWidth and hotkeys scrollbars Syntax scrollbars yes no 1 0 The scrollbar feature

12. JavaScript

Window Object Open Method

JavaScript Window Object Open Method In this JavaScript tutorial you will learn about JavaScript Window Object Open Method features of window object open method - channelmode directories dependent fullscreen screenX screenY height left location menubar resizable alwaysLowered alwaysRaised channelmode Syntax channelmode yes no 1 0

13. JavaScript

Window Object Timeout Methods

JavaScript Window Object Timeout Methods In this JavaScript tutorial you will learn about setTimeout clearTimeout and open methods of window object along with syntax usage and examples for each method. setTimeout The setInterval method of Window object is used to call a function or evaluate an expression at specified intervals. The

14. JavaScript

Location Object

JavaScript Location Object In this JavaScript tutorial you will learn about JavaScript Location Object assign reload replace JavaScript Window Object Methods viz alert blur setInterval and clearInterval .Methods of Location Object assign The assign method of location object is used for loading a new document. General

15. JavaScript

Location Object Properties

JavaScript Location Object Properties In this JavaScript Tutorial you will learn about Properties of Location Object - hash host hostname href pathname port protocol and search property The Location object contains information about the current URL. This representation is a string that denotes the different portions of the URL as below

16. JavaScript

History Object Properties and Methods

JavaScript History Object Properties and Methods In this JavaScript tutorial you will learn about history object properties and methods length current next previous properties back forward and go methods along with syntax and examples. The history property has the return value as history object which is an array of history

17. JavaScript

Document Object Methods Part II

JavaScript Document Object Methods Part II In this JavaScript tutorial you will learn about document object methods - getElementsByTagName getSelection handleEvent releaseEvents routeEvent write writeln along with syntax examples and brief explanation. getElementsByTagName The the getElementsTagName method returns a collection of objects

18.JavaScript

Document Object Methods Part I

JavaScript Document Object Methods - Part I In this JavaScript tutorial you will learn about methods of document object along with syntax and examples. This section covers captureEvents open close getElementById getElementsByName methods with explanations for each method. Methods of document Object captureEvents The captureEvents

19. JavaScript

Document Object Properties

JavaScript Document Object Properties In this JavaScript tutorial you will learn about Document Object Properties viz. formName forms images lastModified layers linkColor links plugins referrer title URL and vlinkColor. formName Using the formName property any form in the document can be referred and the formName is assigned as FORM

20.

JavaScript Document Object

JavaScript Document Object In this JavaScript tutorial you will learn about document object - part of JavaScript window object properties and windows of document object alinkColor anchors applets bgColor cookie domain embeds and fgColor. The Document object is part of the Window object. The document object is used to access all

21. JavaScript

Windows Object Properties Part II

JavaScript Windows Object Properties Part II In this JavaScript tutorial you will learn about screenX screenY screenLeft and screenTop top length frames opener parent and window property of Window

object along with syntax and examples. screenX This property screenX returns the x coordinate of the window relative to the user s monitor screen.

22.

JavaScript Windows Object Properties Part I

JavaScript Windows Object Properties Part I In this JavaScript tutorial you will learn about Windows Object properties namely personalbar statusbar scrollbar toolbar property of Window object pageXOffset pageYOffset innerwidth innerheight outerwidth and outerheight. personalbar Property of Window Object The personalbar property of a Window

23.

JavaScript DOM Window Object

JavaScript DOM Window Object In this JavaScript tutorial you will learn about closed property and name property defaultStatus status self property of JavaScript Window object closed Property of Window Object The closed property of a Window object returns a Boolean variable denoting whether window has been closed or not. The closed property

24.

Working with JavaScript DOM Objects

Working with JavaScript DOM Objects In this JavaScript tutorial you will learn about DOM object window properties of window object methods of window object screen properties of screen object navigator properties of navigator object methods of navigator object history property of history object methods of history object location properties

25.

JavaScript Array Object Methods Part II

JavaScript Array Object Methods Part II In this JavaScript tutorial you will learn about on array object methods - slice splice toString shift and unshift methods along with general syntax and examples. slice By using the methods of the array object the programmer is able to retrieve the first and the last elements in an

26.

JavaScript Array Object

JavaScript Array Object In this JavaScript tutorial you will learn about JavaScript Array Object its properties and methods. Usage of the Array Object The Array object is used to store a set of values in a single variable name. There are many operations involved with Array object Defining Array object Adding Values to Array

27.

JavaScript Array Object Methods Part I

JavaScript Array Object Methods Part I In this JavaScript tutorial you will learn about Array Object Methods - concat join pop push and reverse methods along with general syntax and examples. concat The concat method is used to join two or more Array objects together to produce a new one. In the concat method the

28.

JavaScript Boolean Object

JavaScript Boolean Object In this JavaScript tutorial you will learn about JavaScript boolean object how to pass value to the boolean object properties and methods used with boolean object. Usage of the Boolean Object The Boolean object is a wrapper for the Boolean data type. The Boolean object is used to convert a non-Boolean value to a Boolean

29.

JavaScript OnError Event

JavaScript OnError Event In this JavaScript tutorial you will learn about onerror event how to use onerror event along with syntax and example. Using onerror event The onerror event fires when a page has a script error. This onerror event occurs in JavaScript when an image or document causes an error during loading. This does not mean that it

30.

JavaScript Exception Handling Part II

JavaScript Exception Handling Part II In this JavaScript tutorial you will learn about exception handling viz. try catch..finally statement and nested try catch statements along with syntax and examples. try catch..finally Statement JavaScript has a finally statement that can be used as an optional construct along

31. JavaScript

Exception Handling Part I

JavaScript Exception Handling Part I In this JavaScript tutorial you will learn about Exception Handling Catching errors in JavaScript Using try..catch statement and throw in JavaScript along with syntax and examples. It is impossible for a programmer to write a program without errors. Programming languages include exceptions or errors

32.

JavaScript Event Handler

JavaScript Event Handler In this JavaScript tutorial you will learn about using event handlers along with events for each HTML tag. Using Event Handler in JavaScript Event Handlers are used in JavaScript by placing the name of the event handler inside the HTML tag associated with object. This is followed by JavaScript code the

33.

JavaScript Events Handling

JavaScript Events Handling In this JavaScript tutorial you will learn about handling events in JavaScript what is event handling in JavaScript events in JavaScript events associated with mouse onmousemove onclick ondblclick onmouseout onmouseover events associated with keyboard onkeydown onkeyup onkeypress. onerror onfocus onblur

34.

JavaScript Array Operations

JavaScript Array Operations In this JavaScript tutorial you will learn about different operations with array in JavaScript how to use the for...in statement Combining Operations between arrays and within elements of an array joining two or more arrays and joining elements of an arrays along with syntax and example scripts.for in statement

35.

JavaScript Two Dimensional Arrays

JavaScript Two Dimensional Arrays In this JavaScript tutorial you will learn about two dimensional arrays - how to define and access two dimensional array in JavaScript. Two Dimensional Arrays in JavaScript Two Dimensional Arrays are storing elements in a structure similar to that of a table. Defining Two Dimensional Arrays in JavaScript One

36.

Passing values to JavaScript Function

Passing values to JavaScript Function In this JavaScript Tutorial you will learn about how to pass values to and also how to return values from a JavaScript function. Passing Values to function Values can be passed to a function as parameters. The general syntax for passing values to a function in JavaScript is

37.

JavaScript Functions
JavaScript Functions In this JavaScript tutorial you will learn about JavaScript functions and how to create them. What is a function Function is a block of code that can be reused as and when needed at various places. The function executes whenever it is called. JavaScript Functions How does a programmer define create and handle functions

38.

JavaScript Arrays

JavaScript Arrays In this JavaScript tutorial you will learn about JavaScript Array different ways of defining an array in JavaScript viz. traditional way shorter form literal array accessing the elements in an array and editing the values or elements in an array. The array concept is used to store a set of values in a single variable name. This

39.

JavaScript Iterative Structures - Part II

JavaScript Iterative Structures - Part II In this JavaScript tutorial you will learn about JavaScript Iterative Structures while loop and do..while loop explained along with syntax and examples. while loop This looping structure is used when a programmer wants the block of code to execute until the condition specified remains true. The

40.

JavaScript Iterative Structures - Part I

JavaScript Iterative Structures - Part I In this JavaScript tutorial you will learn about JavaScript Iterative Structures for loop for..in statement break and continue explained along with syntax and examples. Iterative Structures are used to execute a certain piece of code a specified number of times or until the condition mentioned remains

41. JavaScript

Math Object

JavaScript Math Object In this JavaScript tutorial you will learn about Math Object usage properties and methods of math object along with syntax and examples. Usage of Math Object JavaScript Math object is used to perform mathematical tasks. But unlike the String and the Date object which requires defining the object Math object need not be

42.

JavaScript Date Object

JavaScript Date Object In this JavaScript tutorial you will learn about date object and methods of date object explained along with syntax and example. JavaScript Date Object Usage of Date Object Date object of Java Script is used to work with date and times. General syntax for defining Date object in Java Script is as follows var variablename new

43.

JavaScript String Object

JavaScript String Object In this JavaScript tutorial you will learn about String Object purpose of string object in JavaScript purpose of string object indexof method lastIndexOf method and substring method along with syntax and example. Purpose of String Object in JavaScript The main purpose of String Object in JavaScript is for storing text.

44.

JavaScript Objects

JavaScript Objects Object oriented Programming in an important aspect of JavaScript. It is possible to use built-in objects available in JavaScript. It is also possible for a JavaScript programmer to define his own objects and variable types. In this JavaScript tutorial you will learn how to make use of built-in objects available in JavaScript. Built-in

45.

JavaScript Confirm Box

JavaScript Confirm Box In the previous section of this tutorial JavaScript Alert Box we discussed about alert boxes. In this section you will learn about JavaScript confirm box and prompt box. Confirm Box The confirm box is a box that pops up with both an OK and a Cancel button. The confirm box is used to verify acceptance from the user. If the

46.

JavaScript Alert Box

JavaScript Alert Box In this JavaScript tutorial you will learn about JavaScript alert box along with code for placing the alert box when page is loaded. There are three types of popup boxes that can be created using JavaScript. Depending on the needs of user the programmer can create any of these types of popup boxes using JavaScript. Three

47.

JavaScript Conditional Statements Part 2

JavaScript Conditional Statements Part 2 In continuation of JavaScript Conditional Statements Part 1 this tutorial will help you learn about remaining conditional statements in JavaScript if...else if...else statement and switch statement. if...else if....else statement If there are many branching or conditions to be decided based on which actions

48.

JavaScript Conditional Statements Part 1

JavaScript Conditional Statements Part 1 In this JavaScript tutorial you will learn about the conditional statements available in JavaScript for decision making if statement and if...else statement. Just like any other programming language conditional statements in JavaScript are used for decision making purpose. The conditional statements

49.

How to use JavaScript in HTML page

How to use JavaScript in HTML page In this JavaScript tutorial you will learn how to use JavaScript in HTML page how to write output to a page different places where JavaScript can be paced in HTML JavaScript in external file and how to place and execute JavaScript in external file. How to Insert JavaScript into a HTML page You can insert JavaScript

50.

JavaScript Variables

JavaScript Variables In this JavaScript tutorial you will learn about JavaScript variables rules for variable names in JavaScript declaration of variable in JavaScript variables usage JavaScript in external file how to place the JavaScript in external file and how to execute this JavaScript placed in external file. Just like any programming

51. JavaScript

Features

JavaScript Features In this JavaScript tutorial you will learn about features of JavaScript JavaScript as a programming tool dynamic effects browser detection DOM control and other popular JavaScript features. A Great Programming Tool for HTML Professional Web designers are undoubtedly adept in using HTML and proficient in website design but

52.

JavaScript Introduction

JavaScript Introduction In this JavaScript tutorial you will learn about introduction to JavaScript why JavaScript differences between Java and JavaScript and advantages of JavaScript. What is JavaScript JavaScript was first developed by Netscape as an open scripting language to create interactive web pages. Script is nothing but a small program

JavaScript Introduction
Author : Exforsys Inc. Published on: 5th Apr 2007 | Last Updated on: 15th Jan 2009

JavaScript Introduction
In this JavaScript tutorial, you will learn about introduction to JavaScript, why JavaScript, differences between Java and JavaScript and advantages of JavaScript.
What is JavaScript?

JavaScript was first developed by Netscape as an open scripting language to create interactive web pages. Script is nothing but a small program which is generally very easy to learn and use. JavaScript as an open language implies that it can be used by anyone; no license is required to use JavaScript. Microsoft created Jscript for its Internet Explorer similar to Netscape JavaScript. JavaScript has the ability to function both as an object

oriented language as well as procedural language. Using JavaScript you can create objects, attach methods and properties. Though JavaScript can run on both client-side and serverside, it is very popular among client-side scripting languages. Client side means the script runs on client browser. JavaScript are generally embedded in the header of web pages.
Why JavaScript?

JavaScript plays a vital role for adding interactive feature to HTML web pages. JavaScript can respond to several events that occur on web-pages and thereby help in designing dynamic and interactive web-sites. Moreover JavaScript makes it very easier to validate a form, check if any fields are empty and verify correctness of data. JavaScript does all these at client side even before actually sending the data to server, thereby reducing considerable load on server and thus makes form processing easier and quicker. Millions of web-pages and server applications make use of JavaScript all over the world, there is no doubt that almost all major web-browsers support JavaScript.
My First JavaScript

JavaScript Example <HTML> <HEAD> <TITLE>My First </HEAD> <BODY> <H1 <BR /><BR <SCRIPT document.write("My </SCRIPT> </H1> </BODY> </HTML> Output

JavaScript</TITLE>

First

ALIGN=CENTER> /><BR /> LANGUAGE="JavaScript"> JavaScript")

JavaScript can be used in different ways within an HTML file. 1. header scripts In this type, JavaScript is embedded between <SCRIPT> tags within the <HEAD> tag and is used for initializing variables and or create functions that can be called from anywhere of the entire script. JavaScript in header is executed once when the page is loaded. 2. body scripts In this type, JavaScript is embedded between <SCRIPT> tags within the <BODY> tag. JavaScript within Body Tags are used for handling various events. 3. called directly when certain events occur In this type, JavaScript are called when certain events occur. Example of events include onLoad, onClick, onError, onSelect, onSubmit, onChange etc.,
Differences between Java and JavaScript:

JavaScript is different from Java programming language, Unlike Java, which needs compilation; JavaScript is dynamic and is interpreted in run-time. Though there are some similarities like both Java and JavaScript are client-side programming language, both descend from C++ yet both Java and JavaScript differ in many ways.
Java was developed by Sun Microsystems while JavaScript was developed by Netscape. . JavaScript is a high-level scripting language whereas Java is an Object Oriented Programming language. . JavaScript is easy to learn and use whereas Java is comparatively difficult. .

In case of Java programming language the code is first written and then compiled. In JavaScript the script can be executed without any compilation. . JavaScript as conveyed can be directly embedded or placed in HTML but it is not possible in case of Java. One cannot write Java code directly into HTML. .

JavaScript was mainly developed for web pages or web sites to add interactive facility or feature and there by making programming effort easier, enable users to interact with web sites and there by making it user-friendly. In addition to interactive facility JavaScript also helps in giving a dynamic functionality for a webpage which helps JavaScript to handle large volume of data during online processing.
Advantages of JavaScript:

JavaScript offers numerous features which makes it popular. Few among them are listed below:
JavaScript is a dynamic open scripting language with simple syntax and rules which makes it easier to use and learn for programmers. This has made JavaScript a popular Client-side scripting language. . It is an interpreted language meaning that it could be used or executed with ease without precompilation. . JavaScript is very useful for creating interactive web pages or web sites. . JavaScript helps in adding dynamic functionality to websites . JavaScript makes it very easier to validate a form at the client side without connecting to server. JavaScript has the ability to instantly notify users in case there is any mistake in input data.

JavaScript Features
Author : Exforsys Inc. Published on: 24th Apr 2007

JavaScript Features
In this JavaScript tutorial, you will learn about features of JavaScript, JavaScript as a programming tool, dynamic effects, browser detection, DOM control and other popular JavaScript features.
A Great Programming Tool for HTML:

Professional Web designers are undoubtedly adept in using HTML and proficient in website design but not necessarily skillful in computer programming. JavaScript is a programming tool for such a situation. JavaScript is a powerful scripting language that helps HTML

designers to effectively and interactively design websites and web pages in a very simple and efficient way.
Handles Dynamic Effects:

JavaScript is such a powerful scripting language which has features to achieve dynamic effects in web pages. Using the features available in JavaScript, the designer can decide to have dynamically placed text at run time.
Browser Detection:

One of the powerful feature of JavaScript is its ability to detect client browser. Browser detection feature of JavaScript helps to achieve independent platforms. JavaScript can detect the type of browser the visitor is using and programatically switch the page to show customised pages designed for different browsers. Thus by making use of browser detection feature of JavaScript, the designer gets better control over the browser.
Saves Time:

JavaScript also has the feature of validating data submitted at the client level. This helps in saving the processing time of the server because JavaScript initially creates the validation on the client side.
DOM:

Client side JavaScript is embedded inside HTML This embedded JavaScript is used along with DOM (Document Object Model) for control over the browser by means of objects.
Popular Scripting language:

JavaScript has simple rules and procedures that make it easier to use and learn for programmers. This has made JavaScript a popular client-side scripting language.
Interpreted Language:

It is an interpreted language, meaning that it can be used or executed with ease without precompilation.
Visual JavaScript:

Visual JavaScript is a component-based visual development tool for the Netscape Open Network Environment used by programmers who want to build cross-platform web-based applications.
Generators and Iterators:

The

newer

version

of

JavaScript

features

built-in

Generators

and

Iterators.

There are other important features in JavaScript such as variables, arrays, objects, methods, event handlers, etc. which will be explained in detail in the following sections of this tutorial.

JavaScript Variables
Author : Exforsys Inc. Published on: 15th Apr 2007

JavaScript Variables
In this JavaScript tutorial, you will learn about JavaScript variables, rules for variable names in JavaScript, declaration of variable in JavaScript, variables usage, JavaScript in external file, how to place the JavaScript in external file and how to execute this JavaScript placed in external file. Just like any programming language, variables in JavaScript are also used to store values. The value of the variable can be edited as required by the programmer.
Rules for Variable Names in JavaScript:

Some of the rules for forming variable names are as follows:


Variable names are case sensitive. They must begin with a letter or the underscore character

Now let us see how to declare a variable name.


Declaration of Variable in JavaScript:

This is done by using the var statement. The syntax of var statement is var variable name = value In any programming language, a variable must first be declared. Storage location must be allocated for the variable before using the variable. In JavaScript, it is possible to skip the command var and directly assign value to variable names. For Example: variable name = value Using the variable name Exforsys and the notion that a programmer wants to assign the value Training to this variable it can be written two ways: var Exforsys = Training or It can also be done as follows: Exforsys = Training

Variables Usage:

The variables can be declared and used in two ways namely:


Locally Globally

When a programmer declares a JavaScript variable within a function, the variable can only be accessed within that function. When the control moves out of the function, the variable is destroyed. These variables are called local variables. Each of the local variables placed with the same name in different functions are different because they are recognized only within the function in which they are declared. If a programmer declares a JavaScript variable outside a function, all the functions on the page can access the variable. The lifetime of these variables starts when they are declared, and ends when the page is closed.
JavaScript in External File:

There may be scenarios in which the same functionality of script needs to be executed in several places in the program. Instead of writing the same JavaScript in several places (which would cause poor optimization of code) the programmer can place the JavaScript in an external file thereby allowing programmers to make use of single external file at more the one place.
How to place the JavaScript in External file:

This process is very simple. The code or the JavaScript that needs to be executed in several places in the program is written separately in a file and then saved with extension as .js for that file.
How to execute this JavaScript placed in External File:

This is performed using the attribute src for the <script> tag. The script tag is placed as needed in either the HEAD section or the BODY section using the src attribute as follows: <html> <head> <script </head> <body> </body> </html>

src="filename.js"></script>

Suppose the JavaScript is placed in an external file named Exforsys.js then it is executed by placing it as: <html> <head> <script </head> <body> </body> </html>

src="Exforsys.js"></script>

How to use JavaScript in HTML page


Author : Exforsys Inc. Published on: 20th Apr 2007 | Last Updated on: 24th Dec 2010

How to use JavaScript in HTML page


In this JavaScript tutorial you will learn how to use JavaScript in HTML page, how to write output to a page, different places where JavaScript can be paced in HTML, JavaScript in external file and how to place and execute JavaScript in external file.
How to Insert JavaScript into a HTML page:

You can insert JavaScript into an HTML page by using <script> tag. JavaScript is placed between tags starting with <script type = text/javascript> and ending with </script>. General syntax of JavaScript is as follows:

<html> <body> <script type="text/javascript"> ... //JavaScript </script> </body> </html>

How to write output to a page:

The JavaScript command used for writing output to a page is document.write. Thedocument.write command takes the argument as the text required for producing output. The example below shows how to place JavaScript command inside an HTML page : Example:

<html> <body> <script type="text/javascript"> document.write("EXFORSYS </html> Training") </script> </body>

Output of the above script as produced in a HTML page is shown below:

Observe that semicolons have not been placed to mark the end of statement, which differs from code writing style in programming languages C and C++. In JavaScript, the placement of a semicolon is optional. If a programmer wants to place more than one statement on a single line then the programmer can make use of the semicolon.
Different places where JavaScript can be paced in HTML:

JavaScript can be placed in various locations in HTML such as

JavaScript in HEAD section JavaScript in BODY section JavaScript in both HEAD and BODY section JavaScript in External File

The placing of JavaScript in the above location differs in the timing of their execution. JavaScript placed in the HEAD section of HTML will be executed when called whereas, JavaScript placed in the BODY section of HTML will be executed only when the page is loaded. The general structure for placing a JavaScript in the HEAD section is:

<html> <head> <script type="text/javascript"> ..... //JavaScript </head> <body> </body> </html> written in HEAD ..... Section </script>

The general structure for placing a JavaScript in the BODY section is

<html> <head> </head> <body> <script type="text/javascript"> ..... //JavaScript </html> written in BODY ..... Section </script> </body>

If a programmer wants to execute JavaScript when called, or when an event is triggered, then JavaScript is placed in the HEAD section. JavaScript is placed in the HEAD Section because scripts gets loaded first. When a programmer wants to execute JavaScript when the page loads then JavaScript should be placed in the BODY section. In addition to these, you can also place JavaScripts in both HEAD and BODY sections of an HTML page. Moreover, you can place any number of scripts in an HTML page. The general structure of JavaScript for placement in both head and body sections is as follows:

<html> <head> <script type="text/javascript"> //JavaScript written in document.write("JavaScript placed </script> </head> <body> <script type="text/javascript"> //JavaScript written in document.write("JavaScript placed </html> HEAD in HEAD Section Section")

in

BODY BODY

Section Section") </script> </body>

Output of the above script as produced in a HTML page is shown below:

JavaScript in External File: There may be scenarios in which the same functionality of script needs to be executed in several places in program. For handling this scenario instead of writing the same JavaScript in several places which would cause poor optimization of code one can place the JavaScript in external file. How to place the JavaScript in External file: This process is very simple. The code or the JavaScript which needs to be executed in several places in the program is written separately in a file and is saved with extension as .js for the file. How to execute this JavaScript placed in External File: This is done by using the attribute named as src for the <script> tag.

Te general syntax of this is as follows:

<html> <head> <script src="filename"> </script> </head> <body> </body> </html>

The script tag is placed as needed in either HEAD section or BODY section as seen in earlier chapter but with the src attribute as follows: It is important to note that external JavaScript file cannot contain HTML tags. Suppose if the JavaScript placed in external file is named as exforsys.js then it is executed by placing it as

<html> <head> <script src="exforsys.js"> </script> </head> <body> </body> </html>

JavaScript Conditional Statements Part 1


Author : Exforsys Inc. Published on: 24th Apr 2007 | Last Updated on: 25th Apr 2007

JavaScript Conditional Statements Part 1


In this JavaScript tutorial, you will learn about the conditional statements available in JavaScript for decision making, if statement and if...else statement. Just like any other programming language, conditional statements in JavaScript are used for decision making purpose. The conditional statements available in JavaScript for decision making are:
if statement if...else statement if...else if....else statement switch statement

NOTE: All syntax specified above must be written exactly as above since JavaScript is a case-sensitive language.
if statement:

If a programmer wants to execute certain statements only when a desired condition is satisfied or has true value then conditional if statement is used. General syntax of if statement in JavaScript is as follows:

if (condition) { //Statements }

executed

if

condition

is true

Let us see an example to understand this concept:

<html> <body> <script type="text/javascript"> var exforsys = if (exforsys < { document.write("<b>Welcome</b>") } </html> 20 30)

</script> </body>

Output of the above script as produced in a HTML page is shown below:

In the above example, if block will be executed only when value of the variable is less than 30. In our example, the value of variable exforsys is 20 (which is less than 30) hence if block is executed and the output Welcome is printed.
if...else statement:

This conditional structure is used in JavaScript if a programmer wants to execute a certain block of statements if a condition is true and execute another block of statements if the condition returns false value. General syntax of this if...else structure in a JavaScript is as follows:

if (condition) { //Statements } else { //Statements } executed if condition is false executed if condition is true

For example

<html>

<body> <script type="text/javascript"> var exforsys = if (exforsys < { document.write("<b>Welcome</b>") } else { document.write("<b>Thank You!</b>") } </html> 40 30)

</script> </body>

Output of the above script as produced in a HTML page is shown below:

In this example, if block is executed only when the value of variable exforsys is less than 30, otherwise else block will get executed, since the value of variable exforsys in our example is 40, else block is executed and the output Thank You! is printed.

JavaScript Conditional Statements Part 2


Author : Exforsys Inc. Published on: 24th Apr 2007

JavaScript Conditional Statements Part 2


In continuation of JavaScript Conditional Statements Part 1, this tutorial will help you learn about remaining conditional statements in JavaScript, if...else if...else statement and switch statement.

if...else if....else statement

If there are many branching or conditions to be decided (based on which actions must be executed) then the programmer can use the if...else if....else statement. General structure of if...else if....else statement in JavaScript is:

<html> <body> <script type="text/javascript"> if (condition1) { ......... ......... //executed if condition1 is true } else if (condition2) { ......... ......... //executed if condition2 is true } else { ....... ....... //executed if condition1 & condition2 are false } </script> </body> </html>

An example for if...else if....else statement in JavaScript is shown below

<html> <body> <script type="text/javascript"> var exforsys = if (exforsys < { document.write("<b>Welcome</b>") } else if (exforsys > 5 && exforsys < 10) { document.write("<b>Have a nice day!</b>") } 20 5)

else { document.write("<b>Thank You!</b>") } </script> </body> </html>

Output of the above script as produced in a HTML page is shown below:

In the above example variable exforsys takes the value 20 (which is not less than 5) then statements in condition1 are not executed. The value (if greater than 5 but not less than 10) of statements in condition2 are not executed, therefore the else structure is executed and the output is Thank You.
switch statement:

A programmer makes use of switch statement whenever one out of the many blocks of code needs to be executed. General structure for switch statement in Java Script is as follows:

switch (variable) { case value1: statements in block break case value2: statements in block break ........

1 2

........ default: statements to be executed if variable is different from case value1 or value2, and so on }

For Example

<html> <body> <script type="text/javascript"> var exforsys = switch (exforsys) case 2: document.write("<b>Hi!</b>") break case 3: document.write("<b>Welcome</b>") break case 4: document.write("<b>Thank break default: document.write("<b>Have a } </script> </body> </html> 5 {

You!</b>") Great Day!</b>")

Output of the above script as produced in a HTML page is shown below:

This is because the value of the variable exforsys is assigned as 5 which does not satisfy the value of any of the case values and hence default block is execute which gives the output as above.

JavaScript Alert Box


Author : Exforsys Inc. Published on: 25th Apr 2007

JavaScript Alert Box


In this JavaScript tutorial, you will learn about JavaScript alert box along with code for placing the alert box when page is loaded. There are three types of popup boxes that can be created using JavaScript. Depending on the needs of user, the programmer can create any of these types of popup boxes using JavaScript. Three kinds of popup boxes created using JavaScript are:
Alert Box Confirm Box Prompt Box

Let us now learn how to create each of these popup boxes using JavaScript.
Alert Box:

This type of popup box is a dialog box used when a programmer wants to make sure that the information is passed to the user. The alert box pops up with an OK button which the user has to press to continue further. General syntax of alert box is alert(textmessage) For example: alert(Exforsys) The above statement will display a dialog box with message Exforsys and a OK button. The dialog box remains in view until the user presses the OK button. When no text message is placed alert() This would display an empty dialog box with an OK button that the user must press to proceed. It is also possible to display messages with values of variables in an alert box. For example:

<html> <body> <script type="text/javascript"> var exam_score = alert ("Exam Score is:" + exam_score) </html> 56 </script> </body>

In the above script alert box displays the value of variable exam_score concatenated with a string. The plus sign acts as a concatenation symbol. Output of the above script as produced in a HTML page is shown below:

It is vital to understand that the alert box can be placed in different locations or events. Depending on the placing of the alert box and based on the place of usage, the alert box will be activated. For example,
it is possible to place the alert box so that it pops up when a page is loaded. it is possible to place the alert box to be activated when a button is clicked.

Here is an example of JavaScript code for placing the alert box to be executed when a page is loaded.

<html> <body> <script type="text/javascript"> alert ("Exforsys") </script> </body> </html>

Output of the above script as produced in a HTML page is shown below:

In the above example, message Exforsys pops up in the alert box when the page is loaded.

JavaScript Confirm Box


Author : Exforsys Inc. Published on: 25th Apr 2007 | Last Updated on: 7th Dec 2010

JavaScript Confirm Box


In the previous section of this tutorial JavaScript Alert Box, we discussed about alert boxes. In this section, you will learn about JavaScript confirm box and prompt box. Confirm Box:

The confirm box is a box that pops up with both an OK and a Cancel button. The confirm box is used to verify acceptance from the user. If the user accepts, then the user presses theOK button and the confirm box returns with a true value. If the user rejects with the Cancel button, then the confirm box returns false value. General syntax for a confirm box is confirm (textmessage) A simple confirm box example:

<html> <body> <script type="text/javascript"> if (confirm("Wish to accept or Cancel")) { alert ("Agreed and hence True value returned") } else { alert ("Not Agree and hence False value returned") } </script> </body> </html>

In the above example, the conditional statement ifelse is used and the alert box and the confirm box are written together. Output of the above script as produced in a HTML page is shown below:

The confirm box pops up with the message: Wish to accept or Cancel

Showing two buttons (OK and Cancel) that the user can choose from. If the user presses OKin the confirm box then the value returned would be true, executing the if block of statements. This results in the alert box popping up with the message. Agreed and hence true value returned. If the user presses the Cancel button in the confirm box then the value returned would be false, executing the else block of statements. This results in the alert box popping up with the message Not Agreed and hence false value returned
Prompt Box:

The prompt box is used when a users input value is desired before entering a page. The prompt box pops up with two buttons (OK and Cancel). If the user presses OK then the prompt box returns with the value entered by user but if the user presses the Cancel button then the prompt box returns with a null value. General syntax of prompt box is as follows: prompt(textmessage,value_default) A simple prompt box example:

<html> <body> <script type="text/javascript"> name = prompt ("Input Name","Exforsys") </html> the Training Company </script> </body>

Output of the above script as produced in a HTML page is shown below:

In the above example, the default value is stored with value Exforsys and the prompt box pops up with the message Input the Training Company Name with a default value asExforsys and two buttons (OK and Cancel). When the user presses the OK button, the value Exforsys is returned by prompt box, which is stored in the variable name. If the user presses Cancel, then null value is retuned by the prompt box.

JavaScript Objects
Object oriented Programming in an important aspect of JavaScript. It is possible to use built-in objects available in JavaScript. It is also possible for a JavaScript programmer to define his own objects and variable types. In this JavaScript tutorial, you will learn how to make use of built-in objects available in JavaScript.
Built-in objects in JavaScript:

Some of the built-in objects available in JavaScript are:


Date Math String

Array Object

Of

the

above

objects,

the

most

widely

used kind

one of

is

the

String Each

object. object

Objects are nothing but special has Properties and Methodsassociated with it.
Properties of an Object:

data.

Property is the value that is tagged to the object. For example let us consider one of the properties associated with the most popularly used String object the length property. Length property of the string object returns the length of the string, that is in other words the number of characters present in the string. General syntax of using the length property of the string object is as below:
variablename.length

Here variablename is the name of the variable to which the string is assigned and length is the keyword. For example consider the JavaScript below:

<html> <body> <script type="text/javascript"> exf="Welcome" </script> </body> </html>

var document.write(exf.length)

The output of the above is


7

We see that the property of an object is the value associated with the object.
Method of an Object:

Method of an object refers to the actions than can be performed on the object. For example in String Object there are several methods available in JavaScript. Some of the Methods associated with String Object are:

toUpperCase() toLowerCase() substring() indexOf lastIndexOf

All these methods are used to perform actions on the String object. For example the substring method of the String Object in JavaScript is used for extracting a specific portion of the string. If a programmer wants the value of String methodtoLowerCase() is used on String Object object in lowercase then the

To convert a string to upper case, the method toUpperCase() is used. If a programmer wants to know the position of a characters or group of characters in a String Object it can be determined by applying indexof method to the String. Example to understand how method can be used in an Object. In the example below, we have used toUpperCase method of String object.

<html> <body> <script type="text/javascript"> var exf="Welcome" document.write(exf.toUpperCase()) </script> </body> </html>

The output of the above script is


WELCOME

In the above script since the method toUpperCase is applied to the string object exf which has value initialized as Welcome all letters get converted as upper case and hence the output is as above.

JavaScript String Object

In this JavaScript tutorial, you will learn about String Object, purpose of string object in JavaScript, purpose of string object, indexof method, lastIndexOf method and substring method along with syntax and example.
Purpose of String Object in JavaScript:

The main purpose of String Object in JavaScript is for storing text. General method of using String Object is to declare a variable and assign a string, in other words a text to the variable.
var exf="Welcome"

assigns the text Welcome to the variable exf defined. We have seen in earlier section that some of the methods used in String Objects are:
indexOf lastIndexOf substring() toUpperCase() toLowerCase()

indexOf method of String Object:

If a programmer wants to know the position of a characters or group of characters in a String Object it can be obtained by applying the indexOf method to the String. In other words indexOf method of the String Object returns the position of the first occurrence of a specified string value in a string. General syntax of the indexOf method of String Object in JavaScript is as follows:
indexOf(substr, [start])

Here the substr given in argument is searched in the string and if it found the index number of the searched character is or substring within the string is returned. If it is not found then -1 is returned. The default returned value is 0. The start is an optional argument specifying the position within string to begin the search. For example:

<html> <body> <script type="text/javascript"> var exf="Welcome members" document.write(exf.indexOf("Welcome") + "<br />")

document.write(exf.indexOf("Members") + "<br />") </script> </body> </html>

Output of the above program is:


0 -1

This is because the first write statement has Welcome given as substring in the indexOfmethod and since it occurs in the starting of the String Object the value 0 is printed. The second write statement has Members given as substring in the indexOf method and since it does not occur in the string the value -1 is printed. Only members is present in the String Object and not Members so -1 is printed.
lastIndexOf method of String Object:

General syntax of lastIndexOf method of String Object is as follows:


lastIndexOf(substr, [start])

In this the substring given in parameters is searched for in the String and if it is found the index number of the searched character or substring within the string is returned. Here the order of search is from end to beginning of the String. If it is not found the value returned is -1. Start is an optional argument specifying the position within string to begin the search. Default is string.length-1. For example
"exfor".lastIndexOf("o")

will give a value of 3. This is because the position of text o appearing in the string is counted from the end of string and the end of string is equal to stringlenth -1 which is equal to 4 and so position of o appearing in the string is 3. substring method of String Object:

General syntax of substring method of String Object in JavaScript is as follows:


substring(from, [to])

In this method characters in the string between from and to indexes is returned "to" is optional, and if omitted, characters up to the end of the string is returned. For example:

<html> <body> <script type="text/javascript"> var exf="Welcome" document.write(exf.substring(0,3)); document.write(exf.substring(3,0)); </script> </body> </html>

Output of the above program is


Wel ome

This is because the first substring extracts text starting from the first till the second character which gives Wel as output and the second substring extracts text starting from the fourth till the end of string as the optional to is not specified. We have seen only some of the methods of the String Object above. Apart from these, there are many other methods available for String Object like split, slice, charAt, concat, replace.

JavaScript Date Object


In this JavaScript tutorial, you will learn about date object and methods of date object explained along with syntax and example.
JavaScript Date Object:

Usage of Date Object: Date object of Java Script is used to work with date and times. General syntax for defining Date object in Java Script is as follows:
var variablename=new Date( )

In the above new is a keyword which creates an instance of object and Date() definesvariablename as Date Object. For example:
var exf=new Date( )

In the above example, variable exf is defined as Date object which has current date and time as its initial value.

Methods of Date Object:

Some of the methods available with Date object are:


setSeconds()-

Sets the seconds for a specified date according to local time. setMinutes() - Sets the minutes for a specified date according to local time. setHours() - Sets the hours for a specified date according to local time. setDate() - Sets the day of the month for a specified date according to local time. setMonth() - Sets the month for a specified date according to local time. setYear() - Sets the year (deprecated) for a specified date according to local time. setFullYear() - Sets the full year for a specified date according to local time. toString() Returns a string representing the specified Date object. getSeconds() - Returns seconds in the specified date according to local time. getMinutes() - Returns minutes in the specified date according to local time. getHours() - Returns hour in the specified date according to local time. getDay() - Returns day of the week for a specified date according to local time getDate() - Returns day of the month for a specified date according to local time. getMonth() - Returns month in the specified date according to local time. getYear() - Returns year (deprecated) in the specified date according to local time. getFullYear() - Returns year of the specified date according to local time. Example for usage of Date Object methods mentioned above:
var exf=new Date() exf.setFullYear(2020,0,20)

As we have seen setFullYear() is used for Setting the full year for a specified date according to local time. In the above example the Date object exf is set to the specific date and year 20th January 2020 Example for using methods of Date Object

<html> <body> <script type="text/javascript"> var exforsys=new Date(); var currentDay=exforsys.getDate(); var currentMonth=exforsys.getMonth() + 1; var currentYear=exforsys.getFullYear(); document.write(currentMonth + "/" + currentDay + "/" + currentYear);

</script> </body> </html>

Output of the above program is:


11/15/2006

In the above example:


A variable exforsys is declared. . Then a new instance of the date() object is created using new keyword and is assigned toexforsys variable. . After this statement a variable called currentDay is declared and this is given the value of current day of the month. This is done by using the value of the variable exfrosys, along with dot operator in conjunction with getDate() method. . After this statement a variable called currentMonth is declared and this is given the value of current month. This is done by using the value of variable exfrosys, along with dot operator in conjunction with getMonth() method. Here one can see that we have added "1" to the value of method before assigning it to month variable. This is because months are counted, starting with "0", i.e. January = "0", December ="11". By adding "1", it now becomes the current month. The same concept must be used while getting day of the week also. . After this statement a variable called currentYear is declared and this is given the value of current Year. This is done by using the value of variable exfrosys, along with dot operator in conjunction with getFullYear() method. . At last, a string is created to print out the current full date, using a document.writestatement.

JavaScript Math Object


In this JavaScript tutorial, you will learn about Math Object, usage, properties and methods of math object along with syntax and examples.
Usage of Math Object:

JavaScript Math object is used to perform mathematical tasks. But unlike the String and theDate object which requires defining the object, Math object need not be defined. Math object in JavaScript has two main attributes:
Properties Methods

Properties of Math Object:

The JavaScript has eight mathematical values and this can be accessed by using the MathObject. The eight mathematical values are:
E PI square root of 2 denoted as SQRT2 square root of 1/2 denoted as SQRT1_2 natural log of 2 denoted as LN2 natural log of 10 denoted as LN10 base-2 log of E denoted as LOG2E base-10 log of E denoted as LOG10E

The way of accessing these values in JavaScript is by using the word Math before these values namely as
Math.E Math.LOG10E and so on

Methods of Math Object:

There are numerous methods available in JavaScript for Math Object. Some of them are mentioned below namely:
abs(x) - Returns absolute value of x. acos(x) - Returns arc cosine of x in radians. asin(x) - Returns arc sine of x in radians. atan(x) - Returns arc tan of x in radians. atan2(y, x) - Counterclockwise angle between x axis and point (x,y). ceil(x) - Returns the smallest integer greater than or equal to x. (round up). cos(x) - Returns cosine of x, where x is in radians. exp(x) - Returns ex floor(x) - Returns the largest integer less than or equal to x. (round down) log(x) - Returns the natural logarithm (base E) of x. max(a, b) - Returns the larger of a and b. min(a, b) - Returns the lesser of a and b. pow(x, y) - Returns xy random() - Returns a pseudorandom number between 0 and 1. round(x) - Rounds x up or down to the nearest integer. It rounds .5 up. sin(x) - Returns the Sin of x, where x is in radians. sqrt(x) - Returns the square root of x. tan(x) - Returns the Tan of x, where x is in radians.

Example for Math Object methods mentioned above:

<html>

<body> <script type="text/javascript"> document.write(Math.round(5.8)) </script> </body> </html>

The output of the above program is


6

This is because the round() method rounds the number given in argument namely here 5.8 to the nearest integer. It rounds .5 up which gives 6. Another example for using Math Object in JavaScript.

<html> <body> <script type="text/javascript"> document.write(Math.max(8,9) + "<br />") document.write(Math.max(-5,3) + "<br />") document.write(Math.max(-2,-7) + "<br />") </script> </body> </html>

Output of the above program is


9 3 -2

The above example uses the max() method of the Math object which returns the largest of the two numbers given in arguments of the max method.

JavaScript Iterative Structures - Part I


Author : Exforsys Inc. Published on: 26th Jul 2007

JavaScript Iterative Structures - Part I


In this JavaScript tutorial, you will learn about JavaScript Iterative Structures, for loop, for..in statement, break and continue explained along with syntax and examples. Iterative Structures are used to execute a certain piece of code a specified number of times or until the condition mentioned remains true. The Iterative structures are also termed looping in programming terminology. Iterative Structure is an important part of programming terminology. When a programmer wants to repeat the same code a number of

times, he or she does not have to rewrite the code again and again, resulting in poor code performance. Instead, the programmer can use looping statements to repeat a block of code until the condition specified is true or repeated a specified number of times. Looping can be achieved in JavaScript using various statements:
for loop while loop do..while loop for..in loop

for loop:

This is used when a programmer knows for certain the number of times a block of code should be executed. The general syntax of the for loop structure of a JavaScript is as follows:

for (variable=starting_value; variable relational_operator condition;var=var_incrment/decrement) { Block of Code to be executed }

An Example of for loop of JavaScript

<html> <body> <script type="text/javascript"> var exfor=1 for (exfor=1;exfor<=15;exfor++) { document.write("Value is: " + exfor) document.write("<br />") } </script> </body> </html>

The output of the above example is

Value Value Value Value Value Value Value Value Value Value Value Value Value Value Value is: 15

is: is: is: is: is: is: is: is: is: is: is: is: is: is:

1 2 3 4 5 6 7 8 9 10 11 12 13 14

In the above example, the variable exfor is initialized with a starting value of 1 and the loop executes with this value (as the value is less than 15) and by the statement document.write , the output is written with the current value of variable exfor (which is 1). Then line break is given which gives a new line. Then again control passes to the for loop and the value of exfor is incremented by 1 (by the command exfor++) . This gives the value of exfor as 2 and this is checked with the condition in for statement. Since 2 is less than 15 again, for loop executes and the value of variable exfor prints, continuing until the variable exfor reaches the value 15. Then the value increments to 16, which is greater than 15, taking control out of for loop.
for..in statement:

for..in statement will be explained after the concept of arrays is discussed in the next chapter. There may be situation when programmers want to come out of the loop explicitly or want to break the current loop and continue with the next value. To handle these situations, JavaScript uses two commands:
Break Continue

Break:

The break command is used for breaking the loop and continuing with the execution of the code that follows after the loop. The general structure of this command is

break

for example:

<html> <body> <script type="text/javascript"> var exfor=1 for (exfor=1;exfor<=15;exfor++) { if (exfor==4){break} document.write("Value is: " + exfor) document.write("<br />") } </script> </body> </html>

The output of the above program is


Value Value Value is: 3 is: is: 1 2

In the above program, the initial value of the variable exfor is 1. Inside the for loop the if condition checks to see if the value of variable reaches the value 4. Until the value of the variable exfor reaches 4, the for loop executes and, as a result, the values 1,2,3 print. When the value of exfor reaches 4, the break statement executes and, as a result, the control moves or breaks out of the for loop.
Continue:

The command continue is used for breaking the current loop and proceeding with the next value. The general structure of this command is:
continue

<html> <body> <script type="text/javascript"> var exfor=1

(exfor=1;exfor<=15;exfor++) { if (exfor==4){continue} document.write("Value is: " + exfor) document.write("<br />") } </script> </body> </html>

for

The output of the above program is


Value Value Value Value Value Value is: 7 is: is: is: is: is: 1 2 3 5 6

In the above program, the initial value of the variable exfor is 1. Inside the for loop, the if condition checks to see if the value of variable reaches the value 4. Until the value of the variable exfor reaches 4 the for loop executes and, as a result, the value 1,2,3 prints. When the value of exfor reaches 4, the continue statement executes and, as a result, the current value 4 is skipped and the loop proceeds to the next value of the variable (5) and proceeds as before.

JavaScript Arrays
Page 1 of 2
Author : Exforsys Inc. Published on: 7th Jun 2007

JavaScript Arrays
In this JavaScript tutorial, you will learn about JavaScript Array, different ways of defining an array in JavaScript viz. traditional way, shorter form, literal array, accessing the elements in an array and editing the values or elements in an array. The array concept is used to store a set of values in a single variable name. This is a very important concept in any programming language. In this section, how to define and handle arrays in JavaScript is examined.

In order to work with the concept of arrays in JavaScript, there are many sections the programmer must become familiar with.
Array Definition Accessing the elements in an array Editing the values or elements in an array. Single Dimensional Array Two Dimensional Arrays Different Operations with Array

Array Definition:

The array must first be defined before it is accessed or used. There are a variety of ways this can be accomplished in JavaScript. Below are some of the ways of defining arrays in JavaScript. Depending on convenience, the programmer can choose from any of the following techniques to define arrays in JavaScript:
Defining an Array in JavaScript:

Array is defined in JavaScript by making use of the keyword new. General format of defining array in JavaScript is as follows:

var varaiblename = new Array( )

For example, if a programmer wants to define an array exforsys, it is written as follows:

var exforsys = new Array( )

Values or elements can be added in various ways to the above-defined array:


Traditional way:

This is the traditional way of adding elements to array in JavaScript. The first element of the array in JavaScript always starts with an index as zero. The format for adding elements in this structure is as follows:

var varaiblename = new Array( variablename[0]=element1

variablename[1]=element2 variablename[2]=element3 variablename[3]=element4

For example, if the programmer wants to store 4 elements (Training, Division, Institute, Company ) to the array named Exforsys, it is written as follows:

var Exforsys = new Exforsys[0]=Training Exforsys[1]=Division Exforsys[2]=Institute Exforsys[3]=Company

Array(

It is also possible that if the programmer is certain of the array length, it can be defined while defining the array itself as:

var Exforsys = new Array(4)

Note that in the above example, since the value of the elements are strings, they are defined inside the double quotes. If the elements to be stored are integers, then they are placed without the double quotes. For example, if one wants to store 15 in array Exforsys it is written as follows:

var Exforsys = new Exforsys[0]=15

Array(

Shorter form:

The elements can also be defined in a shorter form as:


var variablename=new Array(element1,element2,elements3,.)

The same example used above (the array named Exforsys containing 4 elements) can be represented in a shorter form as: By this method of representation, the definition of the array and the defining of the elements in the array is written in a single step.

var Exforsys=new Array(Training,Division,Institute,Company)

Table of Contents JavaScript Arrays Accessing JavaScript array elements

Accessing JavaScript array elements


Page 2 of 2
Author : Exforsys Inc. Published on: 7th Jun 2007

JavaScript Arrays
Accessing the elements in an array:

An element in an array can be accessed by referring to the name of the array, followed by open braces [inside which the index number of the element to be accessed is placed and then the braces are closed using]. The index of an array in JavaScript starts with 0. For example, if a programmer wants to write the element Institute define in the array exforsys below. It is written as follows:
var Exforsys=new Exforsys[0]=Training Exforsys[1]=Division Exforsys[2]=Institute Exforsys[3]=Company document.write(exforsys[2]) Array( )

will write Institute as output.

Editing the values or elements in an array: It is also possible that the value or elements of the array defined can be edited or modified.

This is written using the same approach for accessing array elements.

For example, if a programmer wants to change the value of Division to Output it can simply be written as follows:

Exforsys[1]=Output

Literal Array:

General format for defining the literal array is as follows:

var variablename=[element1,element2,.]

For example, if a programmer wants to define an array named exforsys with the first element Example, the second and third elements of the array as undefined and the fourth element as Training, it can be written as follows:

var Exforsys=[Example, , , Training]

Thus, using this method, the programmer has the flexibility to leave elements undefined between the arrays.

JavaScript Functions
In this JavaScript tutorial, you will learn about JavaScript functions and how to create them.
What is a function?

Function is a block of code that can be reused as and when needed at various places. The function executes whenever it is called.
JavaScript Functions:

How does a programmer define, create and handle functions in JavaScript? In JavaScript, the programmer must learn the following broad classifications to fully understand the concept of functions.
1. Idea of JavaScript functions

2. Creating a function in JavaScript 3. Passing values to function 4. Returning values from a function

Idea of JavaScript Functions:

As mentioned above, a function is a piece of code that is reusable by the programmer as and when needed. The function executes when it is called and this calling can be done either by an event or by a calling program. Functions in JavaScript are defined at the beginning of the page and are placed in the section. The functions placed in JavaScript can be called from anywhere.
Creating a Function in JavaScript:

General syntax for creating a function in JavaScript is as follows:

function name_of_function(argument1,argument2,arguments) { //Block of }

Code

In the above syntax, argument1, argument2,argument3 are optional. They are only placed if some values or data needs to be passed to the function. If the function does not have any values to be passed, then the syntax of function in JavaScript would be as follows:

function name_of_function( { //Block }

) of Code

In the above syntax, the first word function represents a keyword, followed by the name of the function and then the block of code which is to be placed within the braces { and }. JavaScript is case-sensitive, care must be taken to write the keywords with lower case only as specified above. For example, if a programmer wants to create a function exforsys with no data passed to function it is written in JavaScript as follows:

function exforsys( { //Block }

) of Code

Passing values to JavaScript Function


Page 1 of 2
Author : Exforsys Inc. Published on: 5th Jun 2007 | Last Updated on: 21st Jan 2009

Passing values to JavaScript Function


In this JavaScript Tutorial you will learn about how to pass values to and also how to return values from a JavaScript function.
Passing Values to function:

Values can be passed to a function as parameters. The general syntax for passing values to a function in JavaScript is:

function name_of_function(argument1,argument2,argumentn) { //Block of }

Code

In the above argument1, argument2,...argumentn represents the values passed to the function. For Example: Suppose a programmer wants to create a function with name exforsys, which takes two values x and y. These two values are passed from the calling program. Then function takes up the shape as follows:

function exforsys(x,y)

{ //Block }

of

Code

Suppose the values passed to the function from the calling program are 10 and 15. Then, from the calling program the function is called as follows:

exforsys (10,15)

Returning Values from Function


Page 2 of 2
Author : Exforsys Inc. Published on: 5th Jun 2007 | Last Updated on: 21st Jan 2009

Passing values to JavaScript Function


Returning Values from Function:

After executing the function, there may be situations where the programmer wants to return some value from the function to the calling program. This is achieved by using the return statement in JavaScript. The general syntax of this return statement is as follows:

return variablename

An example to understand this concept: Suppose the programmer wants to create a function with name exforsys, which takes two values x and y. The function is written to add these values and return the result of the addition to the calling program. This is achieved in JavaScript as follows:

function exforsys(x,y) { z=x+y return z

Thus, in the above example, the added value x+y is stored in variable z and returned to the calling program using the statement

return z

In the calling program, suppose the values passed to the function from the calling program are 10 and 15. From the calling program, the function is called as follows:

result=exforsys(10,15)

The returned value z is the addition of two values x and y of the function exforsys . This is stored in the variable result in the calling program. A complete example of a function in JavaScript:

<html> <head> <script type="text/javascript"> function exforsys(x,y) { return x+y } script> head> <body> <script type="text/javascript"> document.write(exforsys(10,15)) script> body> html>

The output of the above program is

25

Thus, in the above example, the function creation is done on the <head> section of the program. The function exforsys is called with values 10 and 15 passed to the function and the added value 25 is returned from the function using the return statement. This is stored in the function name exforsys and then printed in the calling program.

JavaScript Two Dimensional Arrays


In this JavaScript tutorial you will learn about two dimensional arrays - how to define and access two dimensional array in JavaScript.

Two Dimensional Arrays in JavaScript:


Two Dimensional Arrays are storing elements in a structure similar to that of a table.
Defining Two Dimensional Arrays in JavaScript:

One of the vital points to note is JavaScript does not support multi-dimensional arrays and thereby does not support Two Dimensional Array. In order to create a Two Dimensional Array in JavaScript, the programmer must use the concept of creating the Single Dimensional Array while employing a small trick in the code. Two-Dimensional Arrays in JavaScript are constructed by creating an array of arrays. JavaScript does not directly allow creation of a Two-Dimensional Array. Two-Dimensional Arrays in JavaScript are constructed when the inner array is created first and then, using this initial array, the outer array is then populated. For example defining

var Exforsys=new Array(4)

defines 4 storage area for the array named as Exforsys. That is

A two-dimensional array can be built by defining another array on each of Exforsys[0], Exforsys[1], Exforsys[2], Exforsys[3]

This is done as follows:

var Exforsys=new for (i=0; Exforsys[i]=new Array(4)

<4;

Array(4) i++)

This gives structure as follows:

This shows a two-dimensional array constructed using the single dimensional concept of arrays in JavaScript. The next step is adding elements to two-dimensional arrays using JavaScript. The elements can be added to the two-dimensional array in JavaScript using double brackets. For example, to store elements in the above two dimensional array named Exforsys we write:

Exforsys[0][0]="Example1" Exforsys[0][1]="Example2" Exforsys[0][2]="Example3" Exforsys[0][3]="Example4" Exforsys[1][0]="Example5" Exforsys[1][1]="Example6" Exforsys[1][2]="Example7" Exforsys[1][3]="Example8" Exforsys[2][0]="Example9" Exforsys[2][1]="Example10" Exforsys[2][2]="Example11" Exforsys[2][3]="Example12" Exforsys[3][0]="Example13" Exforsys[3][1]="Example14" Exforsys[3][2]="Example15"

Exforsys[3][3]="Example16"

Thus the above two dimensional array named as Exforsys has 4*4 =16 storage spaces.

JavaScript Array Operations


In this JavaScript tutorial, you will learn about different operations with array in JavaScript, how to use the for...in statement, Combining Operations between arrays and within elements of an array, joining two or more arrays and joining elements of an arrays along with syntax and example scripts.
forin statement:

The forin statement is used for looping through the elements of the array. The general structure of the for..in statement in JavaScript is as follows:
for { ............ ............ } //Block of Code to be executed (variablename in arrayname)

<html> <body> <script type="text/javascript"> var A var Exforsys=new Array() Exforsys[0] = "Training" Exforsys[1] = "Example" Exforsys[2] = "Company" for (A in Exforsys) { document.write(Exforsys[A] + "<br />") } </script> </body> </html>

The output of the above example is


Training Example Company

In the above example, the variable name defined inside the for..in statement is A, which is used as an index for moving through the array Exforsys. Combining Operations between arrays and within elements of an array: It is possible to perform various operations between arrays and within elements of an array. One of these is the combining operation, which uses two aspects:
* Joining Two or more arrays

* Joining elements of a array

Joining two or more arrays:

The operation of Joining Two arrays can be performed using the predefined function concat( ). The general format of concat( ) is: arrayname1.concat(arrayname2,arrayname3,.arraynamen)

<html> <body> <script type="text/javascript"> var exforsys=new Array(4) exforsys[0]="Example1" exforsys[1]= "Example2" exforsys[2]= "Example3" exforsys[3]="Example4" var company=new Array(4) company[0]="Training1" company[1]="Training2" company[2]="Training3"

company[3]="Training4" document.write(exforsys.concat(company)) </script> </body> </html>

The output of the above script is


Example1,Example2,Example3,Example4,Training1,Training2,Training3,Training4

In the above example we have concatenated elements of two arrays.

Joining elements of an array:

This is performed by using the join( ) method in JavaScript. The join method returns a string containing the elements of the array. The general format of join( ) method is as follows: arrayname.join(paramter) In the above example, the parameter given is dot( . ), then each element of the joined array would be separated with a dot. for example:

<html> <body> <script type="text/javascript"> var exforsys=new Array(4) exforsys[0]="Example1" exforsys[1]= "Example2" exforsys[2]= "Example3" exforsys[3]="Example4" document.write(exforsys.join(".")) </script> </body> </html>

gives output as
Example1.Example2.Example3.Example4

The parameter given in join is optional.

JavaScript Events Handling


In this JavaScript tutorial, you will learn about handling events in JavaScript, what is event handling in JavaScript? events in JavaScript, events associated with mouse - onmousemove, onclick, ondblclick, onmouseout, onmouseover, events associated with keyboard onkeydown, onkeyup, onkeypress. onerror, onfocus, onblur, onsubmit, onload and onunload.
What is Event Handling in JavaScript?

This is a very vital concept of JavaScript because without events there would be no code. Event handling is the execution of code for the users reaction. In other words, when a user performs some action, the associated event fires or executes. For example, if a programmer

want a piece of code to execute when a user presses a button, then the code is placed in the onclick event of the button, executing the code when the user clicks that button. In addition, there are events in JavaScript that are automatically fired without the intervention of the user. The load event fires when the page loads. Thus, there are various scenarios for firing events such as:
When the user performs some action based on which event fires When the page load event fires When some fields change, the associated events fire.

Events in JavaScript:

There are numerous events in JavaScript, some of which are listed below. A particular object has numerous events associated with it, depending on the action taken by the user. For example, the object mouse has numerous events associated with it which depend on the users actions.
Events associated with Mouse: onmousemove:

If the user moves a button, then the events associated with onmousemove fire.
onclick:
onclick events fire when the mouse button clicks.

ondblclick:

The event ondblclick fires when the mouse button is double clicked. There are also some events associated with the mouse pointer position such as:
onmouseout:
onmouseout event fires if the mouse pointer position is out of focus from the element.

onmouseover:
onmouseover event fires if the mouse pointer position is in focus of the element position.

The above are some of the various mouse events available in JavaScript.
Events associated with Keyboard:
onkeydown onkeyup onkeypress

onkeydown:
onkeydown event fires when key is pressed.

onkeyup:
onkeyup event fires when key is released.

onkeypress:

The event onkeypress fires if the onkeydown is followed by onkeyup. There are many additional events available in JavaScript. A few are listed below:
onerror:
onerror event fires when an error occurs.

onfocus:

When a element gains focus, onfocus event fires or executes.


onblur:

In contrast to an onfocus event, this event fires when the element loses its focus. Bothonfocus and onblur may be used for handling validation of forms.
onsubmit:

The event onsubmit fires when the command form submit is given. This event is used for validating all fields in the form before submitting the form.
onload:
onload event automatically executes as soon as the document fully loads. This loads when

the user enters the page. This is a commonly used event. This event is used to check compatibility with the browser version and type. Based on this compatibility, the appropriate version of a page will then load.
onunload:

In contrast to onload event, the onunload event fires when the user leaves the page.

JavaScript Event Handler


In this JavaScript tutorial, you will learn about using event handlers along with events for each HTML tag.

Using Event Handler in JavaScript:

Event Handlers are used in JavaScript by placing the name of the event handler inside the HTML tag associated with object. This is followed by =JavaScript code, the code in JavaScript which must execute when the event fires. The events for each HTML tag are as follows: <A>
click mouseOver mouseOut (onMouseOut) (onClick) (onMouseOver)

<AREA>
mouseOver mouseOut (onMouseOut) (onMouseOver)

<BODY>
blur error focus load unload (onUnload) (onBlur) (onError) (onFocus) (onLoad)

<FORM>
submit reset (onReset (onSubmit)

<FRAME>
blur focus (onFocus) (onBlur)

<FRAMESET>
blur error focus load unload (onUnload) (onBlur) (onError) (onFocus) (onLoad)

<IMG>

abort error load (onLoad)

(onAbort) (onError)

<INPUT TYPE = "button">


click (onClick)

<INPUT TYPE = "checkbox">


click (onClick)

<INPUT TYPE = "reset">


click (onClick)

<INPUT TYPE = "submit">


click (onClick)

<INPUT TYPE = "text">


blur focus change select (onSelect) (onBlur) (onFocus) (onChange)

<SELECT>
blur focus change (onChange) (onBlur) (onFocus)

<TEXTAREA>
blur focus change select (onSelect) (onBlur) (onFocus) (onChange)

For example, consider a button placed in a form named PressButton. The following code placed in the click event of the button named PressButton would be written:

<input type="button" name="PressButton" value="Press the Button onClick="outputvalue();">

to

output

value!!!"

In the above example, when the user clicks the button, the onclick event of the button fires and the message assigned to value displays:
Press the Button output value!!!

The block of code written in the function outputvalue() in JavaScript fires or calls.

JavaScript Exception Handling Part I


In this JavaScript tutorial, you will learn about Exception Handling, Catching errors in JavaScript, Using try..catch statement and throw in JavaScript along with syntax and examples. It is impossible for a programmer to write a program without errors. Programming languages include exceptions, or errors, that can be tracked and controlled. Exception handling is a very important concept in programming technology. In earlier versions of JavaScript, the exceptions handling was not so efficient and programmers found it difficult to use. Later versions of JavaScript resolved this difficulty with exceptions handling features like try..catch handlers, which presented a more convenient solution for programmers of JavaScript.
Catching errors in JavaScript:

It is very important that the errors thrown must be catched or trapped so that they can be handled more efficiently and conveniently and the users can move better through the web page. There are mainly two ways of trapping errors in JavaScript.
Using trycatch statement Using onerror event

Using trycatch statement:

The try..catch statement has two blocks in it:


try block catch block

In the try block, the code contains a block of code that is to be tested for errors. The catch block contains the code that is to be executed if an error occurs. The general syntax of try..catch statement is as follows:

try { } catch { }

//Block

of

code

which

is

to

be

tested

for

errors (err)

//Block of code which is to be executed if an error occurs

When, in the above structure, an error occurs in the try block then the control is immediately transferred to the catch block with the error information also passed to the catch block. Thus, the try..catch block helps to handle errors without aborting the program and therefore proves user-friendly. The concept of trycatch statement shown in an example:

<html> <head> <script type="text/javascript"> try { document.write(junkVariable) } catch(err) { document.write(err.message }

"<br/>") </script> </head> <body> </body>

</html>

The output of the above program is


junkVariable is undefined

In the above program, the variable junkVariable is undefined and the usage of this in try block gives an error. The control is transferred to the catch block with this error and this error message is printed in the catch block.

throw in JavaScript:

There is another statement called throw available in JavaScript that can be used along with trycatch statements to throw exceptions and thereby helps in generating. General syntax of this throw statement is as follows:
throw(exception)

exception can be any variable of type integer or boolean or string. for example:

<html> <head> <script type="text/javascript"> try { var exfor=10 if(exfor!=20) { "PlaceError" }

throw } catch(err) {

if(err == "PlaceError") document.write ("Example to illustrate Throw Statement: Variable exfor not equal to 20. <br/>") } </script> </head> <body> </body> </html>

The output of the above program is:


Example to illustrate Throw Statement: Variable exfor not equal to 20.

In the above example program, the try block has the variable exfor initialized to 10. Using the if statement, the variable value is checked to see whether it is equal to 20. Since exfor is not equal to 20, the exception is thrown using the throw statement. This is named PlaceError and the control transfers to the catch block. The error catched is checked and

since this is equal to the Placeerror, the statement placed inside the error message is displayed and the output is displayed as above.

JavaScript Exception Handling Part II


In this JavaScript tutorial, you will learn about exception handling viz. trycatch..finallystatement and nested trycatch statements along with syntax and examples.
trycatch..finally Statement:

JavaScript has a finally statement that can be used as an optional construct along withtry..catch statements. The finally construct placed in a trycatch construct is an optional statement. When the finally statement is placed in a trycatch construct, it always runs following the trycatch structure. The general syntax of a trycatch..finally statement is as follows:

try { //Block of code which is to be tested for errors } catch(err) { //Block of code which is to be executed if an error occurs } finally { //This is optional and runs after try and catch structure has run. }

for example:

<html> <head> <script type="text/javascript"> try { document.write(junkVariable) }

document.write(err.message

document.write("Finally

Block

entered:

catch(err) { "<br/>") } finally { Welcome") } </script> </head> <body> </body>

</html>

The output of the above program is


junkVariable Finally Block entered: Welcome is undefined

In the above program, after the try block is executed, the catch block throws the error. The finally statement is then executed last, displaying the second message Finally Block entered: Welcome Additional usage information about trycatch..finally and throw statements:
Nested trycatch Statements:

It is also possible to have nested try..catch statements or one try..catch statement placed inside another. for example:

try{ ......... ......... //Block //Block of of code code try { code code } catch(Err) { code code } code code

......... .........

//Block //Block

of of

........ ........ ........ ........

//Block //Block //Block //Block

of of of of

} catch(err1) { ........ ........ } finally { ........ ........ } //Block //Block of of code code //Block //Block of of code code

* It is also possible to catch the error placed in the inner try..catch statement, then use that error in the outer catch statement of the nested try..catch statement using the throw statement of JavaScript. * Using the throw statement, it is possible for the programmer to throw errors at any point.

JavaScript OnError Event


Author : Exforsys Inc. Published on: 4th Aug 2007 | Last Updated on: 25th Feb 2011

JavaScript OnError Event


In this JavaScript tutorial, you will learn about onerror event, how to use onerror event along with syntax and example.
Using onerror event:

The onerror event fires when a page has a script error. This onerror event occurs in JavaScript when an image or document causes an error during loading. This does not mean that it is a browser error. This event handler will only be triggered by a JavaScript error, not a browser error. The general syntax of onerror event is as follows:

onerror=functionname() function { var1=msg; var2=file_loc; var3=line_num; return functionname(msg,file_loc,line_num)

true/false;

The onerror event is called by writing a function. This function is called by assigning to theonerror and the function written takes three arguments:
message text URL line number of the error line

When an error occurs, the written function is invoked. The three values above are set to three variables. The function returns either true or false value using the return statement. The programmer would return the value false from the function if the programmer wants the browser to display the standard error message on the screen. If the programmer does not want to display the standard error message, then the returned value must be true from the function. An example to understand the concept of onerror event in JavaScript:

<html> <head> <script type="text/javascript"> onerror=exfoerr var function { text1="Error text1+="Error: " text1+="URL: " text1+="Line Number: text1+="Click OK alert(text1) return } function { addxlert("Click } text1="" exfoerr(msg,url,line) Displayed\n\n" + "\n" + "\n" + "\n\n" continue.\n\n" true display() to Proceed!!!!") </script> </head> <body> message" </body> </html>

+ + "

msg url + line to

<input type="button" onclick="display()" />

value="View

The output of the program would be


Error Displayed Error: URL: Line: 18 Click to Proceed!!!! Object http://URL expected displayed

In the above example program, the function display() has an error in it (the addalert is typed wrongly as addxlert). When the program reads this error, the onerror event handler fires and the function exfor( ) is called with the three parameters passed to it (the error message, the url of the page and the line number of error 18). These are displayed in the function which produced the output above.

JavaScript Boolean Object


Page 1 of 2
Author : Exforsys Inc. Published on: 7th Jun 2007

JavaScript Boolean Object


In this JavaScript tutorial you will learn about JavaScript boolean object, how to pass value to the boolean object, properties and methods used with boolean object.
Usage of the Boolean Object:

The Boolean object is a wrapper for the Boolean data type. The Boolean object is used to convert a non-Boolean value to a Boolean value. If a programmer wants to convert a nonBoolean value to a Boolean value, he can use Boolean as a function to perform this task, instead of using a Boolean object to convert a non-Boolean value to a Boolean value. The Boolean object returns false when the passed value to the object is any one of the following:
0 "" false undefined NaN

Other than the above values, any other value passed to the Boolean Object returns true. The programmer must clearly understand that a Boolean object is different from Boolean data type.

When an objects value is not undefined or null (including a Boolean object whose value isfalse), it evaluates to true when passed to a conditional statement. For example, the condition in the following if statement evaluates to true:

z if(z)

= new Boolean(false); //Condition returns true

The above concept does not apply for Boolean primitives. For example, the condition in the following if statement evaluates to false:

y if(y)

= false; //Condition returns false

General Syntax for defining the Boolean Object:

General Syntax for defining the Boolean Object is as follows:

var variable_name=new Boolean()

Here the keyword new is used to define the Boolean object. For example:

var exforsys=new Boolean()

The above example defines a Boolean Object exforsys.


How to pass value to the Boolean object:

The general syntax for writing this is as follows:

var variable_name = new Boolean(value)

The above statement creates a Boolean Object given in a variable name with the initial value set to the value passed in arguments of the Boolean. The value can be any one of the following:
0, "", false, undefined, NaN, true, any string and so on.

For example:

var exforsys var sample = new Boolean(true)

= new Boolean("Training")

The above example creates two Boolean objects exforsys and sample with initial value astrue.

var exforsys1 var sample1 = new Boolean(NaN)

= new Boolean(false)

The above example creates two Boolean objects exforsys1 and sample1 with initial value as false.

JavaScript Array Object Methods Part I


In this JavaScript tutorial, you will learn about Array Object Methods - concat(), join(), pop(), push() and reverse() methods along with general syntax and examples.
concat()

The concat() method is used to join two or more Array objects together to produce a new one. In the concat() method, the original Array objects are unaffected by this method and only a copy of the new concatenated array is returned. General syntax of the concat() method of the Array object of JavaScript: arrayObject.concat(arrayname1,arrayname2,......,arraynamen) An example to understand this concept in detail:

<html> <body> <script type="text/javascript"> var exforsys = new Array(3) exforsys[0] = "Welcome" exforsys[1] = "To" exforsys[2] = "Training" var example = new Array(3) example[0] = "Given" example[1] = "By" example[2] = "Exforsys" document.write(exforsys.concat(example)) </script> </body> </html>

The

output

of

the

above

example

is

Welcome To Training Given By Exforsys

The concat() method has an argument, the array object example is concatenated with the array object exforsys.
join()

The join()method is used to join all the elements of an array into a single string. The elements are separated by an optional string separator specified in the join() method. If no string separator is specified in the join() method, then the default string separator used is comma. General syntax of the join() method of the Array object of JavaScript: arrayObject.join(separator) The separator specified in argument is optional and a comma is used as a separator. An example to understand this concept in detail:

<html> <body> <script type="text/javascript"> = new Array(4)

var

exforsys

exforsys[0] = exforsys[1] = exforsys[2] = exforsys[3]= document.write(exforsys.join() document.write(exforsys.join("!")) </html>

"Welcome" "To" "Training" "Exforsys" "<br />") </script> </body>

The

output

of

the

above

example

is

Welcome,To,Training Welcome!To!Training

In the first document.write statement has no separator argument given in the argument of the join() method of the array object exforsys and the default separator, the comma is used in output. In the second document.write statement of the above example the separator argument given in the argument of the join() method of the array object exforsys is ! and so this is used in output.
pop()

The method pop() is used to remove and return the last element of an array and therefore the length of the array object gets changed by this method. General syntax of the pop() method of the Array object of JavaScript: arrayObject.pop() Let us see an example to understand this concept in detail:

<html> <body> <script type="text/javascript"> var exforsys = new Array(4) exforsys[0] = "Welcome" exforsys[1] = "To" exforsys[2] = "Exforsys" exforsys[3] = "Training" document.write(exforsys + "<br />") document.write(exforsys.pop() + "<br />")

document.write(exforsys) </script> </body> </html>

The output of the above example is

Welcome,To,Exforsys,Training Training Welcome,To,Exforsys

In the above example, the array object exforsys elements are first outputted and the pop() method is used with the array object exforsys. This removes and returns the last element of the array object exforsys (Training). Then the next document statement prints the array without the last element since it has been popped out in the previous statement.

push() and reverse() ArrayObject Methods


Page 2 of 2
Author : Exforsys Inc. Published on: 17th Jul 2007

JavaScript Array Object Methods Part I


push()

push() method of an array object contrasts to the pop() method. push() method is used to add one or more elements to the array. This is added to the end of the array, changing the length of the array object. The new length is returned by the push() method. General syntax of the push() method of the Array object of JavaScript: arrayObject.push(element1,element2,....,elementn) Here element1, element2,...., elementn represents the new elements to be added to the array object. It is required that at least element1 must be present. This means, in order for it to be added, there must be at least one element specified in argument of the push(). An example to understand this concept in detail:

<html> <body> <script type="text/javascript"> = new Array(4)

var

exforsys

exforsys[0] = exforsys[1] = exforsys[2] = exforsys[3] = document.write(exforsys + document.write(exforsys.push("Good document.write(exforsys) </html>

"<br Day") +

"Welcome" "To" "Exforsys" "Training" />") "<br />") </script> </body>

The

output

of

the

code

above

will

be:

Welcome,To,Exforsys,Training 5 Welcome,To,Exforsys,Training,Good Day

In the above example, the array object exforsys elements are first outputted and then the push() method with arguments as "Good Day" is used with the array object exforsys. This adds the element after the last element. Therefore, the length of the array changes to 5 and this is then outputted. As shown in the last result, the array is printed with the new elements added to it.
reverse()

As the name implies, the reverse() method of the Array object reverses the order of the elements in an array, using the first element as the last element and the last element as the first element. The original array is changed by using the reverse() method. General syntax of the reverse() method of the Array object of JavaScript: arrayObject.reverse() An example to understand this concept in detail:

<html> <body> <script type="text/javascript"> = new Array(4) = "Welcome" = "To" = "Exforsys"

var

exforsys exforsys[0] exforsys[1] exforsys[2]

exforsys[3] = "Training" document.write(exforsys + "<br />") document.write(exforsys.reverse() + "<br />") </script> </body> </html>

The output of the code above will be:

Welcome,To,Exforsys,Training Training,To,Exforsys,Welcome

In the above example first the elements of the array object exforsys is printed as such and then the reverse() method is sued with the exforsys array object and so the first element "Welcome" is made as the last element and the last element "Training" is made as the last first element and changed array is printed

JavaScript Array Object


In this JavaScript tutorial, you will learn about JavaScript Array Object, its properties and methods.
Usage of the Array Object:

The Array object is used to store a set of values in a single variable name. There are many operations involved with Array object:
Defining Array object Adding Values to Array Accessing Array Editing or Modifying the Values of an Array

These topics have been addressed in previous sections on Arrays in JavaScript. In this section, the properties and methods of Array Object in JavaScript will be outlined.
Properties of array Object: length:

The length property of an array object returns the number of elements in an array. General Syntax of length property of an array Object in JavaScript:

arrayObject.length

For example:

<html> <body> <script type="text/javascript"> Array(2) = "Good" length:" of + arr.length) />")

var exforsys = new exforsys[0] exforsys[1] = "Best" document.write("Old value of document.write("<br arr.length=4 document.write("Modified value </html>

length:"+arr.length) </script> </body>

The output of the code above will be:

Old value Modified value of length: 4

of

length:

index Property :

The index Property is a read-only property and this gives the index of the Array Object. JavaScript Array Object
Methods of Array Object in JavaScript:

There are various methods used with Array object of JavaScript:


valueOf() sort() concat() join() pop() push() shift() reverse() slice()

splice() toString() unshift()

valueOf():

The method valueOf() of the Array object of JavaScript is used to return the primitive value of an Array object. NOTE: the valueOf() method of the Array object is usually called automatically by JavaScript and not explicitly by the programmer. General syntax of the valueOf() method of the Array object of JavaScript:

arrayObject.valueOf()

sort():

The method sort()is used to sort the elements of an array object in JavaScript. General syntax of the sort() method of the Array object of JavaScript:

arrayObject.sort(sortby)

In the above, the sortby argument is optional. If it is given, it indicates the order in which the sorting must take place which must be defined as a function. For example:

<html> <body> <script type="text/javascript"> var exforsys = new Array(5) exforsys[0] = "Test" exforsys[1] = "Welcome" exforsys[2] = "Training" exforsys[3] = "Good" exforsys[4] = "Day" document.write("The Original Array is:" +"<br />") document.write(exforsys + "<br />") document.write("The Sorted Array is:" +"<br />") document.write(exforsys.sort())

</script> </body> </html>

The output of the above example is:

The Original Test,Welcome,Training,Good,Day The Sorted Day,Good,Test,Training,Welcome

Array Array

is: is:

The first output statement prints the array as such without sorting. The seconddocument.write statement has sort() method defined in it with the Array Object exforsys. Thus, the array is sorted before printing.

JavaScript Array Object Methods Part II


In this JavaScript tutorial, you will learn about on array object methods - slice(), splice() toString(), shift() and unshift() methods along with general syntax and examples.
slice():

By using the methods of the array object the programmer is able to retrieve the first and the last elements in an array object. Suppose a programmer wishes to retrieve selected elements from an existing array. This can be performed by using the slice() method of the array object. The slice method creates a new array with the selected elements. General syntax of the slice() method of the Array object of JavaScript:
arrayObject.slice(begining,end)

The beginning and the end parameters specified in the slice() method above denote where to start the selection of elements for retrieving and where to end the selection of elements for retrieving. The beginning parameter is mandatory and must be specified. The end parameter is optional. If the end parameter is not specified in the slice() method, then everything from the position mentioned in the beginning parameter until the end of the array is retrieved. The beginning and the end parameters are represented as numbers representing the index or the position of the array elements. Example

<html> <body> <script type="text/javascript">

exforsys = new Array(4) exforsys[0] = "Welcome" exforsys[1] = "To" exforsys[2] = "Exforsys" exforsys[3] = "Training" document.write(exforsys + "<br />") document.write(exforsys.slice(1) + "<br />") document.write(exforsys) </script> </body> </html>

var

The output of the code above will be:

Welcome,To,Exforsys,Training To,Exforsys,Training Welcome,To,Exforsys,Training

In the above example, the array object exforsys elements are first outputted and then slice(1) method is used with the array object exforsys. This retrieves the elements from the first position of the array object exforsys. Since no end parameter is specified, all elements of the array from the first position until the end position are retrieved and then outputted as "To,Exforsys,Training". Printing of the array object exforsys prints the original array as slice() method does not change the original array.
splice():

If the programmer wishes to add and/or remove elements of an array, then the splice() method can be used along with the array object. General syntax of the splice() method of the Array object of JavaScript:
arrayObject.splice(index,howmany,element1,.....,elementn)

In this example, index and howmany are the mandatory parameters. The element1,.....,elementn are optional. The index argument is a number which represents the position where to add or from where to remove elements in an array object. The howmany parameter is also a number and represents the number of elements to be removed. Optionally, element1,.....,elementn represent the new elements to be added.

Example

<html> <body> <script type="text/javascript"> var exforsys = new Array(4) exforsys[0] = "Welcome" exforsys[1] = "To" exforsys[2] = "Exforsys" exforsys[3] = "Training" document.write(exforsys + "<br />") exforsys.splice(1,0,"All") document.write(exforsys+ "<br />") </script> </body> </html>

The output of the code above will be:

Welcome,To,Exforsys,Training Welcome,All,To,Exforsys,Training

In the above example, the array object exforsys elements are first outputted and splice(1,0,"All") specifies that the new element "All" is to be added to the first position of the array object exforsys. Shown as the result in the above example, the new array with the added element is printed.
toString():

The method toString() is used to convert an array to a string. The elements in the array are separated by commas and the result is then returned. General syntax of the toString() method of the Array object of JavaScript:
arrayObject.toString()

Example

<html> <body> <script type="text/javascript"> var exforsys = new Array(4) exforsys[0] = "Welcome" exforsys[1] = "To" exforsys[2] = "Exforsys" exforsys[3] = "Training" document.write(exforsys.toString()) </script> </body> </html>

The output of the code above will be:

Welcome,To,Exforsys,Training

In the above example, the array object exforsys is converted to a string using the toString() method of the array object.

JavaScript Array Object shift() and unshift()


Page 2 of 2
Author : Exforsys Inc. Published on: 17th Jul 2007

JavaScript Array Object Methods Part II


shift():

As the pop() method removes and returns the last element, the shift() method removes and returns the first element of an array object. Since the first element is removed and returned this also affects the length of the array. General syntax of the shift() method of the Array object of JavaScript:

arrayObject.shift()

Example

<html> <body> <script type="text/javascript"> var exforsys = new Array(4) exforsys[0] = "Welcome" exforsys[1] = "To" exforsys[2] = "Exforsys" exforsys[3] = "Training" document.write(exforsys + "<br />") document.write(exforsys.shift() + "<br />") document.write(exforsys) </script> </body> </html>

The output of the code above will be:

Welcome,To,Exforsys,Training Welcome To,Exforsys,Training

In the above example, the array object exforsys elements are first outputted and the shift() method is then used with the array object exforsys which removes and returns the first element of the array object exforsys (Training). The next document statement prints the array without the first element since it has been removed out in the previous statement.
unshift():

If a programmer wants to add one or more elements to the end of the array, he can use the push() method of the array object. There may be situations where a programmer might wish to add one or more elements to the beginning of the array. This can be achieved by using the unshift() method of the array object. The unshift() method of an array object is used to add one or more elements to the beginning of an array and returns the new length. General syntax of the unshift() method of the Array object of JavaScript:

arrayObject.unshift(newelement1,newelement2,....,newelementn)

The newelement1, newelement2,...., newelementn represents the new elements to be added to the array object. It is required that at least newelement1 must be present. This means there must be at least one element specified in argument of the unshift() method to be added. The newelement2,....,newelementn are optional. Example

<html> <body> <script type="text/javascript"> var exforsys = new Array(4) exforsys[0] = "Welcome" exforsys[1] = "To" exforsys[2] = "Exforsys" exforsys[3] = "Training" document.write(exforsys+"<br />") document.write(exforsys.unshift("Welcome Message")+"<br />") document.write(exforsys) </script> </body> </html>

The output of the code above will be:

Welcome,To,Exforsys,Training 5 Welcome Message,Welcome,To,Exforsys,Training

In the above example, the array object exforsys elements are first outputted and then the unshift method() used with the exforsys array object has in its argument "Welcome Message". This is added to the beginning of the array object exforsys and changes the length of the array exforsys to 5. This prints and the new array with "Welcome Message" added to the beginning of the array is outputted.

Working with JavaScript DOM Objects


Page 1 of 2

Author : Exforsys Inc.

Published on: 4th Jun 2007 | Last Updated on: 6th Jun 2007

Working with JavaScript DOM Objects


In this JavaScript tutorial, you will learn about DOM object - window, properties of window object, methods of window object, screen, properties of screen object, navigator, properties of navigator object, methods of navigator object, history, property of history object, methods of history object, location, properties of location object and methods of location object. DOM stands for Document Object Model. Document Object Model or DOM is a set of objects that allow programmers scripts to integrate with the browser and work with documents,windows, forms, and other components. The biggest feature that JavaScript has over basic HTML is that scripts can manipulate the web document and its contents. JavaScript can load a new page onto the browser, work with parts of the browser window and document, open new windows, and even modify text dynamically within the page. To work with the browser and documents, JavaScript uses a hierarchy of parent and child objects called the Document Object Model or DOM. These objects are organized into a tree-like structure, and represent all of the content and components of a web document. All objects in JavaScript have properties and methods associated with them. Document Object Model has properties and methods associated with it. The properties of the Document Object Model are used to describe the web page or document and the methods of the Document Object Model are used for working with parts of the web page. A detailed study of these methods and properties will be made in the coming sections. The HTML DOM is an abbreviation denoting the Document Object Model for HTML. It is a standard defined by W3C. The HTML DOM defines a standard set of objects for HTML, and a standard way to access and manipulate HTML documents. Adding new elements or modifying the contents of the elements using DOM can manipulate HTML elements. HTML DOM is a language independent platform. DOM is technically separate from JavaScript and can be accessed using other scripting languages. The following list denotes HTML DOM objects that are used for providing information about the environment of the user's system. These objects are used to provide various information about the user's environment like screen size, resolution, monitor depth, browser history, the URL, operating system, browser type, version, language and so on. The objects are:
Window Screen

Navigator History Location

Associated with each of these objects are properties and methods.


Window:

With respect to the hierarchy of JavaScript, the Window object is the top level object. TheWindow object denotes the browser window. The following list gives some of the properties and methods of the Window object.
Properties of Window Object:
closed document defaultStatus frames history length location name opener parent personalbar self status statusbar scrollbars top toolbar window innerWidth innerHeight outerWidth outerHeight pageXOffset pageYOffset screenX screenY screenLeft screenTop

Methods of Window Object:


alert() blur()

clearInterval() clearTimeout() close() confirm() createPopup() focus() moveBy() moveTo() open() print() prompt() resizeBy() resizeTo() scrollBy() scrollTo() setInterval() setTimeout()

JavaScript HTML DOM Objects


Page 2 of 2
Author : Exforsys Inc. Published on: 4th Jun 2007 | Last Updated on: 6th Jun 2007

Working with JavaScript DOM Objects


Screen:
Screen object object contains information about the display screen of the client. The

object provides information about the user's video display and color settings. JavaScript runtime engine automatically creates these settings. There are various properties associated with the Screen object.
Properties of Screen Object:
availHeight availWidth bufferDepth colorDepth deviceXDPI deviceYDPI fontSmoothingEnabled height logicalXDPI logicalYDPI pixelDepth

updateInterval width

In the next sections, the usage, syntax and explanation with examples of each of the properties of the Screen object will be discussed.
Navigator:
Navigator object is an object that is automatically created JavaScript runtime engine.

Navigator contains information about the client browser. This object is used to obtain information about the type of browser being used to access the page. Using this information, the user can be directed to a different page or carry out tasks or functions depending upon the users browser. The following list gives some of the properties and methods of the Navigator object.
Properties of Navigator Object:
appCodeName appMinorVersion appName appVersion browserLanguage cookieEnabled cpuClass onLine platform systemLanguage userAgent userLanguage

Methods of Navigator Object:


javaEnabled() taintEnabled()

History:

Like the Screen Object, the History object is also automatically created object by the JavaScript runtime engine. Browsers store the list of the users previously visited URLs. Using this list, the user navigates to previously visited web pages using the back and forward buttons in the browser. This list of URLs is called the browser's history. It's stored in the form of a list that can be accessed by JavaScript. History object can be assessed by using thewindow.history property. The History object is a part of a Window object. The following list gives some of the properties and methods of the History object.

Property of History Object:


length

Methods of History Object:


back() forward() go()

Syntax and explanation with examples of History object properties and methods are discussed in coming sections.
Location:
Location object contains information about the current URL and thus this object provides

access and control over the URL of the current window. But one important point to note in this context is that it cannot modify the URL displayed in the browser's address box and thus adds security in its usage. Since it is part of the Window object it is accessed using thewindow.location property.
Location Object is automatically created by the JavaScript runtime engine. The following

list gives some of the properties and methods of the Location object.
Properties of Location Object:
hash host hostname href pathname port protocol search

Methods of Location Object:


assign() reload() replace()

JavaScript DOM Window Object


Page 1 of 3
Author : Exforsys Inc. Published on: 21st Jun 2007 | Last Updated on: 10th Apr 2011

JavaScript DOM Window Object


In this JavaScript tutorial, you will learn about closed property and name property, defaultStatus, status, self property of JavaScript Window object
closed Property of Window Object:

The closed property of a Window object returns a Boolean variable denoting whether window has been closed or not. The closed property tells you whether or not a window opened using window.open(). Once a window is opened in JavaScript, its closed property is immediately initialized, with a value of false. When the newly opened window is closed, then the closed property of this window is set to a value of true. A programmer can study whether a window is closed or open using the closed property of a Window object. General syntax of closed property of Window Object:

windowname.closed

For example:
<html> <head> <script type="text/javascript"> function callClosed() { document.write("'ExforsysWindow' is closed!") } function callopen() { document.write("'ExforsysWindow' is not closed and is Open!") } function funcheck() { if (ExforsysWindow.closed) callClosed() else callopen() } </script> </head> <body> <script type="text/javascript"> ExforsysWindow=window.open('','','width=100,height=100') ExforsysWindow.document.write("The Window is 'ExforsysWindow'")

</script> <input value="Is the onclick="funcheck()" </body> </html>

Window

'ExforsysWindow'

type="button" Closed?" />

In the above example a new window object ExforsysWindow is opened using window.openstatement. The opening of ExforsysWindow gives a window ExforsysWindow with message displayed as

The Window is 'ExforsysWindow'

A button is created to check whether the window object ExforsysWindow is closed or open. This is done as follows: On the clicking of this button, the function funcheck() is called. The statementExforsysWindow. closed is used to check whether the current state of the windowExforsysWindow is open or closed. The value returned by this statement would be false if the window is open and if the window ExforsysWindow is closed, then the value returned by this statement would be true. If the window ExforsysWindow is closed, the value returned is true. functioncallClosed() in if block is called and the statement displayed would be: The

'ExforsysWindow' is closed!

If the window ExforsysWindow is open, then the value returned is false. The functioncallopen() in else block is called and the statement displayed would be:

'ExforsysWindow' is not closed and is Open!

name Property of Window Object:

The name property of a Window object is used for setting or returning the name of the window. The name property is a string containing the window's name.

NOTE: it is not possible to define them dynamically. General syntax of name property of Window Object:

'ExforsysWindow' is closed!

for example
<html> <head> <script type="text/javascript"> function displayWindow() { document.write("The Name of window is: " + createdWindow.name) } </script> </head> <body> <script type="text/javascript"> createdWindow=window.open('','Exforsys','width=100,height=100') </script> <input type="button" value="What's the name of 'createdWindow'?" onclick="displayWindow()" /> </body> </html>

In the above example, the program first creates a window createdWindow and then a button is displayed with text as:

What's the name of 'createdWindow'

When this button is clicked, the function displayWindow() is called. Then the message and the name of the window is displayed on the screen as:

The Name of window is: Exforsys

Using the function displayWindow() creates Window.name statement in document.writestatement. This creates Window.name and has the name of window as Exforsys stored in it.

Author : Exforsys Inc.

Published on: 21st Jun 2007 | Last Updated on: 10th Apr 2011

JavaScript DOM Window Object JavaScript Window Object defaultStatus Property: The defaultStatus property is a Read/Write property that can be set at any time and defines the default message displayed in a window's status bar. It is possible to set or return the default text in the status bar of the window using this property. The text is displayed during the loading of the page. General syntax of defaultStatus property of Window Object:

window.defaultStatus=textmessage

For example:

window.defaultStatus = "Exforsys -Example message to show defaultStatus property"

of

Status

bar

A complete program as example to understand the usage of this property:

<html> <head> <script type="text/javascript"> window.defaultStatus="Exforsys -Example bar message to show defaultStatus </head> </html>

of

Status

property" </script>

The output of the above script is

Exforsys -Example of defaultStatus property

Status

bar

message

to

show

The above message appears in the Status bar of the window as default text.
status property of Window Object:

The status property is used to set or return the text in the status bar of a window. For a window, the defaultStatus property reflects the default message displayed in the status bar at the bottom of the window. This defaultStatus property is different from status property. The status property reflects a priority or transient message in the status bar, such as the message that appears when a mouseOver event occurs over an anchor. The defaultStatus property differs to the status property. In defaultStatus property, the text is always shown in the status bar. The status property can be used to temporarily alter the status bar text. The status property can be used to temporarily change the text displayed in the status bar of a browser window. It is commonly used to set the status bar text when the mouse is moved over links in a document, so that more explanatory text, instead of a URL is displayed. General syntax of status property of Window Object:

window.status=textmessage

For example:

window.status = "Exforsys -Example of Status bar message to show status property"

The usage looks similar to that of defaultStatus property however, the status property can be set at any time. For example, the programmer can place set the status bar message on theonMouseOver event as follows:

<html> <head> <script type="text/javascript"> <A HREF="http://www.exforsys.com" onMouseOver="window.status='Exforsys

-Example

of

Status return </head> </html>

bar message to true">Place Mouse

show status property'; and See Status Bar</A> </script>

The output of the above script is

Exforsys property

-Example

of

Status

bar

message

to

show

status

The above message appears in the Status bar of the window only when the user places the mouse over the link displayed as Place Mouse and See Status Bar.

JavaScript Window Object Self Property


Page 3 of 3
Author : Exforsys Inc. Published on: 21st Jun 2007 | Last Updated on: 10th Apr 2011

JavaScript DOM Window Object JavaScript Window Object defaultStatus Property: The defaultStatus property is a Read/Write property that can be set at any time and defines the default message displayed in a window's status bar. It is possible to set or return the default text in the status bar of the window using this property. The text is displayed during the loading of the page.

window.self

An example to understand this concept:

<html> <head> <script type="text/javascript"> function checkwindow() { if (window.top!=window.self) { document.write("The window is not current window!!!!!") }

else { document.write("The window is current window!!!!!") } } </script> </head> <body> <input type="button" onclick="checkwindow()" value="Check the Window by clicking Here"> </body> </html>

In the above example a button is displayed with message

Check the Window by clicking Here

When this button is clicked, the function checkwindow() is called and the Current Window status is checked. If the Window top is equal to window.self (which has the reference to the current window) then else statement gets fired and the message:

The window is current window!!!!!

is displayed. If the Window top is not equal to window.self (which has the reference to the current window) then if statement gets fired and the message:

The window is not current window!!!!!

is displayed.

JavaScript Windows Object Properties Part I


Author : Exforsys Inc. Published on: 8th Aug 2007

JavaScript Windows Object Properties Part I

In this JavaScript tutorial, you will learn about Windows Object properties namely personalbar, statusbar, scrollbar, toolbar property of Window object, pageXOffset, pageYOffset, innerwidth, innerheight, outerwidth and outerheight.
personalbar Property of Window Object:

The personalbar property of a Window Object relates to the browser's personal or directory bars. This is the region where the user has easy access to certain bookmarks. The personalbarproperty has the default property set as true, meaning visible, and can also be set to false, meaning hidden, as per the programmer's requirement. The personalbar Property of aWindow Object is used to show or hide the browser's personal or directory bars as per the needs of the user. NOTE: In order to set the value of the personalbar visible property, the programmer must have the UniversalBrowserWrite privilege. General syntax of personalbar property of Window Object:
window.personalbar[.visible = false]

The default value is true. Example for personalbar of the Window Object set as hidden.
self.personalbar.visible=false;

scrollbar Property of Window Object:

The scrollbar Property of a Window Object relates to the browser's vertical and horizontal scrollbars. The scrollbars property can be set to visible or hidden. The default value is true, meaning visible, and this can be set to false, meaning hidden, as per the programmer's requirement. Thus, the scrollbar Property of a Window Object is used to Set the scrollbar as visible or hidden, based on the user's needs. NOTE: To set the value of the scrollbar visible property, the programmer must have theUniversalBrowserWrite privilege. General syntax of scrollbar property of Window Object:
window.scrollbars[.visible = false]

The default value is true. For example the statement below sets the scrollbar of the window as hidden.
self.scrollbar.visible=false;

statusbar Property of Window Object:

The statusbar property of a Window Object relates to the browser's statusbar. This is the region containing the security indicator, browser status, and so on. The statusbar property has the default property set as true, meaning visible and can also be set to false, meaning hidden, as per the programmer's requirement. Thus, the statusbar Property of a Window Object is used to set the browsers statusbar to visible or hidden, depending on the user's needs. NOTE: To set the value of the statusbar visible property, the programmer must have theUniversalBrowserWrite privilege. General syntax of statusbar property of Window Object: The general syntax for using this statusbar property of Window object is as follows:
window.statusbar[.visible = false]

The default value is true. For example the statement below


window.statusbar.visible=false;

would set the statusbar of the window as hidden.


toolbar Property of Window Object:

The toolbar property of Window Object relates to the browser's toolbar. The toolbar has items usually like the navigation buttons such as Back, Forward, Reload, Home, and so on. The toolbar property has the default property set as true which means visible and can be set to false which means hidden as per the programmer's requirement. Thus this property namely the toolbar Property of Window Object is used to set visible or hidden the browser's toolbar as per user's needs. But one important point to note in this toolbar property is that the programmer must set this property before the window is opened and also it is essential that the programmer must have UniversalBrowserWrite privilege for doing this. General syntax of toolbar property of Window Object:
window.toolbar[.visible = false]

The default value is true. For example the statement below sets the toolbar of the window as hidden.
window.toolbar.visible=false;

screenLeft, screenTop of Window object with syntax.


pageXOffset:

The pageXOffset property sets or returns the X position of the current page in relation to the upper left corner of a window's display area. General syntax of pageXOffset property of Window Object:
window.pageXOffset

pageYOffset:

The pageYOffset property sets or returns the Y position of the current page in relation to the upper left corner of a window's display area. General syntax of pageYOffset property of Window Object:
window.pageYOffset

innerwidth:

The innerwidth property sets or returns the inner width of a window. The innerwidthproperty of the Window object is a read or write property that specifies the width in pixels. This width includes only the window's content area and does not include the toolbar, scrollbars and so on. General syntax of innerwidth property of Window Object:
window.innerwidth=pixels

innerheight:

The innerheight property sets or returns the inner height of a window. The innerheightproperty of the Window object is a read or write property that specifies the height in pixels. This height includes only the window's content area and does not include the toolbar, scrollbars and so on. General syntax of innerheight property of Window Object:
window.innerheight=pixels

outerwidth:

The outerwidth property sets or returns the outer width of a window. The outerwidthproperty of the Window object is a read or write property that specifies the

total width in pixels. This width includes not only the window's content area but also includes the toolbar, scrollbars and so on. General syntax of outerwidth property of Window Object:
window.outerwidth=pixels

outerheight:

The outerheight property sets or returns the outer height of a window. The outerheightproperty of the Window object is a read or write property that specifies the total height in pixels. This height includes not only the window's content area but also includes the toolbar, scrollbars and so on. General syntax of outerheight property of Window Object:
window.outerheight=pixels

An example to illustrate the use of the above outerheight and outerwidth properties of Window object:

<html> <body> <script type="text/javascript"> exforsysWindow=window.open('','') exforsysWindow.outerheight="300" exforsysWindow.outerwidth="200" exforsysWindow.document.write("The Window 'exforsysWindow' has outer height as: " + window.outerheight) </script> </body> </html>

In the above example, window exforsysWindow is set with outerheight and outerwidth as 300 and 200 respectively and the message
The Window 'exforsysWindow' has outer height as: 300

is displayed as window.outerheight returns the outerheight of window.

JavaScript Document Object Methods Part I

Author : Exforsys Inc.

Published on: 5th Aug 2007

JavaScript Document Object Methods - Part I


In this JavaScript tutorial, you will learn about methods of document object along with syntax and examples. This section covers captureEvents, open, close, getElementById, getElementsByName methods with explanations for each method.
Methods of document Object: captureEvents:

The captureEvents method instructs the document to capture and handle all events of a particular type. The general syntax for using the captureEvents method of document object is as follows:
document.captureEvents(eventType)

The list of eventType in an earlier section of this tutorial called Event Handler in JavaScript. For example:
document.captureEvents(Event.MOUSEMOVE);

In the above, the MouseMove event is captured. When the MouseMove event occurs, then the event handler function defined in document.onMouseMove executes.
open:

The output stream is opened by document.open() method. This is opened to collect the output of subsequent document.write() or document.writeln methods. The general syntax for using the open method of document object is as follows:
document.open(mimetype,replace)

In the above syntax, both mimetype and replace are optional. The mimetype refers to the type of document the programmer wants to write to. The default value of this is "text/html". When replace is mentioned, it causes the history entry for the new document to inherit the history entry from the parent document.
close:

The close method of a document object is used for closing the output stream previously opened with the document.open method. This also collects and displays the collected data in this process.

The output stream is opened by document.open() method. This is opened to collect the output of subsequent document.write() or document.writeln methods. Once all the writes are performed, the document.close() method causes any output written to the output stream to be displayed in the document opened in a secondary window. The general syntax for using the close method of document object is as follows:
document.close()

Let us see an example to understand the concept of open and close method in detail:

<html> <head> <script type="text/javascript"> function exfor() { opendocu=document.open("text/html","replace"); test="<html><body>Welcome to Exforsys!</body></html>"; exfor.write(test); exfor.close(); </script> </head> <body> Here!" </body> </html>

var var

<input type="button" onclick="exfor()">

value="Click

The output of the above program is a button with message


Click Here!

and on clicking this the output appears in a new document exfor as


Welcome to Exforsys!

The document exfor closes after this statement exfor.close().


getElementById:

In the getElementById method, the object id is specified in argument getElementById() and this returns the reference to the first object with the specified ID. The general syntax for using the getElementById method of document object is as follows:

document.getElementById(id)

for example:

<html> <head> <script type="text/javascript"> ShiftDoll() { = document.getElementById('doll').style; dollvar.left = 500; </script> </head> <body> onMouseDown="ShiftDoll()">Click for Dancing Doll</a></p> src="doll.jpg" id="doll" style="position:absolute;width="520" </body> </html>

function dollvar }

<p><a

href="#" <p><img

height="400"></p>

The output of the above program is:


Click for Dancing Doll

with the doll.jpg displays When the above link is clicked, the doll.jpg displays with position shifted to the right. The statement document.getElementById('doll') gives reference to the object with id as doll and the attributes are applied to that object.
getElementsByName:

The getElementById method was used for returning the reference to the first object with the specified ID. The programmer can also get a collection of objects with the object name given in argument by using the method getElementsByName. The getElementsByName() method returns a collection of objects with the specified Name given in argument. This method returns an array of elements with a name attribute whose value matches that of the parameter given. The general syntax for using the getElementsByName method of a document object is as follows:
document.getElementsByName(name)

for example:

<html> <head> <script type="text/javascript"> function Exforinput() { test=document.getElementsByName("Exforsys"); alert(test.length); </script> </head> <body> <input name="Exforsys" type="text" size="30" /><br /> <input name="Exforsys" type="text" size="30" /><br /> <input type="button" onclick="Exforinput()" value="Click to see the number of input box" /> </body> </html>

var }

The output of the above program is

and a button with the message:


Click to see the number of input box

and when this is clicked, the output appears as:


2

The statement document.getElementsByName("Exforsys") returns the object with object name Exforsys. There are two input box as objects with name Exforsys, so the result displayed is 2.

JavaScript Document Object Methods Part II

In this JavaScript tutorial, you will learn about document object methods getElementsByTagName, getSelection, handleEvent, releaseEvents, routeEvent, write, writeln along with syntax, examples and brief explanation.
getElementsByTagName:

The the getElementsTagName() method returns a collection of objects with the specifiedTagNAME given in argument. The programmer can enter an asterisk ("*") as the parameter to retrieve a list of all elements within the document. The general syntax for using the getElementsByName method of document object is as follows:
document.getElementsByTagName(tagname)

for example:

<html> <head> <script type="text/javascript"> function Exforinput() { test=document.getElementsByTagName("input"); alert(test.length); } </head> <body> <input name="Exforsys" type="text" size="30" /><br /> <input name="Exforsys" type="text" size="30" /><br /> <input type="button" onclick="Exforinput()" value="Click to see the number of tag with input as tag name" /> </body> </html>

var

</script>

The output of the above program is

and a button with message

Click to see the number of tag with input as tag name

When this button is clicked, the output appears as:


3

The statement document.getElementsByTagName("input") returns the object with tag name as Input. There are three elements with input as tag name (as seen in the program) so the displayed result is 3.
getSelection:

A programmer can return the contents of a selected text in the current document by using the getSelection()method. The general syntax for using the getSelection method of document object is as follows:
document.getSelection( )

for example:

<html> <head> <script type="text/javascript"> </script> </head> <body> <INPUT TYPE="BUTTON" VALUE="Selected Highlighted Text is Displayed!!" onClick="alert('You have selected the text:\n'+document.getSelection());"> </body> </html>

In the above, when the button is pressed, the message:


Selected Highlighted Text is Displayed!!

The selected text in the current document displays as:


You have selected the text: xxxx

The document.getSelection() method returns the contents of a selected text in the current document.
handleEvent:

For the handleEvent method, the event is specified as a parameter and the method calls the corresponding handler for the specified event. When a call of the handleEvent method is

made, a search for the corresponding available set of event handler functions is performed. This is then passed to the event for an appropriately mapped handler function. The general syntax for using the handleEvent method of document object is as follows:
document.handleEvent(event)

releaseEvents:

The releaseEvents method is used for indicating the events that are no longer needed. This is captured by the receiving Document object. The functionality is similar to that ofwindow.releaseEvents() method. The general syntax for using the releaseEvents method of document object is as follows:
document.releaseEvents(eventType)

In the above, any event of the eventType mentioned in a parameter is released. This is passed down to the Document Object for capturing.
routeEvent:

The routeEvent() method passes all previously captured events of the event type passed through their normal event processes. The general syntax for using the routeEvent method of document object is as follows:
document.routeEvent(event)

write:

If a programmer wishes to write HTML expressions to the specified document, then it can be done using write method of document object. The general syntax for using the write method of document object is as follows:
document.write(exp1,exp2,....)

In the above syntax, it is evident that the programmer can write multiple expressions, each separated by commas, and placed in the order of their occurrence. The values given in arguments are converted to a string value, appended to the content of the document window and then interpreted as HTML. This technique can be widely used to create dynamically changing pages. An example to understand the write method in detail:

<html> <body> <script type="text/javascript"> document.write("Welcome to Exforsys!") </script> </body> </html>

The above example would give output as below


Welcome to Exforsys!

A simple example where more than one expression using document.write method is written:

<html> <body> <script type="text/javascript"> document.write("Welcome All","To Exforsys!","<p style='color:red;'>Training Division</p>") </script> </body> </html>

The output of the above program is


Welcome All To Exforsys! Training Division

writeln:

The functionality of writeln method of document object is similar to that of write method but here in writeln method in addition a new line character is written after each expression. Thewriteln method places a carriage return after the written value of each expression. The general syntax for using the writeln method of document object is as follows:
document.writeln(exp1,exp2,....)

for example:

<html> <body> <script type="text/javascript"> document.writeln("Welcome to Exforsys!") </script> </body> </html>

The above example would give output as below


Welcome to Exforsys!

In the above output, a carriage is placed after the display of output is written.

JavaScript History Object Properties and Methods


In this JavaScript tutorial, you will learn about history object properties and methods, length, current, next, previous properties, back(), forward() and go() methods along with syntax and examples. The history property has the return value as history object, which is an array of history items having details of the URL's visited from within that window. Also, note that the History object is a JavaScript object and not an HTML DOM object. General syntax of history property of Window Object:
window.history

The JavaScript runtime engine automatically creates this object. An introduction on the history object and the properties and methods associated with it was covered in an earlier section. This section studies in detail the property and methods of the history object with an example for each.
Property of History Object: length:

The length property of the history object returns the number of elements in the history list. General syntax of length property of history Object:
history.length

An example to understand the length property of history object:

<html> <body>

<script type="text/javascript"> var ex = history.length; document.write("The number of pages visited before this page is" +ex+ " pages!!!.") </script> </body> </html>

The output of the above program is


The number of pages visited before this page is 5 pages!!!

This means that there are 5 entries in the history list and denotes the number of pages visited before visiting the current page.
current:

This property contains the complete URL of the current History entry. General syntax of current property of history Object:
history.current

next:

The next property of history object contains the complete URL of the next element in the History list. This functionality or the URL visited is the same as pressing the forward button or menu. General syntax of next property of history Object:
history.next

previous:

The previous property of history object contains the complete URL of the previous element in the History list. This functionality or the URL visited is the same as pressing the back button or menu. General syntax of previous property of history Object:
history.previous

Methods of History Object: back():

There may be scenarios where the programmer wishes to load the previous URL present in the history list. In this case, the programmer can make use of the back() method of the

history object. The back() method of the history object takes the user to the previous page. The functionality results in the same as pressing the back button of the browser. General syntax of back method of history Object:
history.back()

An example to understand the back method of history object:

<html> <head> <script type="text/javascript"> funback() { window.history.back() </script> </head> <body> to go </body> </html>

function

<input type="button" value="Press the Button to Previous Page!!!" onclick="funback()" />

The output of the above program is a button with message as


Press the Button to go to Previous Page!!!

When this button is pressed, the control is navigated to the previous page.
forward():

The forward() method of the history object loads the next URL in the History list. The functionality results are the same as pressing the forward button of the browser. General syntax of forward method of history Object:
history.forward()

An example to understand the forward method of history object in brief:

<html> <head> <script type="text/javascript"> funfor() { window.history.forward()

function

} </script> </head> <body> to go </body> </html>

<input type="button" value="Press the to Next Page!!!" onclick="funfor()" />

Button

The output of the above program is a button with message as


Press the Button to go to Next Page!!!

When this button is pressed, the control is navigated to next page (to the next URL) in the history list.
go():

If the programmer wishes to load a specified URL from the History list, then the go method of history object can be used. General syntax of go method of history Object:
history.go(number)

or
history.go(URL)

The back method seen above is the same as history.go(-1) in terms of go method of history object. The forward method seen above is the same as history.go(1) for example:

<html> <head> <script type="text/javascript"> function funfor() { window.history.go(1) } </script> </head> <body> type="button" value="Press the Button to go Next Page!!!" onclick="funfor()" /> </body>

<input to

</html>

The output of the above program loads the next page in the history list.

JavaScript Location Object Properties


Page 1 of 3
Author : Exforsys Inc. Published on: 13th Jun 2007

JavaScript Location Object Properties


In this JavaScript Tutorial you will learn about Properties of Location Object - hash, host, hostname, href, pathname, port, protocol and search property The Location object contains information about the current URL. This representation is a string that denotes the different portions of the URL as below:
<protocol>//<host>[:<port>]/<pathname>[<hash>][<search>]

The location object has a number of properties and methods in it. The usage, syntax and explanation with examples of each of the properties and methods of the Location object are explained in this section and the following sections.
Properties of Location Object: hash: The hash property of location object starts with the symbol hash denoted as #, specifying an anchor name in an URL. The hash property is also used for returning the URL.

General syntax of hash property of location Object:


location.hash = anchorname

for example

<html> <body> <script type="text/javascript"> document.write(location.hash); </script> </body> </html>

Suppose the current URL is: http://xforsys.com/example.htm#test5 Then the output of the above program is

#test5

The location.hash in document.write takes the symbol starting from hash in the current URL and displays it giving the output as #test5
host:

The property of location objects are used for setting or returning the hostname and port number of the current URL. General syntax of host property of location Object:
location.host

for example The location.host in document.write takes the hostname in the current URL and displays it with the output exforsys.com

<html> <body> <script type="text/javascript"> document.write(location.host); </script> </body> </html>

Suppose the current URL is: http://xforsys.com/example.htm#test5 Then the output of the above program is
xforsys.com

The location.host in document.write takes the hostname in the current URL and displays it with the output exforsys.com

Properties: hostname, href and pathname


Page 2 of 3
Author : Exforsys Inc. Published on: 13th Jun 2007

JavaScript Location Object Properties


hostname:

This has a similar function as hot property which was previously discussed. The only difference between hostname property of location object and hot property is the hostname property of location object is used for setting or returning the hostname only of the current URL. General syntax of hostname property of location Object:
location.hostname

for example

<html> <body> <script type="text/javascript"> document.write(location.hostname); </script> </body> </html>

Suppose the current URL is: http://xforsys.com/example.htm#test5 Then the output of the above program is
xforsys.com

The location.hostname in document.write takes the hostname in the current URL and displays the output exforsys.com
href:

If a programmer wants to set or return the entire URL, then the href property of location object can be used. General syntax of href property of location Object:
location.href=URL

An example

<html> <body> <script type="text/javascript">

document.write(location.href); </script> </body> </html>

Suppose the current URL is: http://xforsys.com/example.htm#test5 Then the output of the above program is
http://xforsys.com/example.htm#test5

The location.href in document.write takes the entire URL in the current URL and displays the output as displayed above.
pathname

As the name of this property suggests, the pathname property of location object is used for setting or returning the path of the current URL. This pathname specifies the path for accessing the particular URL or resource. General syntax of pathname property of location Object:
location.pathname=path

An example

<html> <body> <script type="text/javascript"> document.write(location.pathname); </script> </body> </html>

Suppose the current URL is: http://xforsys.com/example.htm#test5 Then the output of the above program is
/xforsys.com/example.htm

The location.pathname in document.write takes the pathname specified in the current URL and displays it with the output as displayed above.

JavaScript Window Object Timeout Methods


In this JavaScript tutorial, you will learn about setTimeout(), clearTimeout() and open() methods of window object along with syntax, usage and examples for each method.

setTimeout():

The setInterval() method of Window object is used to call a function or evaluate an expression at specified intervals. The setTimeout() method of a window object performs in a similar manner. In contrast to the setInterval() method, the setTimeout() method of window object is used to call a function or evaluate an expression after a specified number of milliseconds. The setTimeout() method helps schedule the expression or function for the time specified by the user. The function given in arguments is called or the expression is evaluated after a specified number of milliseconds given as argument in the setTimeout() method of window object. General Syntax of the setTimeout() method of window object:
window.setTimeout(expression/function, milliseconds)

setTimeout() example:

<html> <head> <script type="text/javascript"> function exf() { exforsys.close() } </script> </head> <body> exforsys = window.open('','','width=100,height=200') exforsys.document.write("Example on setTimeout() method!") exforsys.setTimeout('exf()', 7000) </body> </html>

The output of the above program is a window exforsys. This opens with the displayed message:
Example on setTimeout() method!

The window exforsys is closed after seven seconds. The setTimeout() method is applied to the window exforsys with a parameter passed as function exf(). This performs the action of closing the window exforsys by the statement exforsys.close(). This is performed after 7 seconds because the second parameter passed to the setTimeout() method is 7000 milliseconds.

clearTimeout():

If a user wishes to cancel the timeout set in the setTimeout() method, he or she can use theclearTimeout() method of window object. The clearTimeout() method of a window object is used to cancel a timeout set with the setTimeout() method. General Syntax of the clearTimeout() method of window object:
window.clearTimeout(timeoutID)

The timeoutID given as argument in the clearTimeout() method is the ID that is declared or set during the setTimeout() method. An example to understand the usage of the clearTimeout() method of window object:

<html> <head> <script type="text/javascript"> exforsys = setTimeout ("window.location='http://exforsys.com/test.html'", 5000); </script> </head> </html>

The above example sends the user to a new page test.html in exforsys.com after 5 seconds. The setTimeout method calls the page after 5000 milliseconds or 5 seconds. The ID of thesetTimeout method is set to exforsys. Using the clearTimeout() method of window object and the previous example to cancel the timeout set in the setTimeout() method:

<html> <head> <script type="text/javascript"> clearTimeout (exforsys); </script> </head> </html>

In the above example, the timeout created in the previous example is canceled by passing the corresponding ID exforsys set in setTimeout() method as argument to the clearTimeout()method of window object.
open():

A new browser window opens using the open() method of a window object.

General Syntax of the open() method of window object:


window.open(URL,name,specs,replace)

In the above, all the fields (URL, name, specs, replace) given in arguments are optional. The URL given in the argument of the open() method of window object specifies the URL of the page to open. If the user does not mention any URL, then an empty window will be created and opened. The name field specified in the open() method of window object is a string denoting the name of the new window. This can be used as the target attribute. The most commonly used values are:
_blank This is a default value that denotes that the URL is loaded into a new window. _parent This denotes that the URL is loaded into the parent frame. _self This denotes and makes the URL replace the current page. _top This denotes that the URL replaces any framesets that may be loaded. name This denotes the name of the window.

The specs field specified as argument in the open() method of window object can have numerous items in it, each separated with commas. This is a string denoting the details of the features or attributes that are to be used for the new window. The features have a value as either yes or no and, in some cases, as 1 or 0. Any feature can be turned on, as the user requires or needs to use it. Some of the features or attributes that are most commonly used are:
channelmode directories dependent fullscreen screenX screenY height left location menubar resizable alwaysLowered alwaysRaised scrollbars status

titlebar toolbar top width innerHeight innerWidth outerHeight outerWidth hotkeys

The usage, syntax and explanation of the above features will be described in the next section in detail.

JavaScript Window Object Open Method


In this JavaScript tutorial, you will learn about JavaScript Window Object Open Method, features of window object open method - channelmode, directories, dependent, fullscreen, screenX, screenY, height, left, location, menubar, resizable, alwaysLowered, alwaysRaised
channelmode:

Syntax: channelmode=yes|no|1|0 The channelmode is used to denote whether the user wants to display the window in theater mode or not. The default setting of this feature is NO. The user can set channelmode value toYES which would then display the window in theater mode. This is a very important feature of Window Object of JavaScript .
directories:

Syntax: directories=yes|no|1|0 directories are used to specify whether the user wants to add directory buttons or not. The default value of the directories feature is YES.
dependent:

Syntax: dependent=yes|no|1|0 If the value of the dependent feature is set to yes then it creates the new window as a child of the current window.
fullscreen:

Syntax: fullscreen=yes|no|1|0 The feature fullscreen is used to specify whether or not the user wants to display the browser in full-screen mode. The default setting of this feature is NO. User can turn on thefullscreen feature, by setting its value to YES, displaying the browser in full-screen mode.

NOTE: This feature requires that a window in full-screen mode must also be in theater mode. If the value of fullscreen is set to yes then the value of the channelmode feature must also be set to yes.
screenX:

Syntax: screenX=pixels When screenX feature is used, the new window created and opened displays from the left side of the screen at a distance equal to the number of pixels specified. The value in this feature is given in pixels.
screenY:

Syntax: screenY=pixels When sreenY feature is used, the new window created and opened displays from the top of the screen at a distance equal to the number of pixels specified. The value in this feature is given in pixels.
height:

Syntax: height=pixels height feature is used to specify the window height. The minimum value that must be specified for the height attribute is 100. The value for this feature is given in pixels.
left:

Syntax: left=pixels left feature is used to specify the left position of the window. The value for this feature is given in pixels.
top:

Syntax: top=pixels top feature is used to specify the top position of the window. The value for this feature is given in pixels.
width:

Syntax: width=pixels width feature is used to specify the window width. The minimum value that must be specified for the width attribute is 100. The value for this feature is given in pixels.
location:

Syntax: location=yes|no|1|0 The location is used to denote whether or not the address field should be displayed. The

default value of this location feature is YES, displaying the address field. If the user sets the value to NO in the location feature then the address field is not displayed.
menubar:

Syntax: menubar=yes|no|1|0 The menubar is used to denote whether or not the menu bar should be displayed. The default value of this menubar feature is yes, displaying the menu bar. If the value of the menubarfeature is set to NO by the user, then the menu bar is not displayed.
resizable:

Syntax: resizable=yes|no|1|0 If the user wants to specify whether or not the window should be resizable then the resizable feature can be used. The default value of the resizable feature is yes, making the window resizable by default. If the user does not want the window to be resized then the value must be set to NO by the user.
alwaysLowered:

Syntax: alwaysLowered=yes|no|1|0 When the value of the attribute alwaysLowered is set to YES, it creates a window that always floats below other windows.
alwaysRaised:

Syntax: alwaysRaised=yes|no|1|0 When the value of the attribute alwaysRaised is set to YES, it creates a window that always floats above other windows

JavaScript Window Object Open Method Part 2


In this JavaScript tutorial, you will learn about JavaScript Window Object Open Method, features of window object open method - scrollbars, status, titlebar, toolbar, top, width, innerHeight, innerWidth, outerHeight, outerWidth and hotkeys
scrollbars:

Syntax: scrollbars=yes|no|1|0 The scrollbar feature denotes whether or not the scroll bars should be displayed. The default value of the scrollbars feature is YES, displaying the scroll bars. If the value of the scrollbars feature is set to NO by the user, then the scroll bars are not displayed.

status:

Syntax: status=yes|no|1|0 This allows the user the provision of adding the status bar or not. The default value to the status feature is YES, which adds the status bar. If the user sets the value of the statusfeature to NO, then the status bar is not added.
titlebar:

Syntax: titlebar=yes|no|1|0 JavaScript provides the option to add the status bar or not and the same option is provided for the visibility of the title bar. The titlebar feature allows the user to denote whether or not the title bar should be displayed. The default value to the titlebar feature is YES, displaying the title bar. If the value of the titlebar feature is set to NO by the user then the title bar is not displayed. NOTE: this is called only if the application called is an HTML application, otherwise, calling the titlebar feature is not taken into account.
toolbar:

Syntax: toolbar=yes|no|1|0 Like the scroll bar, the toolbar is used to denote whether the browsers tool bars should be displayed or not. The default value of the toolbar feature is YES, displaying the tool bar. If the value of the toolbar feature is set to NO by the user, then the tool bar is not displayed.
innerHeight:

Syntax: innerHeight=pixels This feature is used to specify the inner height of the window. The value for this feature is given in pixels.
innerWidth:

Syntax: innerWidth=pixels This feature is used to specify the inner width of the window. The value for this feature is given in pixels.
outerHeight:

Syntax: outerHeight=pixels This feature is used to specify the outer height of the window. The value for this feature is given in pixels.

outerWidth:

Syntax: outerWidth=pixels This feature is used to specify the outer width of the window. The value for this feature is given in pixels.
hotkeys: Syntax: hotkeys=yes|no|1|0 If the user sets the value of the hotkeys feature to NO, then the windows usage or function of hotkeys is disabled. replace:

Another optional attribute that is passed to the open() method of window object is the replace method. This attribute is mentioned in the syntax of the open() method in above description. This specifies the way the entry in the history list is handled. This method is used to specify whether the URL has to create a new entry in the history list or replace the current entry in the history list. The replace attribute can take the values of true or false. The truevalue specifies that the URL replaces the current document in the history list. The false value specifies that the URL creates a new entry in the history list. Let us see an example to understand the usage of open() method of window object in brief:

<html> <head> <script type="text/javascript"> function exforsys() { window.open("http://exforsys.com","_blank","toolbar=yes, location=yes, directories=no, status=yes, menubar=no, scrollbars=yes, resizable=no, width=300, height=500") } script> head> <body> <form> <input type="button" value="Click Here to Display Window!!!" onclick="exforsys()"> form> body> html>

The output of the above example is a button with the message:

When this button is clicked, the URL http://exforsys.com displays in a new window. This is because the first argument mentioned is http://exforsys.com and the second argument mentioned is _blank, denoting that the URL loads into a new window. The URL displayed in the new window has its window width as 300 and its height as 500. The value of widthand height are mentioned as 300 pixels and 500 pixels respectively. The windows displayed have the scroll bars, tool bar, status bar displayed because the value of scrollbars, status and toolbar is set to yes, making these visible in the window. The window displayed is not resizable and is fixed in size because the resizable feature is set to no. The value of themenubar is set to no, displaying no menu bars in the final output window.

JavaScript Object Oriented Features


In this JavaScript tutorial you will learn about JavaScript Object Oriented Features, object type, object instantiation, using object properties, using object methods and achieving object instantiation. Object-oriented capabilities make any language or application powerful. This section outlines the object oriented features supported by JavaScript and how to use them in programming process. JavaScript is not a complete programming language but, rather, it is a scripting language. There are some object-oriented features that are not supported by JavaScript. JavaScript does not support the features of inheritance, information hiding, encapsulation and classification that are supported by other object-oriented programming languages. Lack of information hiding and lack of encapsulation features in JavaScript cause the methods and properties to only be accessible directly in JavaScript. Similarly, JavaScript does not support

the inheritance or classification features. These features cannot be used for developing hierarchy of object types. The concepts of object reusability and modular approach concept are used by JavaScript in a very limited way. JavaScript can be reused in the Internet only by using SRC attribute (discussed in the SCRIPT tag in an earlier section of this tutorial). Polymorphism, another important feature of Object-oriented programming, is supported by JavaScript using arguments array in function definition, which will be explained in detail in later sections. The lack of these features does not reduce the capabilities of JavaScript in any way. JavaScript has many other compensating features, making it the best scripting language for use in web and server side programming.
Object based Features Supported by JavaScript:

JavaScript supports various features related to object based language and JavaScript is sometimes referred to as an object-based programming language. The vital features which JavaScript supports related to object based are:
Object Type:

JavaScript supports the development of Object types and in this context JavaScript supports both predefined and user-defined objects. It is possible to assign objects of any type to any variable. It is possible to instantiate the defined object types to create object instances in JavaScript, which is a very powerful feature of Object based language. In this context, the limitation of Object type in JavaScript does not permit users to carry out type enforcement on Object types.
Object Instantiation:

To carry out the process of creating specific object instances available in JavaScript, users can make use of a new operator. These two powerful, object-based features supported by JavaScript described above make this an object model language. In JavaScript, the object types are defined by properties and methods. Properties of Objects are used to access the data values contained in an object. Users can make use of the properties of JavaScript objects for editing as well as reading, depending on whether or not the objects nature is read only. If the user wants to carry out functions on the object, this is achieved by using methods that make use of the objects properties. Using object based features (object properties and methods), in JavaScript:

To use Object Properties:

Syntax for making use of JavaScript object properties is by using the object name followed by dot and then the property name:

objectname.propertyname

To use Object Methods:

Syntax for making use of JavaScript object methods follows the same process as objectproperties with the difference being that the property name is replaced by the method name and any arguments. To access object methods in JavaScript, the programmer uses theobject name followed by dot and then the method name with any arguments:

objectname.methodname(arguments)

How to achieve Object instantiation:

The new operator available feature is used to achieve Object instantiation. General syntax for new operator for creating objects in JavaScript is as follows:

variablename=new objecttype(arguments)

In the above syntax, new refers to keyword and the objecttype(arguments) refer to the constructor. The number of arguments taken by constructors varies from no arguments to one or more than one, depending on the type of object. An example of object type with constructor taking no arguments:

CD=new Date() Date refers to the predefined JavaScript object type. The Date() constructor does not

take any parameter and the above statement stores the current date and time to the variable CD. It is also possible to use the same object type. For example, the Date() constructer taking a specified date as the parameter and creating object instances for that specified date.

CDD=newDate(96,3,3)

In this example, instances are created for the specified Date March 3,1996.

Properties : port, protocol and search


Page 3 of 3
Author : Exforsys Inc. Published on: 13th Jun 2007

JavaScript Location Object Properties


port:

The hostname property for returning the hostname alone of the current URL is similar to the port property. The port property of location object is used for setting or returning the port number of the current URL. This port number refers to the communications port used by the server. General syntax of port property of location Object:
location.port=portnumber

for example

<html> <body> <script type="text/javascript"> document.write(location.port); </script>

</body> </html>

Then the output of the above program is


24

The number 24 displayed above specifies the port number of the current URL.
protocol:

As the name of this property suggests, the protocol property of location object is used for setting or returning the protocol of the current URL. General syntax of protocol property of location Object:
location.protocol=path

for example

<html> <body> <script type="text/javascript"> document.write(location.protocol); </script> </body> </html>

Suppose the current URL is: http://xforsys.com/example.htm#test5 Then the output of the above program is
http:

The location.protocol in document.write takes the protocol specified in the current URL which is http: and displays it as shown above.
search:

The search property of the location object is a string and it is used to set and return the value from the current URL starting from question mark(?) General syntax of search property of location Object:
location.search=path

In the above, the path is taken from question mark(?) of the current URL.

for example

<html> <body> <script type="text/javascript"> document.write(location.search); </script> </body> </html>

Suppose the current URL is: http://xforsys.com/example.asp?filename=test10 Then the output of the above program is
?filename=test10

The location.search in document.write takes the symbol starting from ? in the current URL and displays it giving the output as ?filename=test10

JavaScript Location Object


Page 1 of 2
Author : Exforsys Inc. Published on: 4th Jul 2007

JavaScript Location Object


In this JavaScript tutorial, you will learn about JavaScript Location Object - assign(), reload(), replace(), JavaScript Window Object Methods viz alert(), blur(), setInterval() and clearInterval().

Methods of Location Object


assign():

The assign method of location object is used for loading a new document. General syntax of assign method of location Object:
location.assign(URL)

for example

<html> <head> <script type="text/javascript">

function

test() { window.location.assign("http://www.exforsys.com") </script> </head> <body> Loading New </body>

<input type="button" value="Click Document" onclick="test()" /> </html>

Here

For

The output of the above program is a button with message as


Click Here For Loading New Document

When this button is clicked, the site exforsys.com loads as a document.


reload():

This method of location object is used for reloading the current document. The currently displayed page in the window that owns the location object is reloaded. This means that the document that owns the Location object is to be reloaded. General syntax of reload method of location Object:
location.reload()

for example

<html> <head> <script type="text/javascript"> test() { window.location.reload() </script> </head> <body> <input type="button" value="Click Here For ReLoading page" onclick="test()" /> </body> </html>

function

The output of the above program is a button with message as

Click Here For ReLoading Page

When this button is clicked, the current document reloads.


replace():

As the name implies, the replace() method of location object replaces the current document with a new one. The current History entry is replaced with the URL specified in the replace method. NOTE: The programmer must know that after the replace method is called he or she cannot go back to the previous URL by using the back button. General syntax of replace method of location Object:
location.replace(URL)

The URL specified in argument is the new URL. for example

<html> <head> <script type="text/javascript"> function exareplace() { window.location.replace("http://www.exforsys.com") } </script> </head> <body> Replace" </body> </html>

<input type="button" onclick="exareplace()" />

value="Click

Here

to

The output of the above program is a button with message as


Click Here to Replace!!!

When this button is clicked, the http://www.exforsys.com as document.

current

document

is

replaced

with

JavaScript Window Object Open Method Part 2


In this JavaScript tutorial, you will learn about JavaScript Window Object Open Method, features of window object open method - scrollbars, status, titlebar, toolbar, top, width, innerHeight, innerWidth, outerHeight, outerWidth and hotkeys

scrollbars:

Syntax: scrollbars=yes|no|1|0 The scrollbar feature denotes whether or not the scroll bars should be displayed. The default value of the scrollbars feature is YES, displaying the scroll bars. If the value of the scrollbars feature is set to NO by the user, then the scroll bars are not displayed.
status:

Syntax: status=yes|no|1|0 This allows the user the provision of adding the status bar or not. The default value to the status feature is YES, which adds the status bar. If the user sets the value of the statusfeature to NO, then the status bar is not added.
titlebar:

Syntax: titlebar=yes|no|1|0 JavaScript provides the option to add the status bar or not and the same option is provided for the visibility of the title bar. The titlebar feature allows the user to denote whether or not the title bar should be displayed. The default value to the titlebar feature is YES, displaying the title bar. If the value of the titlebar feature is set to NO by the user then the title bar is not displayed. NOTE: this is called only if the application called is an HTML application, otherwise, calling the titlebar feature is not taken into account.
toolbar:

Syntax: toolbar=yes|no|1|0 Like the scroll bar, the toolbar is used to denote whether the browsers tool bars should be displayed or not. The default value of the toolbar feature is YES, displaying the tool bar. If the value of the toolbar feature is set to NO by the user, then the tool bar is not displayed.
innerHeight:

Syntax: innerHeight=pixels This feature is used to specify the inner height of the window. The value for this feature is given in pixels.
innerWidth:

Syntax: innerWidth=pixels This feature is used to specify the inner width of the window. The value for this feature is given in pixels.

outerHeight:

Syntax: outerHeight=pixels This feature is used to specify the outer height of the window. The value for this feature is given in pixels.
outerWidth:

Syntax: outerWidth=pixels This feature is used to specify the outer width of the window. The value for this feature is given in pixels.
hotkeys: Syntax: hotkeys=yes|no|1|0 If the user sets the value of the hotkeys feature to NO, then the windows usage or function of hotkeys is disabled. replace:

Another optional attribute that is passed to the open() method of window object is the replace method. This attribute is mentioned in the syntax of the open() method in above description. This specifies the way the entry in the history list is handled. This method is used to specify whether the URL has to create a new entry in the history list or replace the current entry in the history list. The replace attribute can take the values of true or false. The truevalue specifies that the URL replaces the current document in the history list. The false value specifies that the URL creates a new entry in the history list. Let us see an example to understand the usage of open() method of window object in brief:

<html> <head> <script type="text/javascript"> function exforsys() { window.open("http://exforsys.com","_blank","toolbar=yes, location=yes, directories=no, status=yes, menubar=no, scrollbars=yes, resizable=no, width=300, height=500") } script> head> <body> <form> <input type="button" value="Click Here to Display Window!!!" onclick="exforsys()">

form> body> html>

The output of the above example is a button with the message:

When this button is clicked, the URL http://exforsys.com displays in a new window. This is because the first argument mentioned is http://exforsys.com and the second argument mentioned is _blank, denoting that the URL loads into a new window. The URL displayed in the new window has its window width as 300 and its height as 500. The value of widthand height are mentioned as 300 pixels and 500 pixels respectively. The windows displayed have the scroll bars, tool bar, status bar displayed because the value of scrollbars, status and toolbar is set to yes, making these visible in the window. The window displayed is not resizable and is fixed in size because the resizable feature is set to no. The value of themenubar is set to no, displaying no menu bars in the final output window.

JavaScript Window Object Open Method


In this JavaScript tutorial, you will learn about JavaScript Window Object Open Method, features of window object open method - channelmode, directories, dependent, fullscreen, screenX, screenY, height, left, location, menubar, resizable, alwaysLowered, alwaysRaised
channelmode:

Syntax: channelmode=yes|no|1|0 The channelmode is used to denote whether the user wants to display the window in theater mode or not. The default setting of this feature is NO. The user can set channelmode value

toYES which would then display the window in theater mode. This is a very important feature of Window Object of JavaScript .
directories:

Syntax: directories=yes|no|1|0 directories are used to specify whether the user wants to add directory buttons or not. The default value of the directories feature is YES.
dependent:

Syntax: dependent=yes|no|1|0 If the value of the dependent feature is set to yes then it creates the new window as a child of the current window.
fullscreen:

Syntax: fullscreen=yes|no|1|0 The feature fullscreen is used to specify whether or not the user wants to display the browser in full-screen mode. The default setting of this feature is NO. User can turn on thefullscreen feature, by setting its value to YES, displaying the browser in full-screen mode. NOTE: This feature requires that a window in full-screen mode must also be in theater mode. If the value of fullscreen is set to yes then the value of the channelmode feature must also be set to yes.
screenX:

Syntax: screenX=pixels When screenX feature is used, the new window created and opened displays from the left side of the screen at a distance equal to the number of pixels specified. The value in this feature is given in pixels.
screenY:

Syntax: screenY=pixels When sreenY feature is used, the new window created and opened displays from the top of the screen at a distance equal to the number of pixels specified. The value in this feature is given in pixels.
height:

Syntax: height=pixels height feature is used to specify the window height. The minimum value that must be specified for the height attribute is 100. The value for this feature is given in pixels.

left:

Syntax: left=pixels left feature is used to specify the left position of the window. The value for this feature is given in pixels.
top:

Syntax: top=pixels top feature is used to specify the top position of the window. The value for this feature is given in pixels.
width:

Syntax: width=pixels width feature is used to specify the window width. The minimum value that must be specified for the width attribute is 100. The value for this feature is given in pixels.
location:

Syntax: location=yes|no|1|0 The location is used to denote whether or not the address field should be displayed. The default value of this location feature is YES, displaying the address field. If the user sets the value to NO in the location feature then the address field is not displayed.
menubar:

Syntax: menubar=yes|no|1|0 The menubar is used to denote whether or not the menu bar should be displayed. The default value of this menubar feature is yes, displaying the menu bar. If the value of the menubarfeature is set to NO by the user, then the menu bar is not displayed.
resizable:

Syntax: resizable=yes|no|1|0 If the user wants to specify whether or not the window should be resizable then the resizable feature can be used. The default value of the resizable feature is yes, making the window resizable by default. If the user does not want the window to be resized then the value must be set to NO by the user.
alwaysLowered:

Syntax: alwaysLowered=yes|no|1|0 When the value of the attribute alwaysLowered is set to YES, it creates a window that always floats below other windows.

alwaysRaised:

Syntax: alwaysRaised=yes|no|1|0 When the value of the attribute alwaysRaised is set to YES, it creates a window that always floats above other windows

JavaScript Window Object Timeout Methods


In this JavaScript tutorial, you will learn about setTimeout(), clearTimeout() and open() methods of window object along with syntax, usage and examples for each method.
setTimeout():

The setInterval() method of Window object is used to call a function or evaluate an expression at specified intervals. The setTimeout() method of a window object performs in a similar manner. In contrast to the setInterval() method, the setTimeout() method of window object is used to call a function or evaluate an expression after a specified number of milliseconds. The setTimeout() method helps schedule the expression or function for the time specified by the user. The function given in arguments is called or the expression is evaluated after a specified number of milliseconds given as argument in the setTimeout() method of window object. General Syntax of the setTimeout() method of window object:
window.setTimeout(expression/function, milliseconds)

setTimeout() example:

<html> <head> <script type="text/javascript"> function exf() { exforsys.close() } </script> </head> <body> exforsys = window.open('','','width=100,height=200') exforsys.document.write("Example on setTimeout() method!") exforsys.setTimeout('exf()', 7000) </body> </html>

The output of the above program is a window exforsys. This opens with the displayed message:
Example on setTimeout() method!

The window exforsys is closed after seven seconds. The setTimeout() method is applied to the window exforsys with a parameter passed as function exf(). This performs the action of closing the window exforsys by the statement exforsys.close(). This is performed after 7 seconds because the second parameter passed to the setTimeout() method is 7000 milliseconds.
clearTimeout():

If a user wishes to cancel the timeout set in the setTimeout() method, he or she can use theclearTimeout() method of window object. The clearTimeout() method of a window object is used to cancel a timeout set with the setTimeout() method. General Syntax of the clearTimeout() method of window object:
window.clearTimeout(timeoutID)

The timeoutID given as argument in the clearTimeout() method is the ID that is declared or set during the setTimeout() method. An example to understand the usage of the clearTimeout() method of window object:

<html> <head> <script type="text/javascript"> exforsys = setTimeout ("window.location='http://exforsys.com/test.html'", 5000); </script> </head> </html>

The above example sends the user to a new page test.html in exforsys.com after 5 seconds. The setTimeout method calls the page after 5000 milliseconds or 5 seconds. The ID of thesetTimeout method is set to exforsys. Using the clearTimeout() method of window object and the previous example to cancel the timeout set in the setTimeout() method:

<html> <head>

<script type="text/javascript"> clearTimeout (exforsys); </script> </head> </html>

In the above example, the timeout created in the previous example is canceled by passing the corresponding ID exforsys set in setTimeout() method as argument to the clearTimeout()method of window object.
open():

A new browser window opens using the open() method of a window object. General Syntax of the open() method of window object:
window.open(URL,name,specs,replace)

In the above, all the fields (URL, name, specs, replace) given in arguments are optional. The URL given in the argument of the open() method of window object specifies the URL of the page to open. If the user does not mention any URL, then an empty window will be created and opened. The name field specified in the open() method of window object is a string denoting the name of the new window. This can be used as the target attribute. The most commonly used values are:
_blank This is a default value that denotes that the URL is loaded into a new window. _parent This denotes that the URL is loaded into the parent frame. _self This denotes and makes the URL replace the current page. _top This denotes that the URL replaces any framesets that may be loaded. name This denotes the name of the window.

The specs field specified as argument in the open() method of window object can have numerous items in it, each separated with commas. This is a string denoting the details of the features or attributes that are to be used for the new window. The features have a value as either yes or no and, in some cases, as 1 or 0. Any feature can be turned on, as the user requires or needs to use it. Some of the features or attributes that are most commonly used are:
channelmode directories dependent

fullscreen screenX screenY height left location menubar resizable alwaysLowered alwaysRaised scrollbars status titlebar toolbar top width innerHeight innerWidth outerHeight outerWidth hotkeys

The usage, syntax and explanation of the above features will be described in the next section in detail.

JavaScript Object Oriented Features


Author : Exforsys Inc. Published on: 20th May 2007

JavaScript Object Oriented Features


In this JavaScript tutorial you will learn about JavaScript Object Oriented Features, object type, object instantiation, using object properties, using object methods and achieving object instantiation. Object-oriented capabilities make any language or application powerful. This section outlines the object oriented features supported by JavaScript and how to use them in programming process. JavaScript is not a complete programming language but, rather, it is a scripting language. There are some object-oriented features that are not supported by JavaScript. JavaScript does not support the features of inheritance, information hiding, encapsulation and classification that are supported by other object-oriented programming languages. Lack of information hiding and lack of encapsulation features in JavaScript cause the methods and properties to only be accessible directly in JavaScript. Similarly, JavaScript does not support

the inheritance or classification features. These features cannot be used for developing hierarchy of object types. The concepts of object reusability and modular approach concept are used by JavaScript in a very limited way. JavaScript can be reused in the Internet only by using SRC attribute (discussed in the SCRIPT tag in an earlier section of this tutorial). Polymorphism, another important feature of Object-oriented programming, is supported by JavaScript using arguments array in function definition, which will be explained in detail in later sections. The lack of these features does not reduce the capabilities of JavaScript in any way. JavaScript has many other compensating features, making it the best scripting language for use in web and server side programming.
Object based Features Supported by JavaScript:

JavaScript supports various features related to object based language and JavaScript is sometimes referred to as an object-based programming language. The vital features which JavaScript supports related to object based are:
Object Type:

JavaScript supports the development of Object types and in this context JavaScript supports both predefined and user-defined objects. It is possible to assign objects of any type to any variable. It is possible to instantiate the defined object types to create object instances in JavaScript, which is a very powerful feature of Object based language. In this context, the limitation of Object type in JavaScript does not permit users to carry out type enforcement on Object types.
Object Instantiation:

To carry out the process of creating specific object instances available in JavaScript, users can make use of a new operator. These two powerful, object-based features supported by JavaScript described above make this an object model language. In JavaScript, the object types are defined by properties and methods. Properties of Objects are used to access the data values contained in an object. Users can make use of the properties of JavaScript objects for editing as well as reading, depending on whether or not the objects nature is read only. If the user wants to carry out functions on the object, this is achieved by using methods that make use of the objects properties. Using object based features (object properties and methods), in JavaScript:

To use Object Properties:

Syntax for making use of JavaScript object properties is by using the object name followed by dot and then the property name:
objectname.propertyname

To use Object Methods:

Syntax for making use of JavaScript object methods follows the same process as objectproperties with the difference being that the property name is replaced by the method name and any arguments. To access object methods in JavaScript, the programmer uses theobject name followed by dot and then the method name with any arguments:
objectname.methodname(arguments)

How to achieve Object instantiation:

The new operator available feature is used to achieve Object instantiation. General syntax for new operator for creating objects in JavaScript is as follows:
variablename=new objecttype(arguments)

In the above syntax, new refers to keyword and the objecttype(arguments) refer to the constructor. The number of arguments taken by constructors varies from no arguments to one or more than one, depending on the type of object. An example of object type with constructor taking no arguments:
CD=new Date() Date refers to the predefined JavaScript object type. The Date() constructor does not

take any parameter and the above statement stores the current date and time to the variable CD. It is also possible to use the same object type. For example, the Date() constructer taking a specified date as the parameter and creating object instances for that specified date.
CDD=newDate(96,3,3)

In this example, instances are created for the specified Date March 3,1996.

JavaScript Browser Objects


Page 1 of 2
Author : Exforsys Inc. Published on: 13th Jun 2007

JavaScript Browser Objects


In this JavaScript tutorial, you will learn about browser objects in JavaScript, categories of browser-based objects, additional browser objects, anchor object, link object, properties of link object and methods of link object. JavaScript supports a number of browser-based objects. When a webpage loads by a browser that supports JavaScript, the browser creates a variety of JavaScript objects. This makes it possible to access the web page and handle elements, like HTML. There are a vast number of browser objects for JavaScript. This section highlights some of the most vital and supported by most popular browsers. With the help of these browser-based objects, it is possible for JavaScript to interact with the browser and the loaded webpage.
Categories of Browser-based Objects:

JavaScript browser-based objects are broadly categorized into two main categories:
Browser Object Model also called BOM Document Object Model also called DOM

The Document Object Model (DOM) is a W3C standard meaning it is a platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure and style of documents. DOM describes the relationship of the HTML elements within the document to the document object itself. The Document Object Model is actually present inside the Browser Object Model. The Browser Object Model or BOM, includes objects related to the browser. DOM does not include the browser and all things related to it. In the DOM, the topmost object is the document object. In the BOM, the topmost level contains the window object followed by the navigator, screen, history, location, and document objects. There are additional browser objects available in JavaScript:
anchor object applet object area object button object checkbox object elements object

embed object event object FileUpload object form object frame object hidden object image object mimeType object option object password object plugin object radio object reset object select object submit object text object textarea object link object

The above objects along with their properties, methods and syntax will be explained in later sections of this tutorial. The following section will discuss link object and anchor object . JavaScript Browser Objects
Link Object:
Link object is also a property of the document object. The link object is used to get or

capture a text or image link present in a document. Similar to the anchor object having anchor array, all the links are contained in link array.
Properties of Link Object:

The link object has all the properties of the location object such as; hash, host,hostname, href, pathname, port, protocol and search. Additionally, link object has one more property called target property. The target property is used to identify the window where the document referenced by the link's URL loads. The most popularly used Internet Explorer browser, supports both anchor object and link object. Because of this association, the programmer might have a question in differentiating between the two. The href property of anchors object sets the anchor that represents the link and when the name property is set, it indicates a named anchor.

Methods of Link Object:

There is only one method present in the link object named handleEvent(). The argument given in this method is an event object, thus invoking the associated event handler for that event. There is an anchor() method associated with the string object and, additionally, there is another method of string object called the link() method. The link() method of string object takes HREF attribute of link as parameter and creates a link to the given HREF. This can be written as follows:
exforsys =" Welcome Training".link("http://www.exforsys.com/training/") documet.write(exforsys) To

The above example generates HTML, thus creating a link for the current document with the given HREF.
Anchor Object:

The anchor object accesses the target of a hypertext link since it keeps track of all named offsets defined in respect to the HTML document. The anchor object has no associated properties, methods or events. It is actually a property of the document object. All the anchors of a particular document are contained in anchor array, so this is used for accessinganchor objects within a document. There is an anchor() method associated with thestring object, used for creating an anchor in a current document. This can be written as follows:
example="Exforsys".anchor("test") document.write(example)

The above example creates the named anchor in the current document.

JavaScript Elements and Embed Objects


Author : Exforsys Inc. Published on: 4th Aug 2007

JavaScript Elements and Embed Objects


In this JavaScript tutorial, you will learn about browser objects - elements and embed, properties of elements object, length, type, embed object, properties of embed object along with syntax and examples.

elements object:

The elements object is used in JavaScript to access all form elements such as fields or buttons that are present or embedded within a form. Since each element inside the form is stored as an array element within the array elements[], the user can make use of the loop concept to access any individual element within a form in JavaScript. For example:
document.exforsys.elements[j]

The above statement is used to access the jth form element within the form exforsys. If a user wants to get the total number of form elements within the form exforsys, it can be written by the following statement:
document.exforsys.elements.length

Properties of elements object:


length type

length: The length property of elements object returns the total number of elements within the form. The example above depicts the usage of this property. type: The type property of elements object is used to return the type of the form element accessed. The returned value from this property would be a string type. In other words, the type of form elements that are returned from this property can be any one of these: button, checkbox, file, hidden, image, password, radio, reset, submit, text, textarea, select-one, select-multiple For example:
document.exforsys.elements[j].type

The above statement returns the type of the jth form element exforsys. An example to understand all the concepts of elements objects discussed above in detail:

<html> <head> <script type="text/javascript"> testing(exforsys){

function

var for

flag=true j&lt;exforsys.elements.length; i++){ (exforsys.elements[j].type=="text"){ if (exforsys.elements[j].value==""){ alert("Must Enter Value!!!") flag=false break } (j=0; if

} } return }

flag </script> </head> <body> </body>

</html>

In the above example, function testing can be used to check if any text box in a form from the function call has been left empty. From each element on the form where the function testing is called, using for loop on the elements array accesses this. The for loop runs until theelements.length returns the total number of elements within the form. Each element in the form is checked for text box type by using the if statement:
exforsys.elements[j].type=="text"

When if returns true then the value of this text box element is checked for empty by the if statement:
exforsys.elements[j].value==""

If this also returns true then an error message is generated for entering value and loop breaks with a false value returned to the function call.
embed object:

The embed object is used in JavaScript to access all embedded object. If a user wants to access all the embedded objects contained in a document then he or she can make use of the embeds array. The embeds array gives access to all the embedded objects associated with the document.
Properties of embed object:
SRC Type Align Height

Width Name Hidden Palette Pluginspage ReadyState Units

The programmer can make use of &lt;embed&gt; tag to embed Plug-in documents in a web page. The concept Plug-in documents will be detailed in later sections of this tutorial. General syntax of using embed tag is as follows:
&lt;embed attribues&gt;

In the above, the SRC attribute or a Type attribute is mandatory. The user can include the remainder of the attributes mentioned above when needed. SRC: The SRC attribute of the embed tag denotes the documents to be embedded and displayed in the plug-in. This attribute is used more often than the Type attribute. For example, an example to understand the usage of &lt;embed&gt; tag with SRC attribute.
&lt;embed SRC="exforsys.avi"&gt;

The above denotes the location of the document to be viewed by a plug-in. The details of how the above is internally processed will be explained later in the plug-ins concepts of JavaScript chapter. Type: The type attribute of JavaScript is used to specify the MIME type. Height: As the name implies, the Height attribute specifies the vertical dimension of the window area assigned to plug-in. Width: As the name implies, the Width attribute specifies the horizontal dimension of the window area assigned to plug-in. Name:

Denotes the name by which the user can access the associated plug-in object. Hidden: This attribute helps the user to make the plug-in object visible or hidden as needed. Palette: This attribute denotes the mode of the plug-in color palette. Units: The units attribute denotes the units by which the Height and Width attributes are ascribed. The default unit is pixels.

JavaScript Applet Objects


Author : Exforsys Inc. Published on: 13th Jun 2007

JavaScript Applet Objects


In this JavaScript tutorial, you will learn about applet object, properties and methods of applet object, Methods of applet object, area object, Properties of area object viz. hash, host, hostname, href, pathname, port, protocol, search and target.
applet object:

The applet object is used in JavaScript to access a Java applet. User can make use of theapplets array to access all the applets contained in a document. The applets array property gives access to all the applets associated with the document. The applet object is a browser object that is a property of the document object, used for enabling code of JavaScript to access java variables and methods.
Properties of applet object:

The applet object of JavaScript has name property associated with it. This property is used to access the name attribute associated with the <applet> tag.
Methods of applet object:

There are no methods or events associated with the applet object of JavaScript.
area object:

The area object is a browser object in JavaScript used to access an area from the client side. The area object is actually a property of the document object. The area object has similar attributes to that of the link object.

Properties of area object:


hash host hostname href pathname port protocol search target

hash:
hash property of area object denotes the URL anchor part including the leading hash mark if

one exists.
host:
host property of area object denotes the URL hostname and port.

hostname:
hostname property of area object denotes the URL hostname section.

href:
href property of area object denotes the URL.

pathname:

As the name suggests, pathname property of area object denotes the URL pathname section.
port:
port property of area object denotes the URL port section.

protocol:
protocol property of area object denotes the URL protocol section including the colon after

the protocol name.


search:
search property of area object denotes the URL query string section.

target:
target property of area object denotes the URL link's target name.

JavaScript Form Object

Author : Exforsys Inc.

Published on: 19th May 2007

JavaScript Form Object


In this JavaScript Tutorial you will learn about JavaScript form object, properties of form object, action - elements[], encoding, length, method, name, target, button, checkbox, FileUpload, hidden, password, radio, reset, select, submit, text, textarea and methods of form object.
Form Object:
form object is a Browser object of JavaScript used to access an HTML form. If a user

wants to access all forms within a document then he can use the forms array. The form object is actually a property of document object that is uniquely created by the browser for each form present in a document. The properties and methods associated with form object are used to access the form fields, attributes and controls associated with forms.
Properties of Form Object:
action elements[] encoding length method name target button checkbox FileUpload hidden password radio reset select submit text textarea

action:
action property of form object is used to access the action attribute present in HTML

associated with the <form> tag. This property is a read or write property and its value is a string.

elements[]:
elements property of form object is an array used to access any element of the form. It

contains all fields and controls present in the form. The user can access any element associated with the form by using the looping concept on the elements array.
encoding:

The encoding property of a form object is used to access the enctype attribute present in HTML associated with the <form> tag. This property is a read or write property and its value is a string. This property helps determine the way of encoding the form data.
length:
length property of form object is used to specify the number of elements in the form. This

denotes the length of the elements array associated with the form.
method:
method property of form object is used to access the method attribute present in HTML

associated with the <form> tag. This property is a read or write property and its value is a string. This property helps determine the method by which the form is submitted.
name:
name property of form object denotes the form name.

target:
target property of form object is used to access the target attribute present in HTML

associated with the <form> tag. This property denotes the name of the target window to which form it is to be submitted into.
button:

The button property of form object denotes the button GUI control placed in the form.
checkbox:
checkbox property of form object denotes the checkbox field placed in the form.

FileUpload:
FileUpload property of form object denotes the file upload field placed in the form..

hidden:

The hidden property of form object denotes the hidden field placed in the form.

password:
password property of form object denotes the object that is placed as a password field in the

form.
radio:
radio property of form object denotes the radio button field placed in the form.

reset:

As the name implies, the reset property of form object denotes the object placed as reset button in the form.
select:
select property of form object denotes the selection list object placed in the form.

submit:
submit property of form object denotes the submit button field that is placed in the form.

text:
text property of form object denotes the text field placed in the form.

textarea:
textarea property of form object denotes the text area field placed in the form.

An example to understand the above explanations in detail:


<FORM NAME="exforsys" ACTION="" METHOD="GET"> Input Values:<BR> <INPUT TYPE="text" NAME="test" VALUE=""><P> <INPUT TYPE="button" NAME="example" VALUE="Click"onClick="testfunc(this.for m)"> </FORM>

Here the FORM NAME="exforsys" creates and denotes the name of the form. The user can refer to the form in his or her code of JavaScript by the name exforsys. The form name given must follow the naming conventions or rules of JavaScript's variable or function naming rules. The next word, ACTION="" tells the way the user wants the browser to handle the form when it is submitted to a CGI program running on the server. It can also be left as not specified with any of the above properties. This means the URL for the CGI program is then omitted. The METHOD="GET" defines that the method data is passed to the server when the form is submitted.

INPUT TYPE="text" defines the object used as a text box with the name of the text box as a

test with no initial value specified. INPUT TYPE="button" defines the object used as a button with the name of the button object as an example. The value is specified as Click and when the button is clicked, the onClick event handler fires and the function associated with it (testfunc(this.form)) is called.
Methods of form object:
reset() submit() handleEvent()

reset():
reset() method of form object is used to reset a form.

submit():
submit() method of form object is used to submit a form.

handleEvent():
handleEvent() method of form object is used to start or invoke a form's event handler for a

specified event.

JavaScript FileUpload Object


Author : Exforsys Inc. Published on: 18th May 2007

JavaScript FileUpload object


In this JavaScript tutorial, you will learn about FileUpload object, FileUpload properties, accessKey, disabled, form, name, type, value, FileUpload methods - blur(), focus(), select(), handleEvent(), click() and event handlers - onblur, onchange and onfocus.

FileUpload object:

FileUpload represents an element that allows a user to specify a file to be uploaded or submitted along with the form. The FileUpload object is a Browser object and is used to access the above FileUpload element of a form. Thus, the FileUpload object allows the user to give any file as input. If a user wants to access the FileUpload object then he or she can using the indexing concept on the elements array. The user can make use of each element inside the form that is stored as an array element within the array named elements []. To implement the FileUpload object:

<FORM> <INPUT TYPE="file" NAME="elementName"> FORM>

The above gives a text area and a Browse button where users can upload their files of choice to the form.

Properties of FileUpload object:


accessKey disabled form name type value

accessKey:

The accessKey property of FileUpload object is used to set or return the accessKey for the field. The returned value from this property is a string.
disabled:

The disabled property of FileUpload object is used to set or return whether or not the field is disabled. The returned value from this property would be a boolean type that is trueor false.

form:

The FileUpload object is a Browser object, used to access the FileUpload element of a form. The form property of FileUpload object is used to reference the form that contains the file upload field. Thus, the form property of FileUpload object returns a reference to the parent form of the FileUpload object. General syntax of form property of FileUpload object is:
object.form

name:

The name property of FileUpload object denotes the name of the FileUpload field. General syntax of name property of FileUpload object is:
object.name

type:

The type of the calling form element and the type property of FileUpload object denotes the file type. General syntax of type property of FileUpload object is:
object.type

value:

The value property of FileUpload object the FileUploadfield.

denotes

the

file

name

entered

into

NOTE: FileUpload object is a read only property. General syntax of form property of FileUpload object is:
object.value

Methods of FileUpload object:


blur() focus() select() handleEvent()

click()

blur():

The blur() method of FileUpload object is used to remove the focus away from theFileUpload field. General syntax for using this method is:
object.blur()

focus():

The focus() method of FileUpload object is used to set the focus on the FileUpload field. General syntax for using this method is:
object.focus()

select():

The select() method of FileUpload object is used for selecting the input area of theFileUpload field. General syntax for using select() method is:
object.select()

handleEvent():

The handleEvent() method of FileUpload object is used to call or invoke the handler for the specified event. General syntax for using this method is:
handleEvent(event)

In the above statement, the event given in argument of the handleEvent method denotes the name of the event associated with the object that has the event handler.
click():

The click() method of FileUpload object denotes and simulates the mouse-click on theFileUpload object. General syntax for using click() method is:

object.click()

Event Handlers of FileUpload object:


onBlur onChange onFocus

onBlur:

The onBlur Event Handlers of FileUpload object fire and execute on the occurrence of the blur event. The onBlur Event Handlers of FileUpload object fire and execute JavaScript code when the focus is lost from the fileUpload field.
onChange:

The onChange Event Handlers of FileUpload object fire and execute JavaScript code when the user changes the value of the FileUpload field and moves focus away from the field.
onFocus:

The onFocus Event Handlers of FileUpload object fire and execute on the occurrence of the focus event. The onFocus Event Handlers of FileUpload object (in contrast to OnBlur event handler) fire and execute JavaScript code when the focus is set on the FileUpload field.

JavaScript Event Object Properties and Methods


Page 1 of 2
Author : Exforsys Inc. Published on: 9th Jun 2007 | Last Updated on: 13th Apr 2011

JavaScript Event Object Properties and Methods


In this JavaScript tutorial, you will learn about event object properties and methods like keycode, layer, offset, modifiers, page, reason, returnValue, screen, srcElement, target, srcFilter and type.
keycode:

The keycode property of event object is used to indicate the keycode associated with the key press of the event. The returned value is a Unicode keycode. If a user wants to convert the value as string, then the predefined function fromCharCode() must be used for conversion. The property keycode is supported only by Internet Explorer and in Navigator, the property named charCode is used to achieve the same result.

layerX and layerY:

The properties layerX and layerY of event object are used to return the cursors horizontal and vertical position, respectively, relative to the layer of occurrence of the event. The returned value from this property will be in pixels. Only Navigator supports this property and the same result can be achieved in Internet explorer by using the offsetX and offsetY properties of event object.
offsetX and offsetY:

The properties offsetX and offsetY of event object are used to return the cursors horizontal and vertical position relative to the container of occurrence of event. The returned value from this property will be in pixels. Only Internet explorer supports this property. In Navigator, the same result can be achieved by using layerX and layerY properties of event object.
modifiers:

The modifier property of event object indicates the keys ALT_MASK,CONTROL_MASK,SHIFT_MASK and META_MASK that are associated with the event happening or key press of an event. These are modifier keys, hence the name. This property is supported only on Navigator.
pageX and pageY:

The properties pageX and pageY of event object are used to indicate the cursor's horizontal and vertical position relative to the page of occurrence of an event. The value denoted by these properties is in pixels. This property is supported only on Navigator and is not supported by Internet Explorer.
reason:

The reason property of event object denotes the status of the transfer of data. This property is supported only by Internet Explorer and not by navigator.
returnValue:

The returnValue of an event object is used to denote the event handler's return value. A false Boolean value is set to indicate canceling of any default action for the event handler. Only Internet Explorer supports this property. In Navigator, the same action can be achieved by using the method preventDefault() which will be discussed in methods of event object.
screenX and screenY:

The properties screenX and screenY of event object are used to indicate the cursor's horizontal and vertical position relative to the screen of occurrence of an event. The value

denoted by these properties is in pixels. Internet Explorer supports both by Navigator and this property.
srcElement:

The srcElement property of event object denotes the element that the event occurred on. Only Internet Explorer supports this property and the same result can be achieved in Navigator by using the target property of event object.
target:

The target property of event object denotes the element in which the event occurred on. Only Navigator supports this property and the same results can be achieved in Internet Explorer by using the srcElement property of event object.
srcFilter:

The srcFilter property of event object denotes the filter object that initiated the onfilterchange event. The onfilterchange event is detailed in the next section of this tutorial. Only Internet Explorer supports this property.
type:

As the name implies, the type property of event object denotes the type of event; click, mouseout and so on. This property is supported both by Internet Explorer and Navigator.
x and y:

The properties x and y of event object are used to indicate the cursor's horizontal and vertical position relative to the document of occurrence of an event. The value denoted by these properties is in pixels. This property is supported only by Internet Explorer and not by Navigator.
Methods of event object:
preventDefault() stopPropagation()

JavaScript Event Object


Author : Exforsys Inc. Published on: 20th May 2007

JavaScript Event Object


In this JavaScript tutorial you will learn about JavaScript event object, properties of event object, altKey, ctrlKey and shiftKey, button, integer value action representation, cancelBubble, clientX and clientY, fromElement and toElement, height and width.

event Object:

The event object is a browser object used to get information about a particular event specified. Using event object, users can access information about event happenings. The difference between event object and Event object is such that the latter gives constants that can be used to identify events, while the former is used to get information about events.
Properties of event Object:
altKey,ctrlKey and shiftKey button cancelBubble clientX clientY fromElement toElement height width keycode layerX layerY modifiers offsetX offsetY pageX pageY reason returnValue screenX screenY srcElement srcFilter target type which x and y

In the above list, some of the events are supported with Internet Explorer Browser and some with Navigator browser, which will be detailed. Some of the properties of event object are explained below.
altKey, ctrlKey and shiftKey:

The above property is used to indicate whether the Alt Key, Control Key or Shift Key was pressed by the user when the event occurred. The indication is known by appropriately setting the value as true or false. This property takes a boolean value as its

return type. Both Internet Explorer and Navigator support this property. In Navigator, there is an extra property called metaKey which is not supported by Internet Explorer. This indicates if the user has pressed Meta key when the event occurred.
button:

The button property of event object is used to denote whether the mouse button was pressed or released when the event occurred. The indication is performed by means of an integer value where the values listed below are returned as per the action when the event occurred. The return value from button property is an integer. Integer Value Action Representation
0 1 2 4 no Button Left Mouse Button Right Mouse Button Middle Mouse Button was pressed was was was pressed pressed pressed

Sometimes, user presses more than one button at the same time when the event occurs. To indicate such a situation, the integer representation would take the sum of integer representations of buttons pressed by the user. For example, if a user presses both the right and the middle button, then addition of the integer representations of right and middle button gives 2+4=6 is returned by the property. This property is supported both by Internet Explorer and Navigator. In Navigator, the integer representation values differ: Integer Value Action Representation
0 Left Mouse Button 2 Right Mouse Button 1 Middle Mouse Button was pressed was was pressed pressed

cancelBubble:
cancelBubble property of event object is used for enabling or disabling the event bubbling

concept of an event object. Event bubbling concept will be discussed in the next section of this tutorial. This property enables and disables event bubbling by setting the boolean value appropriately as true or false as needed. The value of the property cancelBubble is set totrue to prevent the event from bubbling and if it is set to false, the event bubbling is enabled. Only Internet Explorer supports this property. In Navigator, to implement the same property, the programmer has to use the method associated with event object (to be discussed in the methods of event object section).

clientX and clientY:

This property of event object indicates the cursor's horizontal and vertical position when the event occurs relative to the upper-left corner of the window. The denoted value would be in terms of pixels. Both by Internet Explorer and Navigator support this property. Syntax for using this property is as follows:
event.clientX event.clientY

fromElement and toElement:

These properties are supported only in Internet Explorer and denote the HTML element. The event moves from or to, respectively, for fromElement and toElement. The propertiesfromElement and toElement each denote, respectively, the elements the mouse is leaving from and moving onto. In Navigator, the property named relatedTarget is used to achieve the same result. In case of a mouseover event, the relatedTarget property of event object denotes the element that the mouse has left. In case of mouseout event, the relatedTargetproperty of event object denotes the element that the mouse has entered.
height and width:

The height and width property of event object is only supported by Navigator and it indicates the height and width of window or frame, respectively. The value is denoted in pixels.

JavaScript Browser Objects Part 2


In this JavaScript tutorial, you will learn about Browser Objects viz button object properties of button object, form, name, value, Methods of button object, checkbox object, properties of checkbox object - checked, defaultChecked, form, name, type, value, Methods of checkbox object - blur(), click() and focus().
button object: The button object is a browser object in JavaScript that is used to access a form button

other than submit or reset. The button object is a property of the form object. General syntax of button object in JavaScript is as follows:
<INPUT TYPE="button" NAME="some value" onClick="Functionname"> button name"VALUE="some

For example:

<INPUT TYPE="button" NAME="Exforsys" VALUE="For Here!!!" onClick="TrainingFunc">

Training

Click

The above would create a button with a caption on the button:


For Training Click Here!!!

When the button is clicked, the function TrainingFunc is called. The function call is optional and when it is placed, the corresponding function must also be placed.
Properties of button object:

The following are the properties associated with button object:


form name value

form:
form property of button object denotes the form object that includes the button.

name:
name property of button object denotes the name of the button.

value:
value property of button object denotes the value of the button that appears on the button.

Methods of button object:

The most commonly used method of button object The click()method invokes when the user clicks the button.

is

the click() method.

JavaScript Frame object


Author : Exforsys Inc. Published on: 20th May 2007

JavaScript Frame Object


In this JavaScript tutorial, you will learn about frame object its properties and methods in detail with example. frame object, properties of frame object, frames, self, name, length, parent, methods of frame object, blur(), focus(), setInterval(), clearInterval(), setTimeout(expression, milliseconds), clearTimeout() and events associated with frame object.

Frame Object:

The frame object is a browser object of JavaScript used for accessing HTML frames. The user can use frames array to access all frames within a window. Using the indexing concept, users can access the frames array. NOTE:
The frames array index always starts with zero and not 1. The frame object is actually a child of the window object. These objects are created automatically by the browser and help users to control loading and accessing of frames. The properties and methods of frame object are similar to that of Window object in JavaScript. The frame object does not support close() method that is supported by window object. Using the <FRAMESET> document creates frame objects and each frame created is thus a property of window object.

Properties of frame object:


frames name length parent self

frames:

The frames property of frame object denotes a collection or array of frames in a window and also in a frame set.
self:

As the name implies, the self property of frames object denotes the current frame. Usingself property, the user can access properties of the current frame window.
name:

The name property of frame object denotes the name of the frame. The method of denoting the name attribute is performed by using the name attribute of the <frame> tag. For example it can be written as:
exforsys=window.frames(2).name

The above statement would store the name of the third window frame (as the frames array start with index 0) in a frameset document in the variable exforsys.
length:

The frames array has all the frames present within a window and the length property of theframe object denotes the length of the frames array or gives the number of frames present in a window or a frames array.
parent:

As the name implies, the parent property of frames object denotes the parent frame of the current frame.
Methods of frame object:
blur() focus() setInterval() clearInterval() setTimeout(expression, milliseconds) clearTimeout(timeout)

blur():
blur() method of frame object removes focus from the object.

focus():
focus() method of frame object gives focus to the object.

setInterval():
setInterval() method of frame object is used to call a function of JavaScript or to

evaluate an expression after the time interval specified in arguments has expired. The time interval in arguments is always specified in milliseconds. For example:
setInterval=exforsys(test(),2000)

In the above statement, the function test() executes after 2000 milliseconds (2 seconds), specified in the argument.

clearInterval():
clearInterval method

of frame object is used to cancel the corresponding definedsetInterval method. This is written by referencing the setInterval method using its ID or variable. General syntax for the method clearInterval() is as below:
clearInterval (Interval_ID)

setTimeout(expression, milliseconds):
setTimeout method of frame object can be used to execute any function, or access any

method or property after a specified time interval given to this method as argument. General syntax for the method setTimeout() is as below:
setTimeout(expression, milliseconds)

For example:
exforsys=setTimeout ("test()", 3000)

The time is always specified in milliseconds and in the above statement, the function test()is called after the specified time of 3000 milliseconds (3 seconds). This is stored in variable named exforsys. There is confusion about the similarity between setTimeout() method and setInterval()method. The main difference between the two methods is the setInterval method will repeatedly call the referenced function or evaluate the expression until the user leaves the document. In the setTimeout method, the call executes only once after the specified time interval given as argument.
clearTimeout():
clearTimeout method of frame object is used to clear a specified setTimeout method.

This is written by referencing the setTimeout method using its ID or variable. General syntax for the method clearTimeout is as below:
clearTimeout ID_of_setTimeout

For example
clearTimeout exforsys

The above statement clears the setTimeout associated wit the ID named as exforsys, created in the earlier example.
Events associated with frame object:

Though the frame object and frames array have no event handlers associated directly with them, the following event handlers are used to access and control frame objects and frames array:
onBlur onFocus OnLoad OnUnLoad

You might also like