0% found this document useful (0 votes)
1 views55 pages

JavaScript Notes

This document provides an introduction to JavaScript, detailing its purpose, capabilities, and differences from Java. It explains how to embed JavaScript in HTML, use it for dynamic content, and handle browser compatibility. Additionally, it covers JavaScript variables, operators, control structures, and looping mechanisms, providing examples for clarity.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views55 pages

JavaScript Notes

This document provides an introduction to JavaScript, detailing its purpose, capabilities, and differences from Java. It explains how to embed JavaScript in HTML, use it for dynamic content, and handle browser compatibility. Additionally, it covers JavaScript variables, operators, control structures, and looping mechanisms, providing examples for clarity.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

Web Technology Chapter- Introduction

JavaScript
 JavaScript was designed to add interactivity to HTML pages
 JavaScript is a scripting language
 A scripting language is a lightweight programming language
 JavaScript is usually embedded directly into HTML pages
 JavaScript is an interpreted language (means that scripts execute without
preliminary compilation)
 Everyone can use JavaScript without purchasing a license

Are Java and JavaScript the same?


NO! Java and JavaScript are two completely different languages in both concept and
design! Java (developed by Sun Microsystems) is a powerful and much more complex
programming language - in the same category as C and C++.

What can a JavaScript do?

 JavaScript gives HTML designers a programming tool - HTML authors are


normally not programmers, but JavaScript is a scripting language with a very
simple syntax! Almost anyone can put small "snippets" of code into their HTML
pages
 JavaScript can put dynamic text into an HTML page - A JavaScript statement
like this: document.write("<h1>" + name + "</h1>") can write a variable text into
an HTML page
 JavaScript can react to events - A JavaScript can be set to execute when
something happens, like when a page has finished loading or when a user clicks on
an HTML element
 JavaScript can read and write HTML elements - A JavaScript can read and
change the content of an HTML element
 JavaScript can be used to validate data - A JavaScript can be used to validate
form data before it is submitted to a server. This saves the server from extra
processing
 JavaScript can be used to detect the visitor's browser - A JavaScript can be used
to detect the visitor's browser, and - depending on the browser - load another page
specifically designed for that browser
 JavaScript can be used to create cookies - A JavaScript can be used to store and
retrieve information on the visitor's computer

The Real Name is ECMAScript

 JavaScript's official name is ECMAScript.


ECMAScript is developed and maintained by the ECMA organization.
 ECMA-262 is the official JavaScript standard.

32
Web Technology Chapter- Introduction

 The language was invented by Brendan Eich at Netscape (with Navigator 2.0), and
has appeared in all Netscape and Microsoft browsers since 1996.
 The development of ECMA-262 started in 1996, and the first edition of was
adopted by the ECMA General Assembly in June 1997.
 The standard was approved as an international ISO (ISO/IEC 16262) standard in
1998.
 The development of the standard is still in progress.
 The HTML <script> tag is used to insert a JavaScript into an HTML page.

The example below shows how to use JavaScript to write text on a web page:

<html>
<body>
<script type="text/javascript">
document.write("Hello World!");
</script>
</body>
</html>

The example below shows how to add HTML tags to the JavaScript:

<html>
<body>
<script type="text/javascript">
document.write("<h1>Hello World!</h1>");
</script>
</body>
</html>

To insert a JavaScript into an HTML page, we use the <script> tag. Inside the <script> tag
we use the type attribute to define the scripting language.

So, the <script type="text/javascript"> and </script> tells where the JavaScript starts and
ends:

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

The document.write command is a standard JavaScript command for writing output to a


page.

33
Web Technology Chapter- Introduction

By entering the document.write command between the <script> and </script> tags, the
browser will recognize it as a JavaScript command and execute the code line. In this case
the browser will write Hello World! to the page:

<html>
<body>
<script type="text/javascript">
document.write("Hello World!");
</script>
</body>
</html>

Note: If we had not entered the <script> tag, the browser would have treated the
document.write("Hello World!") command as pure text, and just write the entire line on the
page.

How to Handle Simple Browsers


Browsers that do not support JavaScript, will display JavaScript as page content. To
prevent them from doing this, and as a part of the JavaScript standard, the HTML comment
tag should be used to "hide" the JavaScript.

Just add an HTML comment tag <!-- before the first JavaScript statement, and a --> (end
of comment) after the last JavaScript statement, like this:

<html>
<body>
<script type="text/javascript">
<!--
document.write("Hello World!");
//-->
</script>
</body>
</html>

The two forward slashes at the end of comment line (//) is the JavaScript comment symbol.
This prevents JavaScript from executing the --> tag.

JavaScripts can be put in the body and in the head sections of an HTML page.

Where to Put the JavaScript


JavaScripts in a page will be executed immediately while the page loads into the browser.
This is not always what we want. Sometimes we want to execute a script when a page
loads, or at a later event, such as when a user clicks a button. When this is the case we put
the script inside a function, you will learn about functions in a later chapter.

34
Web Technology Chapter- Introduction

Scripts in <head>
Scripts to be executed when they are called, or when an event is triggered, are placed in
functions. Put your functions in the head section, this way they are all in one place, and
they do not interfere with page content.

Example

<html>
<head>
<script type="text/javascript">
function message()
{
alert("This alert box was called with the onload event");
}
</script>
</head>

<body onload="message()">
</body>
</html>

Scripts in <body>
If you don't want your script to be placed inside a function, or if your script should write
page content, it should be placed in the body section.

Example

<html>
<head>
</head>

<body>
<script type="text/javascript">
document.write("This message is written by JavaScript");
</script>
</body>
</html>

Scripts in <head> and <body>


You can place an unlimited number of scripts in your document, so you can have scripts in
both the body and the head section.

Example

<html>

35
Web Technology Chapter- Introduction

<head>
<script type="text/javascript">
function message()
{
alert("This alert box was called with the onload event");
}
</script>
</head>

<body onload="message()">
<script type="text/javascript">
document.write("This message is written by JavaScript");
</script>
</body>

</html>

Using an External JavaScript


If you want to run the same JavaScript on several pages, without having to write the same
script on every page, you can write a JavaScript in an external file.

Save the external JavaScript file with a .js file extension.

Note: The external script cannot contain the <script></script> tags!

To use the external script, point to the .js file in the "src" attribute of the <script> tag:

<html>
<head>
<script type="text/javascript" src="xxx.js"></script>
</head>
<body>
</body>
</html>

Note: Remember to place the script exactly where you normally would write the script!
JavaScript is a sequence of statements to be executed by the browser.

JavaScript is Case Sensitive


Unlike HTML, JavaScript is case sensitive - therefore watch your capitalization closely
when you write JavaScript statements, create or call variables, objects and functions.

JavaScript Statements
A JavaScript statement is a command to a browser. The purpose of the command is to tell
the browser what to do.

36
Web Technology Chapter- Introduction

This JavaScript statement tells the browser to write "Hello Dolly" to the web page:

document.write("Hello Dolly");

It is normal to add a semicolon at the end of each executable statement. Most people think
this is a good programming practice, and most often you will see this in JavaScript
examples on the web.

The semicolon is optional (according to the JavaScript standard), and the browser is
supposed to interpret the end of the line as the end of the statement. Because of this you
will often see examples without the semicolon at the end.

Note: Using semicolons makes it possible to write multiple statements on one line.

JavaScript Code
JavaScript code (or just JavaScript) is a sequence of JavaScript statements. Each statement
is executed by the browser in the sequence they are written. Following example will write a
heading and two paragraphs to a web page:

Example

<script type="text/javascript">
document.write("<h1>This is a heading</h1>");
document.write("<p>This is a paragraph.</p>");
document.write("<p>This is another paragraph.</p>");
</script>

JavaScript Blocks
JavaScript statements can be grouped together in blocks. Blocks start with a left curly
bracket {, and ends with a right curly bracket }. The purpose of a block is to make the
sequence of statements execute together. Following example will write a heading and two
paragraphs to a web page:

Example

<script type="text/javascript">
{
document.write("<h1>This is a heading</h1>");
document.write("<p>This is a paragraph.</p>");
document.write("<p>This is another paragraph tested at pmc.</p>");
}
</script>

The example above is not very useful. It just demonstrates the use of a block. Normally a
block is used to group statements together in a function or in a condition (where a group of
statements should be executed if a condition is met).

37
Web Technology Chapter- Introduction

JavaScript Variables
As with algebra, JavaScript variables are used to hold values or expressions. A variable can
have a short name, like x, or a more descriptive name, like carname.

Rules for JavaScript variable names:


 Variable names are case sensitive (y and Y are two different variables)
 Variable names must begin with a letter or the underscore character

Note: Because JavaScript is case-sensitive, variable names are case-sensitive.

Declaring (Creating) JavaScript Variables


Creating variables in JavaScript is most often referred to as "declaring" variables. You can
declare JavaScript variables with the var statement: var x;

var carname;

After the declaration shown above, the variables are empty (they have no values yet).
However, you can also assign values to the variables when you declare them:

var x=5;
var carname="Volvo";

After the execution of the statements above, the variable x will hold the value 5, and
carname will hold the value Volvo.

Note: When you assign a text value to a variable, use quotes around the value.

Assigning Values to Undeclared JavaScript Variables


If you assign values to variables that have not yet been declared, the variables will
automatically be declared.

These statements:

x=5;
carname="Volvo";

have the same effect as:

var x=5;
var carname="Volvo";

Redeclaring JavaScript Variables


If you redeclare a JavaScript variable, it will not lose its original value.
var x=5;
var x;

38
Web Technology Chapter- Introduction

After the execution of the statements above, the variable x will still have the value of 5.
The value of x is not reset (or cleared) when you redeclare it.

JavaScript Arithmetic
As with algebra, you can do arithmetic operations with JavaScript variables:
y=x-5;
z=y+5;

Comparison Operators
Comparison operators are used in logical statements to determine equality or difference
between variables or values.

Given that x=5, the table below explains the comparison operators:

Operator Description Example


== is equal to x==8 is false
=== is exactly equal to (value and type) x===5 is true
x==="5" is false
!= is not equal x!=8 is true
> is greater than x>8 is false
< is less than x<8 is true
>= is greater than or equal to x>=8 is false
<= is less than or equal to x<=8 is true

Logical Operators
Logical operators are used to determine the logic between variables or values. Given
that x=6 and y=3, the table below explains the logical operators:
Operator Description Example
&& And (x < 10 && y > 1) is true
|| Or (x==5 || y==5) is false
! Not !(x==y) is true

Conditional Operator
JavaScript also contains a conditional operator that assigns a value to a variable based on
some condition.

Syntax
variablename=(condition)?value1:value2

39
Web Technology Chapter- Introduction

Example
greeting=(visitor=="PRES")?"Dear President ":"Dear ";

If the variable visitor has the value of "PRES", then the variable greeting will be assigned
the value "Dear President " else it will be assigned "Dear".

Flow Control
• Conditional statements are used to perform different actions based on different
conditions.
• In JavaScript we have the following conditional statements:
• if statement - use this statement to execute some code only if a specified condition
is true
• if...else statement - use this statement to execute some code if the condition is true
and another code if the condition is false
• if...else if....else statement - use this statement to select one of many blocks of code
to be executed
• switch statement - use this statement to select one of many blocks of code to be
executed

Looping Structures
• Often when you write code, you want the same block of code to run over and over
again in a row. Instead of adding several almost equal lines in a script we can use
loops to perform a task like this.
• In JavaScript, there are two different kind of loops:
• for - loops through a block of code a specified number of times
• while - loops through a block of code while a specified condition is true

The for Loop


• The for loop is used when you know in advance how many times the script should
run.
Syntax
for (var=startvalue;var<=endvalue;var=var+increment)
{

40
Web Technology Chapter- Introduction

code to be executed
}

Example
<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=5;i++)
{
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>

JavaScript While Loop


• The while loop loops through a block of code while a specified condition is true.
Syntax
• while (var<=endvalue)
{
code to be executed
}
Example
<html>
<body>
<script type="text/javascript">
var i=0;
while (i<=5)
{

41
Web Technology Chapter- Introduction

document.write("The number is " + i);


document.write("<br />");
i++;
}
</script>
</body>
</html>
Javascript do while loop

The do...while loop is a variant of the while loop. This loop will execute the block of
code ONCE, and then it will repeat the loop as long as the specified condition is true.
Syntax
do
{
code to be executed
}
while (var<=endvalue);

Example
The example below uses a do...while loop. The do...while loop will always be executed
at least once, even if the condition is false, because the statements are executed before
the condition is tested:
<html>
<body>
<script type="text/javascript">
var i=0;
do
{
document.write("The number is " + i);
document.write("<br />");
i++;

42
Web Technology Chapter- Introduction

}
while (i<=5);
</script>
</body>
</html>

The Break Statement


The break statement will break the loop and continue executing the code that follows
after the loop (if any).
<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=10;i++)
{
if (i==3)
{
break;
}
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>

Javascript for ….. in statement

The for...in statement loops through the elements of an array or through the properties of
an object.

43
Web Technology Chapter- Introduction

Syntax
for (variable in object)
{
code to be executed
}
Note: The code in the body of the for...in loop is executed once for each element/property.

Example: Use the for...in statement to loop through an array:


<html>
<body>
<script type="text/javascript">
var x;
var mycars = new Array();
mycars[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = "BMW";
for (x in mycars)
{
document.write(mycars[x] + "<br />");
}
</script>
</body>
</html>

Functions
• A function is simply a block of code with a name, which allows the block of code
to be called by other components in the scripts to perform certain tasks.
• Functions can also accept parameters that they use complete their task.
• JavaScript actually comes with a number of built-in functions to accomplish a
variety of tasks.

44
Web Technology Chapter- Introduction

Creating Custom Functions


• In addition to using the functions provided by javaScript, you can also create and
use your own functions.
• General syntax for creating a function in JavaScript is as follows:
function name_of_function(argument1,argument2,…arguments)
{
…………………………………………
//Block of Code
…………………………………………
}

Calling functions
• There are two common ways to call a function: From an event handler and from
another function.
• Calling a function is simple. You have to specify its name followed by the pair of
parenthesis.
<SCRIPT TYPE="TEXT/JAVASCRIPT">
name_of_function(argument1,argument2,…arguments)
</SCRIPT>

Example

<html>
<head> <title>PMC</title>
<Script Language="JavaScript">
function welcomeMessage()
{
document.write("Welcome to Patan Campus!");
}
</Script>
</head>

45
Web Technology Chapter- Introduction

<body>
<h1>Patan Multiple Campus CSIT</h1>
<h3>Testing the function in PMC</h3>
<Script Language="JavaScript">
welcomeMessage();
</Script>
</body>
</html>

Popup Boxes

Alert Box:
An alert box is often used if you want to make sure information comes through to the user.
When an alert box pops up, the user will have to click "OK" to proceed.

Syntax
alert("sometext");

Example
<html>
<head>
<script type="text/javascript">
function show_alert()
{
alert("I am an alert box!");
}
</script>
</head>
<body>
<input type="button" onclick="show_alert()" value="Show alert box" />
</body>
</html>

46
Web Technology Chapter- Introduction

Confirmation Box:
A confirm box is often used if you want the user to verify or accept something. When a
confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed. If the
user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns false.

Syntax
confirm("sometext");

Example
<html>
<head>
<script type="text/javascript">
function show_confirm()
{
var r=confirm("Press a button");
if (r==true)
{
document.write("You pressed OK!");
}
else
{
document.write("You pressed Cancel!");
}
}
</script>
</head>
<body>
<input type="button" onclick="show_confirm()" value="Show confirm box" />
</body>
</html>

47
Web Technology Chapter- Introduction

Prompt Box:
A prompt box is often used if you want the user to input a value before entering a page.
When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed
after entering an input value. If the user clicks "OK" the box returns the input value. If the
user clicks "Cancel" the box returns null.

Syntax
prompt("sometext","defaultvalue");

Example
<html>
<head>
<script type="text/javascript">
var name=prompt("Please enter your name",“Rajendra");
</script>
</head>
<body>
<script type="text/javascript">
document.write("Hello "+name + "You have worked will with variables");
</script>
</body>
</html>

JavaScript objects

JavaScript is an Object Oriented Programming (OOP) language. An OOP language allows


you to define your own objects and make your own variable types. An object is just a
special kind of data. An object has properties and methods.

Properties: Properties are the values associated with an object.


Methods: Methods are the actions that can be performed on objects.

48
Web Technology Chapter- Introduction

Array Object in JavaScript

An array is a special variable, which can hold more than one value, at a time. An array can
hold all your variable values under a single name. And you can access the values by
referring to the array name. Each element in the array has its own ID so that it can be easily
accessed. The following code creates an Array object called myCars:

var myCars=new Array();


There are three ways of adding values to an array (you can add as many values as you need
to define as many variables you require).

1.) Conventional array: The classic conventional array looks like the following:

var myCars=new Array();


myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";

You can expand and contract the array as desired, by adding new array elements. Note that
like in most other programming languages, the first array element should have an index
number of 0.

With a conventional array, you have the option of presetting the array's length when
defining it, by passing in a numeric integer into the Array() constructor:
var myCars=new Array(3);
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";

2.) Condensed array: The second way of defining an array is called a condensed array,
and differs from the above simply in that it allows you to combine the array and array
elements definitions into one step:

49
Web Technology Chapter- Introduction

var myCars=new Array("Saab","Volvo","BMW");

This is convinient if you know all the array element values in advance.

3.) Literal array: Finally, we arrive at literal arrays. Introduced in JavaScript1.2 and
support by all modern browsers (IE/NS4+), literal arrays sacrafice intuitiveness somewhat
in exchange for tremendous robustness. The syntax looks like:

var myCars=["Saab","Volvo","BMW"];

Literal array with 5 elements (middle 3 with undefined values).


var mystudents=["giri", , , "tulsi"]

As you can see, enclose all the array elements within an outter square bracket ([ ]), each
separated by a comma (,). To create array elements with an initial undefined value just
enter a comma (,) as shown in the second example above.

Literal arrays really shine when it comes to defining multi-dimensional arrays. It is as easy
as adding containing brackets ([ ]) within the outermost bracket. For example:

var myarray=[["Subash", "Pandey", "Gautam"], Kalanki, Sanepa]

Here the first array element is actually a two dimensional array in itself containing various
cities names. To access LA, then, you'd use the syntax:

myarray[0][1] //returns "Pandey"

Note: If you specify numbers or true/false values inside the array then the type of variables
will be numeric or Boolean instead of string.

Accessing the Array

You can refer to a particular element in an array by referring to the name of the array and
the index number. The index number starts at 0. In above initialized array, the code line
document.write(myCars[0]); will result in the following output: Saab

50
Web Technology Chapter- Introduction

To modify a value in an existing array, just add a new value to the array with a specified
index number:
myCars[0]="Opel";
Now, the following code line:
document.write(myCars[0]); will result in the following output: Opel.

Some methods associated with array

• concat( ): Joins two or more arrays, and returns a copy of the joined arrays
• join( ): Joins all elements of an array into a string
• pop( ): Removes the last element of an array, and returns that element
• push( ): Adds new elements to the end of an array, and returns the new length
• reverse( ): Reverses the order of the elements in an array
• shift( ): Removes the first element of an array, and returns that element
• sort( ): Sorts the elements of an array
• toString( ): Converts an array to a string, and returns the result
• unshift( ): Adds new elements to the beginning of an array, and returns the new
length

Example
Concat( ) : Joining Two Arrays

<script type="text/javascript">
var parents = ["Giri", "Pari"];
var children = ["Cactus", "Rose"];
var family = parents.concat(children);
document.write(family);
</script>

The output will be :

51
Web Technology Chapter- Introduction

Giri, Pari, Cactus, Rose

String Object in JavaScript

The String object is used to manipulate a stored piece of text. String objects are created
with new String().

Syntax
var txt = new String(string);or more simply:
var txt = string;

Some methods associated with String object:


 toLowerCase( ): Converts a string to lowercase letters
 toUpperCase( ): Converts a string to uppercase letters
 concat( ): Joins two or more strings, and returns a copy of the joined strings
 charAt( ): Returns the character at the specified index
 indexOf( ): Returns the position of the first found occurrence of a specified value
in a string
 replace( ): Searches for a match between a substring (or regular expression) and a
string, and replaces the matched substring with a new substring

Examples

In the following example we are using the length property of the String object to return the
number of characters in a string:

<script type="text/javascript">
var txt="Hello World!";
document.write(txt.length);
</script>
The output of the code above will be: 12

52
Web Technology Chapter- Introduction

In the following example we are using the toUpperCase( ) method of the String object to
display a text in uppercase letters:

<script type="text/javascript">
var str="hello its me webtech!";
document.write(str.toUpperCase());
</script>
The output of the code above will be:
HELLO ITS ME WEBTECH

Example: IndexOf ( ) method

The indexOf( ) method returns the position of the first occurrence of a specified value in a
string. This method returns -1 if the value to search for never occurs. The indexOf( )
method is case sensitive.

Syntax
string.indexOf(searchstring, start)

searchstring: Required. The string to search for.


start: Optional. The start position in the string to start the search. If omitted, the search
starts from position 0

<script type="text/javascript">
var str="Patan world!";
document.write(str.indexOf("d") + "<br />");
document.write(str.indexOf("WORLD") + "<br />");
document.write(str.indexOf("world"));

</script>

Output

53
Web Technology Chapter- Introduction

10
-1
6

Math Object in Javascript

The Math object allows you to perform mathematical tasks. The Math object includes
several mathematical constants and methods. For example
var pi_value=Math.PI;
var sqrt_value=Math.sqrt(16);

Note: Math is not a constructor. All properties and methods of Math can be called by using
Math as an object without creating it.

Properties

• Math.E: Returns Euler's number (approx. 2.718)


• Math.LN2: Returns the natural logarithm of 2 (approx. 0.693)
• Math.LN10: Returns the natural logarithm of 10 (approx. 2.302)
• Math.LOG2E: Returns the base-2 logarithm of E (approx. 1.442)
• Math.LOG10E: Returns the base-10 logarithm of E (approx. 0.434)
• Math.PI: Returns PI (approx. 3.14159)
• Math.SQRT1_2: Returns the square root of 1/2 (approx. 0.707)
• Math.SQRT2: Returns the square root of 2 (approx. 1.414)

Methods

• abs(x): Returns the absolute value of x


• ceil(x): Returns x, rounded upwards to the nearest integer
• floor(x): Returns x, rounded downwards to the nearest integer
• log(x): Returns the natural logarithm (base E) of x

54
Web Technology Chapter- Introduction

• max(x,y,z,...,n): Returns the number with the highest value


• min(x,y,z,...,n): Returns the number with the lowest value
• pow(x,y): Returns the value of x to the power of y
• sqrt(x): Returns the square root of x
• random( ): Returns a random number between 0 and 1
• round(x): Rounds x to the nearest integer
• sin(x): Returns the sine of x (x is in radians)
• cos(x): Returns the cosine of x (x is in radians)
• tan(x): Returns the tangent of an angle

Examples
document.write(Math.round(4.7));
Output: 5

document.write(Math.random());
Output: 0.19733826867061233

document.write(Math.floor(Math.random()*6));
Output: 3

Date Object in Javascript

The Date object is used to work with dates and times. Date objects are created with the
Date( ) constructor. We can easily manipulate the date by using the methods available for
the Date object. In the example below we set a Date object to a specific date (14th January
2010):
var myDate=new Date();
myDate.setFullYear(2010,0,14);

And in the following example we set a Date object to be 5 days into the future:

55
Web Technology Chapter- Introduction

var myDate=new Date();


myDate.setDate(myDate.getDate()+5);

Note: If adding five days to a date shifts the month or year, the changes are handled
automatically by the Date object itself!

Methods
getDate() Returns the day of the month (from 1-31)
getDay() Returns the day of the week (from 0-6)
getFullYear() Returns the year (four digits)
getHours() Returns the hour (from 0-23)
getMilliseconds() Returns the milliseconds (from 0-999)
getMinutes() Returns the minutes (from 0-59)
getMonth() Returns the month (from 0-11)
getSeconds() Returns the seconds (from 0-59)
setDate() Sets the day of the month (from 1-31)
setFullYear() Sets the year (four digits)
setHours() Sets the hour (from 0-23)
setMilliseconds() Sets the milliseconds (from 0-999)
setMinutes() Set the minutes (from 0-59)
setMonth() Sets the month (from 0-11)
setSeconds() Sets the seconds (from 0-59)
toString() Converts a Date object to a string

Examples

The Date object is also used to compare two dates. The following example compares
today's date with the 14th January 2010:
var myDate=new Date();
myDate.setFullYear(2010,0,14);

56
Web Technology Chapter- Introduction

var today = new Date();


if (myDate>today)
{
alert("Today is before 15th December 2011");
}
else
{
alert("Today is after 15th January 2011");
}

Examples
<html>
<head>
<script type="text/javascript">
function displayDate()
{
document.getElementById("demo").innerHTML=Date();
}
</script>
</head>
<body>

<h1>My First Web Page</h1>


<p id="demo">This is a paragraph.</p>

<button type="button" onclick="displayDate()">Display Date</button>

</body>
</html>

57
Web Technology Chapter- Introduction

<html>
<body>
<script type="text/javascript">
var d=new Date();
document.write(d);
</script>
</body>
</html>

Example: Displaying the clock


<html>
<head>
<script type="text/javascript">
function startTime()
{
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
// add a zero in front of numbers<10 //m=checkTime(m);

//s=checkTime(s);

document.getElementById('txt').innerHTML=h+":"+m+":"+s;

t=setTimeout('startTime()',1000);

//to concat 0 if i is not double digit


/*function checkTime(i)
{
if (i<10)
{

58
Web Technology Chapter- Introduction

i="0" + i;
}
return i;
} */
</script>
</head>
<body onload="startTime()">
<div id="txt"></div>
</body>
</html>

With JavaScript, it is possible to execute some code after a specified time-interval. This is
called timing events It's very easy to time events in JavaScript. The two key methods that
are used are:

 setTimeout() - executes a code some time in the future


 clearTimeout() - cancels the setTimeout()

Note: The setTimeout() and clearTimeout() are both methods of the HTML DOM Window
object.

The setTimeout() method returns a value. In the syntax defined above, the value is stored in
a variable called t. If you want to cancel the setTimeout() function, you can refer to it using
the variable name. The first parameter of setTimeout() can be a string of executable code,
or a call to a function. The second parameter indicates how many milliseconds from now
you want to execute the first parameter.

Note: There are 1000 milliseconds in one second.

In above example the function startTime( ) get executed after each second, showing the
content of div tag getting refreshed each time so as to display the clock.

User defined objects in JavaScript:

We have seen that JavaScript has several built-in objects, like String, Date, Array, and
more. In addition to these built-in objects, you can also create your own.

An object is just a special kind of data, with a collection of properties and methods.

59
Web Technology Chapter- Introduction

Let's illustrate with an example: A person is an object. Properties are the values associated
with the object. The persons' properties include name, height, weight, age, skin tone, eye
color, etc. All persons have these properties, but the values of those properties will differ
from person to person. Objects also have methods. Methods are the actions that can be
performed on objects. The persons' methods could be eat(), sleep(), work(), play(), etc.

The syntax for accessing a property of an object is:

objName.propName

You can call a method with the following syntax:

objName.methodName()

Note: Parameters required for the method can be passed between the parentheses.

There are different ways to create a new object:

1. Create a direct instance of an object

The following code creates an new instance of an object, and adds four properties to it:

personObj=new Object();
personObj.firstname="Jyoti";
personObj.lastname="Joshi";
personObj.age=25;
personObj.eyecolor="black";

alternative syntax (using object literals):

personObj={firstname:"Jyoti", lastname:"Joshi", age:25, eyecolor:"black"};

Adding a method to the personObj is also simple. The following code adds a method called
eat() to the personObj:

personObj.eat=eat;

function eat( )
{
// code for the function
}

60
Web Technology Chapter- Introduction

2. Create an object constructor

Create a function that constructs objects:

function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
}

Inside the function you need to assign things to this.propertyName. The reason for all the
"this" stuff is that you're going to have more than one person at a time (which person
you're dealing with must be clear). That's what "this" is: the instance of the object at hand.

Once you have the object constructor, you can create new instances of the object, like this:

var myFather=new person("Ramesh","Joshi",50,"black");


var myMother=new person("Gita","Joshi",48,"blue");

You can also add some methods to the person object. This is also done inside the function:

function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;

this.newlastname=newlastname;
}

Note that methods are just functions attached to objects. Then we will have to write the
newlastname( ) function:

function newlastname(new_lastname)
{
this.lastname=new_lastname;
}

The newlastname( ) function defines the person's new last name and assigns that to the
person. JavaScript knows which person you're talking about by using "this." . So, now you
can write: myMother.newlastname("Joshi").

61
Web Technology Chapter- Introduction

Example: Creating a circle object


<html>
<head>
<script type="text/javascript">
// mycircle object defined
function mycircle(r) {
this.radius = r; this.retArea
= getTheArea;
}
function getTheArea( )
{
return ( Math.PI * this.radius * this.radius );
}
function createcircle ( )
{
//create a mycircle called testcircle wtih radius 10
var testcircle = new mycircle(10);
window.alert( 'The area of the circle is ' + testcircle.retArea );
}
</script>
</head>

<body onLoad="createcircle()"> </body>


</html>

62
Web Technology Chapter- Introduction

HTML Document Object Model

The Document Object Model is a platform- and language-neutral interface that will allow
programs and scripts to dynamically access and update the content, structure and style of
documents. The document can be further processed and the results of that processing can
be incorporated back into the presented page. DOM provides a language-independent,
object-based model for accessing / modifying and adding to these tags.

The HTML DOM defines a standard set of objects for HTML, and a standard way to
access and manipulate HTML documents. All HTML elements, along with their containing
text and attributes, can be accessed through the DOM. The contents can be modified or
deleted, and new elements can be created. The HTML DOM is platform and language
independent. It can be used by any programming language like Java, JavaScript, and
VBScript.

When an HTML page is rendered in a browser, the browser assembles all the elements
(objects) that are contained in the HTML page, downloaded from web-server in its
memory. Once done the browser then renders these objects in the browser window as text,
forms, input boxes, etc. Once the HTML page is rendered in web-browser window, the
browser can no longer recognize individual HTML elements (Objects).

Since the JavaScript enabled browser uses the Document Object Model (DOM), after the
page has been rendered, JavaScript enabled browsers are capable of recognizing individual
objects in an HTML page.

The HTML objects, which belong to the DOM, have a descending relationship with each
other.

The topmost object in the DOM is the Navigator (i.e. Browser) itself. The next level in the
DOM is the browser's Window, and under that are the Documents displayed in Browser's
Window.

DOM
|-> Window
|-> Document
|-> Anchor
|-> Link
|-> Form
|-> Text-box
|-> Text Area
|-> Radio Button
|-> Check Box
|-> Select
|-> Button

……….

63
Web Technology Chapter- Introduction

Fig: HTML DOM Tree Example

The Form Object:

The Form object represents an HTML form. For each <form> tag in an HTML document, a
Form object is created. Forms are used to collect user input, and contain input elements
like text fields, checkboxes, radio-buttons, submit buttons and more. A form can also
contain select menus, textarea, fieldset, legend, and label elements. Forms are used to pass
data to a server.

Form Object Collections

Collection Description
elements[] Returns an array of all elements in a form

Form Object Properties

Property Description
acceptCharset Sets or returns the value of the accept-charset attribute in a form
action Sets or returns the value of the action attribute in a form
enctype Sets or returns the value of the enctype attribute in a form
length Returns the number of elements in a form
method Sets or returns the value of the method attribute in a form
name Sets or returns the value of the name attribute in a form
target Sets or returns the value of the target attribute in a form

64
Web Technology Chapter- Introduction

Form Object Methods

Method Description
reset() Resets a form
submit() Submits a form

Form Object Events

Event The event occurs when...


onreset The reset button is clicked
onsubmit The submit button is clicked

Form Method Property

The method property sets or returns the value of the method attribute in a form. The
method attribute specifies how to send form-data (the form-data is sent to the page
specified in the action attribute).

formObject.method=value

The method property can have one of the following values:

Value Description
Appends the form-data to the URL: URL?name=value&name=value (this
get
is default)
post Sends the form-data as an HTTP post transaction

65
Web Technology Chapter- Introduction

RegExp Object:

A regular expression is an object that describes a pattern of characters. When you search in
a text, you can use a pattern to describe what you are searching for. A simple pattern can be
one single character. A more complicated pattern can consist of more characters, and can
be used for parsing, format checking, substitution and more.

Regular expressions are used to perform powerful pattern-matching and "search-and-


replace" functions on text.

Syntax

var patt=new RegExp(pattern,modifiers);

or more simply:

var patt=/pattern/modifiers;

 pattern specifies the pattern of an expression


 modifiers specify if a search should be global, case-sensitive, etc.

Modifiers: Modifiers are used to perform case-insensitive and global searches. The i
modifier is used to perform case-insensitive matching. The g modifier is used to perform a
global match (find all matches rather than stopping after the first match).

For example:

<html>
<body>

<script type="text/javascript">
var str = "Visit W3Schools";
var patt1 = /w3schools/i;
document.write(str.match(patt1));
</script>

</body>
</html>

The output: W3Schools

<html>
<body>

66
Web Technology Chapter- Introduction

<script type="text/javascript">

var str="Is this all there is?";


var patt1=/is/g;
document.write(str.match(patt1));

</script>

</body>
</html>

The output : is, is

<html>
<body>

<script type="text/javascript">

var str="Is this all there is?";


var patt1=/is/gi;
document.write(str.match(patt1));

</script>

</body>
</html>

The output : Is,is,is

test()

The test() method searches a string for a specified value, and returns true or false,
depending on the result. The following example searches a string for the character "e":

<html>
<body>

<script type="text/javascript">
var patt1=new RegExp("e");

document.write(patt1.test("The best things in life are free"));


</script>

</body>
</html>

67
Web Technology Chapter- Introduction

exec()

The exec() method searches a string for a specified value, and returns the text of the found
value. If no match is found, it returns null. The following example searches a string for the
character "e":

<html>
<body>

<script type="text/javascript">
var patt1=new RegExp("e");

document.write(patt1.exec("The best things in life are


free")); </script>

</body>
</html>

A caret (^) at the beginning of a regular expression indicates that the string being searched
must start with this pattern.

 The pattern ^foo can be found in "food", but not in "barfood".

A dollar sign ($) at the end of a regular expression indicates that the string being searched
must end with this pattern.

 The pattern foo$ can be found in "curfoo", but not in "food"

Number of Occurrences ( ? + * {} )

The following symbols affect the number of occurrences of the preceding character: ?, +,
*, and {}.

A questionmark (?) indicates that the preceding character should appear zero or one times
in the pattern.

 The pattern foo? can be found in "food" and "fod", but not "faod".

A plus sign (+) indicates that the preceding character should appear one or more times in
the pattern.

 The pattern fo+ can be found in "fod", "food" and "foood", but not "fd".

A asterisk (*) indicates that the preceding character should appear zero or more times in
the pattern.

68
Web Technology Chapter- Introduction

 The pattern fo*d can be found in "fd", "fod" and "food".

Curly brackets with one parameter ( {n} ) indicate that the preceding character should
appear exactly n times in the pattern.

 The pattern fo{3}d can be found in "foood" , but not "food" or "fooood".

Curly brackets with two parameters ( {n1,n2} ) indicate that the preceding character should
appear between n1 and n2 times in the pattern.

 The pattern fo{2,4}d can be found in "food","foood" and "fooood", but not "fod" or
"foooood".

Curly brackets with one parameter and an empty second paramenter ( {n,} ) indicate that
the preceding character should appear at least n times in the pattern.

 The pattern fo{2,}d can be found in "food" and "foooood", but not "fod".

Common Characters ( . \d \D \w \W \s \S )

A period ( . ) represents any character except a newline.

 The pattern fo.d can be found in "food", "foad", "fo9d", and

"fo*d". Backslash-d ( \d ) represents any digit. It is the equivalent of [0-9].

 The pattern fo\dd can be found in "fo1d", "fo4d" and "fo0d", but not in "food"
or "fodd".

Backslash-D ( \D ) represents any character except a digit. It is the equivalent of [^0-9].

 The pattern fo\Dd can be found in "food" and "foad", but not in "fo4d".

Backslash-w ( \w ) represents any word character (letters, digits, and the underscore (_) ).

 The pattern fo\wd can be found in "food", "fo_d" and "fo4d", but not in "fo*d".

Backslash-W ( \W ) represents any character except a word character.

 The pattern fo\Wd can be found in "fo*d", "fo@d" and "fo.d", but not in "food".

Backslash-s ( \s) represents any whitespace character (e.g, space, tab, newline, etc.).

 The pattern fo\sd can be found in "fo d", but not in "food".

Backslash-S ( \S ) represents any character except a whitespace character.

69
Web Technology Chapter- Introduction

 The pattern fo\Sd can be found in "fo*d", "food" and "fo4d", but not in "fo d".

Form Validation:

Form validation is the process of checking that a form has been filled in correctly before it
is processed. For example, if your form has a box for the user to type their email address,
you might want your form handler to check that they've filled in their address before you
deal with the rest of the form.

There are two main methods for validating forms: server-side (using CGI scripts, ASP,
etc), and client-side (usually done using JavaScript). Server-side validation is more secure
but often more tricky to code and it also increases load of server computer, whereas client-
side (JavaScript) validation is easier to do and quicker too (the browser doesn't have to
connect to the server to validate the form, so the user finds out instantly if they've missed
out that required field!) and it also decreases the load of server computer and hence server
computer can focus on business logic processing.

Form Validation - Checking for Non-Empty

This has to be the most common type of form validation. You want to be sure that your
visitors enter data into the HTML fields you have "required" for a valid submission. Below
is the JavaScript code to perform this basic check to see if a given HTML input is empty or
not.

<script type='text/javascript'>
function notEmpty()
{
var v= document.getElementById('elem').value;
if(v.length == 0)
{
alert("Field should not be empty:");
document.getElementById('elem').value=” ”;
document.getElementById('elem').focus();

70
Web Technology Chapter- Introduction

}
}
</script>
<form>
Required Field: <input type='text' id='elem'/>
<input type='button' onclick="notEmpty()" value='Check'/>
</form>

Form Validation - Checking for All Numbers


If someone is entering a credit card, phone number, zip code, similar information you want
to be able to ensure that the input is all numbers. The quickest way to check if an input's
string value is all numbers is to use a regular expression /^[0-9]+$/ that will only match if
the string is all numbers and is at least one character long. <script type='text/javascript'>

function validate()
{
var patt=/^[0-9]+$/;
var v= document.getElementById('elem').value;
if(v.match(patt))
{
alert("valid entry");
}
else
{
alert("Invalid entry:");
document.getElementById('elem').value="";
document.getElementById('elem').focus();
}
}
</script>
<form>

71
Web Technology Chapter- Introduction

Required Field: <input type='text' id='elem'/>


<input type='button' onclick="validate()" value='Check'/>
</form>

Form Validation - Checking for All Letters


If we wanted to see if a string contained only letters we need to specify an expression that
allows for both lowercase and uppercase letters: /^[a-zA-Z]+$/ . <script
type='text/javascript'>
function validate()
{
var patt=/^[a-zA-Z]+$/;
var v= document.getElementById('elem').value;
if(v.match(patt))
{
alert("valid entry");
}
else
{
alert("Invalid entry:");
document.getElementById('elem').value="";
document.getElementById('elem').focus();
}
}
</script>
<form>
Required Field: <input type='text' id='elem'/>
<input type='button' onclick="validate()" value='Check'/>
</form>

72
Web Technology Chapter- Introduction

Form Validation - Restricting the Length


Being able to restrict the number of characters a user can enter into a field is one of the best
ways to prevent bad data. Below we have created a function that checks for length of input.

<script type='text/javascript'>
function validate()
{
var minlen=6;
var v= document.getElementById('elem').value;
if(v.length<6)
{
alert("User ID must have at least 6 Characters");
document.getElementById('elem').value="";
document.getElementById('elem').focus();
}
else
{
alert("Valid entry:");

}
}
</script>
<form>
User ID: <input type='text' id='elem'/>
<input type='button' onclick="validate()" value='Check'/>
</form>

Form Validation - Selection Made


To be sure that someone has actually selected a choice from an HTML select input you can
use a simple trick of making the first option as helpful prompt to the user and a red flag to
you for your validation code. By making the first option of your select input something

73
Web Technology Chapter- Introduction

like "Please Choose" you can spur the user to both make a selection and allow you to check
to see if the default option "Please Choose" is still selected when he/she submit the form.

<script type='text/javascript'>
function validate()
{
var si=document.getElementById('con').selectedIndex;
var v= document.getElementById('con').options[si].text;
if(v=="Please Choose")
{
alert("You must choose the country");

}
else
{
alert("Your Country is:"+v);

}
}
</script>
<form>
Select Country: <select id='con'>
<option>Please Choose</option> <option>Nepal</option>
<option>India</option> <option>China</option>
</select>
<input type='button' onclick='validate()'
value='Check'/> </form>

74
Web Technology Chapter- Introduction

Validating radio buttons


Radio buttons are used if we want to choose any one out of many options such as gender.
In such case any one of the radio button must be selected. We can validate radio button
selection as below:
<script type='text/javascript'>
function validate()
{
var sex=document.getElementsByName("gen");
if(sex[0].checked==false && sex[1].checked==false)
{
alert("You must choose Gender");
}
else
{
if(sex[0].checked==true)
alert("Male");
else
alert("Female");
}
}
</script>
<form>
Select Gender:
<input type=radio name='gen'>Male
<input type=radio name='gen'>Female
<input type='button' onclick='validate()'
value='Check'/> </form>

75
Web Technology Chapter- Introduction

Form Validation - Email Validation


How to check to see if a user's email address is valid? Every email is made up for 5 parts:
1. A combination of letters, numbers, periods, hyphens, plus signs, and/or underscores
2. The at symbol @
3. A combination of letters, numbers, hyphens, and/or periods
4. A period
5. The top level domain (com, net, org, us, gov, ...)
Valid Examples:
[email protected]
[email protected]
[email protected]
Invalid Examples:
 @deleted.net - no characters before the @
[email protected] - invalid character !
 shoes@need_shining.com - underscores are not allowed in the domain name
<script type='text/javascript'>
function validate()
{
var patt=/^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
var v= document.getElementById('elem').value;
if(v.match(patt))
{
alert("valid Email");
}
else
{
alert("Invalid Email"); document.getElementById('elem').value="";
document.getElementById('elem').focus();
}
}
</script>

76
Web Technology Chapter- Introduction

<form>
Email ID: <input type='text' id='elem'/>
<input type='button' onclick="validate()" value='Check'/>
</form>

Handling Cookies in JavaScript:

A cookie is a variable that is stored on the visitor's computer. Each time the same computer
requests a page with a browser, it will send the cookie too. With JavaScript, you can both
create and retrieve cookie values. A cookie is nothing but a small text file that's stored in
your browser. It contains some data:

1. A name-value pair containing the actual data


2. An expiry date after which it is no longer valid
3. The domain and path of the server it should be sent to

As soon as you request a page from a server to which a cookie should be sent, the cookie is
added to the HTTP header. Server side programs can then read out the information and
decide that you have the right to view the page you requested. So every time you visit the
site the cookie comes from, information about you is available. This is very nice
sometimes, at other times it may somewhat endanger your privacy. Cookies can be read by
JavaScript too. They're mostly used for storing user preferences.

Examples of cookies:

 Name cookie - The first time a visitor arrives to your web page, he or she must fill
in her/his name. The name is then stored in a cookie. Next time the visitor arrives at
your page, he or she could get a welcome message like "Welcome John Doe!" The
name is retrieved from the stored cookie
 Password cookie - The first time a visitor arrives to your web page, he or she must
fill in a password. The password is then stored in a cookie. Next time the visitor
arrives at your page, the password is retrieved from the cookie

77
Web Technology Chapter- Introduction

 Date cookie - The first time a visitor arrives to your web page, the current date is
stored in a cookie. Next time the visitor arrives at your page, he or she could get a
message like "Your last visit was on Tuesday August 11, 2005!" The date is
retrieved from the stored cookie
 And so on.

document.cookie:

Cookies can be created, read and erased by JavaScript. They are accessible through the
property document.cookie. Though you can treat document.cookie as if it's a string, it isn't
really, and you have only access to the name-value pairs. If you want to set a cookie for
this domain with a name-value pair 'ppkcookie1=testcookie' that expires in seven days
from the moment you should write this sentence,
document.cookie = “ppkcookie1=testcookie; expires=Thu, 2 Aug 2001 20:47:11 UTC;
path=/”
1. First the name-value pair ('ppkcookie1=testcookie')
2. then a semicolon and a space
3. then the expiry date in the correct format ('expires=Thu, 2 Aug 2001 20:47:11
UTC')
4. again a semicolon and a space
5. then the path (path=/)

Example:

function createCookie(name, value, days) {


if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
}
else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}

function getCookie(c_name) {
if (document.cookie.length > 0) {

78
Web Technology Chapter- Introduction

c_start = document.cookie.indexOf(c_name + "=");


if (c_start != -1) {
c_start = c_start + c_name.length + 1;
c_end = document.cookie.indexOf(";", c_start);
if (c_end == -1) {
c_end = document.cookie.length;
}
return unescape(document.cookie.substring(c_start, c_end));
}
}
return "";
}

More we can set cookie as below with the proper paths, domain and other parameters;

function setCookie(name, value, expires, path, domain)


{

/* Some characters - including spaces - are not allowed in cookies so we escape to


change the value we have entered into a form acceptable to the cookie.*/

var thisCookie = name + "=" + escape(value) +


((expires) ? "; expires=" + expires.toGMTString() : "") +
((path) ? "; path=" + path : "") + ((domain) ? ";
domain=" + domain : "") ;

document.cookie = thisCookie;

Simply we can display cookie in alert box as;

function showCookie()
{
alert(unescape(document.cookie));
}

79
Web Technology Chapter- Introduction

More Example;

<html>
<head>
<script type="text/javascript">
function setCookie()
{
var name="Cookie1";
var value="Jagdish";
var ed=new Date();
ed.setDate(ed.getDate() +2);
document.cookie = name + "=" + value+" ;expires="+ed.toGMTString()+" ;path=/";
}
function getCookie()
{
var l=document.cookie.length;
setCookie();
var ind=document.cookie.indexOf("Cookie1=");
if(ind==-1)
{
alert("Cookie not found");
}
else
{
var n=document.cookie.substring(ind+8,l);
alert("Wel come:"+n);
}
}
</script> </head>
<body>
<input type=button value="setcookie" onclick="setCookie()">
<input type=button value="getcookie" onclick="getCookie()">

80
Web Technology Chapter- Introduction

</body> </html>

Handling runtime errors in JavaScript:

An exception is an error that occurs at runtime due to an illegal operation during


execution. Examples of exceptions include trying to reference an undefined variable, or
calling a non-existent method. Syntax errors occur when there is a problem with your
JavaScript syntax. Consider the following examples of syntax errors versus exceptions:

alert("I am missing a closing parenthesis //syntax error


alert(x) //exception assuming "x" isn't defined yet
undefinedfunction() //exception

It is almost 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. Normally whenever the browser runs into an exception somewhere in a
JavaScript code, it displays an error message to the user while aborting the execution of the
remaining code. There are mainly two ways of trapping errors in JavaScript.
 Using try…catch statement
 Using onerror event

Using try…catch statement:


The try..catch statement has two blocks in it: try block and 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:

81
Web Technology Chapter- Introduction

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
}

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.
<html>
<head>
<script type="text/javascript">
var txt="";
function message()
{
try
{
adddlert("Welcome guest!");
alert("test");
}
catch(err)
{
txt="There was an error on this page.\n\n";
txt+="Click OK to continue viewing this page,\n";
txt+="or Cancel to return to the home page.\n\n";

82
Web Technology Chapter- Introduction

if(!confirm(txt))
{
document.location.href="http://www.w3schools.com/";
}
}
}
</script>
</head>
<body>
<input type="button" value="View message" onclick="message()" />
</body>
</html>

There is another statement called throw available in JavaScript that can be used along with.
try…catch statements to throw exceptions and thereby helps in generating. General syntax
of this throw statement is as follows:
throw(exception)
<html>
<body>
<script type="text/javascript">
try
{
var a=10;
var b=0;
if(b==0)
{
throw "Division by zero!!!!"
}
}

catch(err)
{
alert(err);
}
</script>
</body>
</html>

83
Web Technology Chapter- Introduction

Although finally is not used as often as catch, it can often be useful. The finally clause is
guaranteed to be executed if any portion of the try block is executed, regardless of how the
code in the try block completes. It is generally used to clean up after the code in the try
clause. If an exception occurs in the try block and there is an associated catch block to
handle the exception, control transfers first to the catch block and then to the finally block.
If there is no local catch block to handle the exception, control transfers first to the finally.

<head>
<script type="text/javascript">
<!--
function myFunc()
{
var a = 100;
try
{
alert("Value of variable a is : " + a );
}
catch ( e )
{
alert("Error: " + e.description );
}
finally
{
alert("Finally block will always execute!" );
}
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>

84
Web Technology Chapter- Introduction

<form>
<input type="button" value="Click Me" onclick="myFunc()" />
</form>
</body>
</html>

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 functionname()
{
//Error Handling Code
}

Example:
<html>
<head>
<script type="text/javascript">
onerror=exfoerr
var text1=""
function exfoerr(msg,url,line)
{
text1="Error Displayed\n\n"
text1+="Error: " + msg + "\n"
text1+="URL: " + url + "\n"
text1+="Line Number: " + line + "\n\n"
text1+="Click OK to continue.\n\n"
alert(text1)

85
Web Technology Chapter- Introduction

return true
}
function display()
{
addxlert("Click to Proceed!!!!")
}
</script>
</head>
<body>
<input type="button" value="View message"
onclick="display()" />
</body>
</html>

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)

86

You might also like