JavaScript PDF
JavaScript PDF
Learning objectives:
After the Completion of this unit you should be able to know
The importance of JavaScript
Features of Java Script
Writing format in Java Script
Variable declaration & initialization
Types of operators
Conditional statements
Repetitive statements
Dialog box in Java Script
Structure
5.1.1 Definition:
5.1.2 History
Page 1
5.1.5 Advantages of JavaScript.
The advantages of using JavaScript are:
Less server interaction: You can validate user input before
sending the page off to the server. This saves server traffic,
which means fewer loads on your server.
Immediate feedback to the visitors: They don't have to wait for
a page reload to see if they have forgotten to enter something.
Increased interactivity: You can create interfaces that react
when the user hovers over them with a mouse or activates them
via the keyboard.
Richer interfaces: You can use JavaScript to include such items
as drag-and-drop components and sliders to give a Rich
Interface to your site visitors.
5.1.6 Browser Compatibility.
<Script ...>
JavaScript code
</script>
Language: This attribute specifies what scripting language you are using.
Typically, its value will be javascript. Although recent versions of HTML
(and XHTML, its successor) have phased out the use of this attribute.
Type: This attribute is what is now recommended to indicate the scripting
language in use and its value should be set to "text/javascript".So your
JavaScript syntax will look as follows.
Page 2
Syntax
<script language="javascript" type="text/javascript">
JavaScript code
</script>
All the modern browsers come with built-in support for JavaScript. Frequently,
you may need to enable or disable this support manually. This chapter explains
the procedure of enabling and disabling JavaScript support in your browsers:
Internet Explorer, Firefox, chrome, and Opera.
5.3.1 JavaScript in Internet Explorer
Here are the steps to turn on or turn off JavaScript in Internet Explorer:
1. Follow Tools Internet Options from the menu.
2. Select Security tab from the dialog box.
3. Click the Custom Level button.
4. Scroll down till you find the Scripting option.
5. Select Enable radio button under Active scripting.
6. Finally click OK and come out.
Tips: To disable JavaScript support in your Internet Explorer, you need to select
Disable radio button under Active scripting.
5.3.2 JavaScript in Firefox
Page 3
5.3.4 JavaScript in Opera
Tips: To disable JavaScript support in Opera, you should not select the Enable
JavaScript checkbox.
5.4Placing JavaScript
Page 4
5.4.2 JavaScript in <body>...</body> Section
If you need a script to run as the page loads so that the script generates content in
the page, then the script goes in the <body> portion of the document. In this case,
you would not have any function defined using JavaScript. Take a look at the
following code.
Page 5
5.4.3 JavaScript in <body> and <head> Sections
You can put your JavaScript code in <head> and <body> section
altogether as follows.
Page 6
5.4.4 JavaScript in External File
You are not restricted to be maintaining identical code in multiple HTML files.
The script tag provides a mechanism to allow you to store JavaScript in an external
file and then include it into your HTML files. Here is an example to show how you
can include an external JavaScript file in your HTML code using script tag and its
src attribute.
<html>
<head>
<script type="text/javascript" src="[Link]" ></script></head>
<body>
……….
……….
</body>
</html>
To use JavaScript from an external file source, you need to write all your
JavaScript source code in a simple text file with the extension ".js" and then
include that file as shown above.
For example, you can keep the following content in [Link] file and then you
can use sayHello function in your HTML file after including the [Link] file.
Function sayHello()
{
alert("Hello World")
}
Page 7
CHECK YOUR PROGRESS 1
Answer:__________________________________________________________
_________________________________________________________________
_________________________________________________________________
Answer:__________________________________________________________
_________________________________________________________________
_________________________________________________________________
Answer:__________________________________________________________
_________________________________________________________________
_________________________________________________________________
Answer:__________________________________________________________
_________________________________________________________________
_________________________________________________________________
Q5. Write the steps to turn on or turn off JavaScript in Internet Explorer.
Answer:__________________________________________________________
_________________________________________________________________
_________________________________________________________________
5.5 Variables
Like many other programming languages, JavaScript has variables. Variables can
be thought of as named containers. You can place data into these containers and
then refer to the data simply by naming the container. Before you use a variable in
a JavaScript program, you must declare it. Variables are declared with the var
keyword as follows.
5.5.1 Definition
Itis a quantity whose value can be change during the execution of the
program.
Page 8
5.5.2 Declaration of variable
Variables are declared with the var keyword as follows.
var money;
var name;
You can also declare multiple variables with the same var keyword as follows:
var money, name;
5.5.3Variable Initialization
Storing a value in a variable is called variable initialization. You can do
variable initialization at the time of variable creation or at a later point in time
when you need that variable. For instance, you might create variable named
money and assign the value 523.50 to it later. For another variable, you can assign
a value at the time of initialization as follows.
Tips:Use the var keyword only for declaration or initialization, once for the life of
any variable name in a document. You should not re-declare same variable twice.
JavaScript is untyped language. This means that a JavaScript variable can hold a
value of any data type. Unlike many other languages, you don't have to tell
JavaScript during variable declaration what type of value the variable will hold.
The value type of a variable can change during the execution of a program and
JavaScript takes care of it automatically. 5.5.4 JavaScript Variable Scope The scope
Global Variables: A global variable has global scope which means it can
be defined anywhere in your JavaScript code.
Page 9
<script type="text/javascript">
var myVar = "global"; // Declare a global variable
function checkscope( )
{
var myVar = "local"; // Declare a local variable
[Link](myVar);
}
</script>
5.6 Operators
5.6.1 Definition
An Operator is a symbol that tells to perform specific operation.
Let us take a simple expression 5 + 3 is equal to 8. Here 5 and 3 are called
operands and „+‟ is called the operator.
Page 10
[Link] Arithmetic Operators
Note: Addition operator (+) works for Numeric as well as Strings. e.g. "a" + 5
will give "a5".
Example
<html>
<body>
<script type="text/javascript">
<!--
var a = 5;
var b = 2;
var c = "Test";
var linebreak = "<br />";
[Link]("a + b = ");
result = a + b;
[Link](result);
[Link](linebreak);
[Link]("a - b = ");
result = a - b;
[Link](result);
[Link](linebreak);
[Link]("a / b = ");
result = a / b;
[Link](result);
[Link](linebreak);
[Link]("a % b = ");
result = a % b;
[Link](result);
[Link](linebreak);
[Link]("a + b + c = ");
result = a + b + c;
[Link](result);
[Link](linebreak);
a = a++;
[Link]("a++ = ");
result = a++;
[Link](result);
[Link](linebreak);
b = b--;
[Link]("b-- = ");
result = b--;
[Link](result);
[Link](linebreak);
//-->
</script>
<p>Set the variables to different values and then try...</p>
Page 11
</body>
</html>
Page 12
3 > Greater
than
Checks if the
value of the left
operand is greater
than the value of A>B False
the right operand,
if yes, then the
condition
becomes true.
4 >= Greater
than or
Equal to
Checks if the
value of the left
operand is greater
than or equal to A>=B False
the value of the
right operand, if
yes, then the
condition
becomes true.
Less
5 < than
Checks if the
value of the left
operand is less
than the value of A<B True
the right operand,
if yes, then the
condition
becomes true.
Less
6 <= than
or
Equal to
Checks if the
value of the left
operand is less
than or equal to A<=B True
the value of the
right operand, if
yes, then the
condition
becomes true.
Page 13
Example
<html>
<body>
<script type="text/javascript">
<!--
var a = 10;
var b = 20;
var linebreak = "<br />";
[Link]("(a == b) => ");
result = (a == b);
[Link](result);
[Link](linebreak);
[Link]("(a < b) => ");
result = (a < b);
[Link](result);
[Link](linebreak);
[Link]("(a > b) => ");
result = (a > b);
[Link](result);
[Link](linebreak);
[Link]("(a != b) => ");
result = (a != b);
[Link](result);
[Link](linebreak);
[Link]("(a >= b) => ");
result = (a >= b);
[Link](result);
[Link](linebreak);
[Link]("(a <= b) => ");
result = (a <= b);
[Link](result);
[Link](linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>
Page 14
This code will produce the following results:
Sl Operator Description
No
&& Logical AND
1
If both the operands are
non-zero, then the
condition becomes true.
2 || Logical OR
If any of the two
operands are non-zero,
then the condition
becomes true.
3 ! Logical NOT
Reverses the logical
state of its operand. If a
condition is true, then
the
NOT Logical
operator will make it
false.
Page 15
Example
<html>
<body>
<script type="text/javascript">
<!--
var a = true;
var b = false;
varlinebreak = "<br />";
[Link]("(a && b) => ");
result = (a && b);
[Link](result);
[Link](linebreak);
[Link]("(a || b) => ");
result = (a || b);
[Link](result);
[Link](linebreak);
[Link]("!(a && b) => ");
result = (!(a && b));
[Link](result);
[Link](linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>
This code will produce the following results:
Page 16
[Link] Assignment Operators
Sl Operator Description
No
= Simple Assignment
1
Assigns values from the right side operand to
the left side operand
Ex: C = A + B will assign the value of A + B
into C
2 += Add and Assignment
It adds the right operand to the left operand and
assigns the result to the left operand.
Ex: C += A is equivalent to C = C + A
3 -= Subtract and Assignment
It subtracts the right operand from the left
operand and assigns the result to the left
operand.
Ex: C -= A is equivalent to C = C - A
Multiply and Assignment
4 *=
It multiplies the right operand with the left
operand and assigns the result to the left
operand.
Ex: C *= A is equivalent to C = C * A
Divide and Assignment)
5 /= It divides the left operand with the right operand
and assigns the result to the left operand.
Ex: C /= A is equivalent to C = C / A
6 %= Modules and Assignment
It takes modulus using two operands and
assigns the result to the left operand.
Ex: C %= A is equivalent to C = C % A
Note: Same logic applies to Bitwise operators, so they will become <<=, >>=,
>>=, &=, |= and ^=.
Page 17
[Link] Conditional (or ternary) Operator The conditional operator first evaluates
Example
<html>
<body>
<script type="text/javascript">
<!--
var a = 10;
var b = 20;
var linebreak = "<br />";
[Link] ("((a > b) ?100 : 200) => "); result = (a > b) ? 100 : 200;
[Link](result);
[Link](linebreak);
[Link] ("((a < b) ?100 : 200) => ");
result = (a < b) ? 100 : 200;
[Link](result);
[Link](linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>
Page 18
CHECK YOUR PROGRESS 2
Answer:__________________________________________________________
_________________________________________________________________
_________________________________________________________________
Answer:__________________________________________________________
_________________________________________________________________
_________________________________________________________________
5.7 IF….ELSE While writing a program, there may be a situation when you need to
adopt one out
of a given set of paths. In such cases, you need to use conditional statements that
allow your program to make correct decisions and perform right actions.
JavaScript supports conditional statements which are used to perform different
actions based on different conditions. Here we will explain the if…..else
statement.
5.7.1 Flow Chart of if-else
The following flow chart shows how the if-else statement works.
Page 19
5.7.2 if Statement
The „if‟ statement is the fundamental control statement that allows JavaScript to
make decisions and execute statements conditionally.
Syntax
Here a JavaScript expression is evaluated. If the resulting value is true, the given
statement(s) are executed. If the expression is false, then no statement would be
not executed. Most of the times, you will use comparison operators while making
decisions.
Example
The following example to understand how the if statement works.
<html>
<body>
<script type="text/javascript">
<!--
var age = 20;
if( age >=18 ){
[Link]("<b>Qualifies for Election Voting</b>");}
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
Page 20
5.7.3 if..else Statement
The „if...else‟ statement is the next form of control statement that allows
JavaScript to execute statements in a more controlled way.
Syntax
The syntax of an if-else statement is as follows:
if (expression)
{}
else
Statement(s) to be executed if expression is true
{
Statement(s) to be executed if expression is false
}
Here JavaScript expression is evaluated. If the resulting value is true, the given
statement(s) in the „if‟ block, are executed. If the expression is false, then the
given statement(s) in the else block are executed.
Example
The following code to learn how to implement an if-else statement in JavaScript.
<html>
<body>
<script type="text/javascript">
<!--
var age = 15;
if( age >= 18 )
{
[Link]("<b>Qualifies for Election Voting</b>"); }else{
[Link]("<b>Does not qualify for Election Voting</b>");
}
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
This code will produce the following results:
Page 21
5.7.4 if….else….if Statement
The „if...else if...‟ statement is an advanced form of if…else that allows JavaScript
to make a correct decision out of several conditions.
Syntax
The syntax of an if-else-if statement is as follows:
if (expression 1){
Statement(s) to be executed if expression 1 is true }
else if (expression 2){
Statement(s) to be executed if expression 2 is true }
else if (expression 3){
Statement(s) to be executed if expression 3 is true }
else{
Statement(s) to be executed if no expression is true
}
There is nothing special about this code. It is just a series of if statements, where
each if is a part of the else clause of the previous statement. Statement(s) are
executed based on the true condition, if none of the conditions is true, then the
else block is executed.
Example
The following code to learn how to implement an if-else-if statement in
JavaScript.
<html>
<body>
<script type="text/javascript">
<!--
var mark = 92;
if(mark >= 90 ){
[Link]("<b>”Result is Excellent”</b>"); }
else if( mark >=60 ){
[Link]("<b>“Result is 1stClass”</b>"); }
else if( mark>=50 ){
[Link]("<b>“Result is 2ndClass”</b>"); }
else if( mark>=40 ){
[Link]("<b>“Result is 3rdClass”</b>"); }
else{
[Link]("<b>Fail</b>");}
//-->
</script>
<p>set the variable to different value and then try...</p>
</body>
</html>
Page 22
This code will produce the following results:
Page 23
5.8.2 Syntax
The objective of a switch statement is to give an expression to evaluate
and several different statements to execute based on the value of the
expression. The interpreter checks each case against the value of the
expression until a match is found. If nothing matches, a default condition
will be used.
switch (expression)
{
case condition 1: statement(s)
break;
case condition 2: statement(s)
break;
...
case condition n: statement(s)
break;
default: statement(s)
}
The break statements indicate the end of a particular case. If they were omitted,
the interpreter would continue executing each statement in each of the following
cases. Example
5.9 Loops
Iterative statements, also called loop statements, specify certain commands
to be executed repeatedly until some condition is met. The loops are often used to
iterate the values of an array (hence the name) or to work though repetitious
mathematical tasks. It is a command that execute again and again till condition
fulfill.
5.9.1 Types of loop
There are different types of loop used in java script . Some of the loop are
:
Syntax:
Page 25
do {
statement
} while (expression);
For example:
var i = 0;
do {
i += 2;
The while statement is a pretest loop. This means the evaluation of the
escape condition is done before the code inside the loop has been executed.
Because of this, it is possible that the body of the loop is never executed.
Syntax:
while(expression) statement
For example:
i += 2;
The for statement is also a pretest loop with the added capabilities of variable
initialization before entering the loop and defining post loop code to be entered.
The „for‟ loop is the most compact form of looping. It includes the following
three important parts:
The loop initialization where we initialize our counter to a starting value.
The initialization statement is executed before the loop begins.
The test statement which will test if a given condition is true or not. If the
condition is true, then the code given inside the loop will be executed,
otherwise the control will come out of the loop.
The iteration statement where you can increase or decrease your counter.
Page 26
You can put all the three parts in a single line separated by semicolons.
Syntax:
For example:
alert(i);
This code defines a variable i that begins with the value 0. The for loop is entered
only if the conditional expression (i <iCount) evaluates to true, making it possible
that the body of the code might not be executed. If the body is executed, the
postloop expression is also executed, iterating the variable i.
Example
<html>
<body>
<script type="text/javascript">
<!--
var count;
[Link]("Starting Loop" + "<br />");
for(count = 0; count < 5; count++){
[Link]("Current Count : " + count );
[Link]("<br />");
}
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
Output
Page 27
5.10 Functions
A function is a group of reusable code which can be called anywhere in
your program. This eliminates the need of writing the same code again and again.
It helps programmers in writing modular codes. Functions allow a programmer to
divide a big program into a number of small and manageable functions.
Like any other advanced programming language, JavaScript also supports all the
features necessary to write modular code using functions. You must have seen
functions like alert() and write() in the earlier chapters. We were using these
functions again and again, but they had been written in core JavaScript only once.
JavaScript allows us to write our own functions as well. This section explains how
to write your own functions in JavaScript.
5.10.1 Function Definition
Before we use a function, we need to define it. The most common way to define a
function in JavaScript is by using the function keyword, followed by a unique
function name, a list of parameters (that might be empty), and a statement block
surrounded by curly braces.
Syntax
<script type="text/javascript">
<!--
function functionname(parameter-list) {
statements
}
//-->
</script>
Example
Page 28
5.10.2Calling a Function
To invoke a function somewhere later in the script, you would simply need to
write the name of that function as shown in the following code.
<html>
<head>
<script type="text/javascript"> function sayHello()
{
[Link] ("Hello there!");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" onclick="sayHello()" value="Say Hello"> </form>
<p>Use different text in write method and then try...</p> </body>
</html>
Output
5.10.3 Function Parameters Till now, we have seen functions without parameters.
Page 29
<html>
<head>
<script type="text/javascript"> function sayHello(name, age)
{
[Link] (name + " is " + age + " years old.");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" onclick="sayHello('Zara', 7)" value="Say Hello">
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>
Output
5.10.4 The return Statement A JavaScript function can have an optional return
Try the following example. It defines a function that takes two parameters
and concatenates them before returning the resultant in the calling
program.
Page 30
<html>
<head>
<script type="text/javascript"> function concatenate(first, last) {
var full;
full = first + last; return full;
}
function secondFunction() {
var result;
result = concatenate('Zara', 'Ali'); [Link] (result );
} </script> </head> <body> <p>Click the following button to call the
function</p> <form> <input type="button" onclick="secondFunction()"
value="Call Function"> </form> <p>Use different parameters inside the
function and then try...</p> </body> </html>
Example
The following example to learn how to implement nested functions.
<html>
<head>
<script type="text/javascript">
<!--
function hypotenuse(a, b) {
function square(x) { return x*x; }
return [Link](square(a) + square(b));
}
function secondFunction(){
var result;
result = hypotenuse(1,2);
[Link] ( result );
}
//-->
</script>
</head>
Page 31
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" onclick="secondFunction()" value="Call Function">
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>
This is the most frequently used event type which occurs when a user
clicks the left button of his mouse. You can put your validation, warning
etc., against this event type.
Example
<html>
<head>
<script type="text/javascript">
<!--
function sayHello() {
[Link] ("Hello World")
}
//-->
</script>
</head>
<body>
<p> Click the following button and see result</p>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>
Page 32
Output
5.11.2 onsubmitEvent Type onsubmit is an event that occurs when you try to submit
<html>
<head>
<script type="text/javascript">
<!--
function validation() {
all validation goes here
.........
return either true or false
}
//-->
</script>
</head>
<body>
<form method="POST" action="[Link]" onsubmit="return
validate()">
.......
<input type="submit" value="Submit" />
</form>
</body>
</html>
Page 33
5.11.3 onmouseover and onmouseout These two event types will help you create
Page 34
oncontextmenu script Triggers when a context menu
is triggered Triggers on a
ondblclick script mouse double- click
Triggers when an element is
ondrag script dragged
Triggers at the end of a drag
ondragend script operation
Triggers when an element has
ondragenter script been dragged to a valid drop
target
Triggers when an element
ondragleave script leaves a valid drop target
Triggers when an element is
ondragover script being dragged over a valid
drop target
Triggers at the start of a drag
operation
ondragstart script
Triggers
ondrop script when dragged
element is being dropped
ondurationchange script Triggers when the length of
the media is changed
onemptied script Triggers when a
media
resource element suddenly
becomes empty.
onended script Triggers when media has
reach the end
onerror script Triggers when an error occur
onfocus script Triggers when the window
gets focus
onformchange script Triggers when a form changes
onforminput script Triggers when a form gets
onhaschange script user input
Triggers when the document
oninput script has changed
Triggers when an element
oninvalid script gets user input
Triggers when an element is
onkeydown script invalid
Triggers
onkeypress script pressed when a key is
when a key is
Triggers key is
onkeyup script pressed and released
Triggers when a
oncontextmenu script released
Triggers when a context menu
is triggered
Page 35
onload script Triggers when the document
loads Triggers when media
onloadeddata script data is loaded
Triggers when the duration
onloadedmetadata script and other media data of a
media element is loaded
Triggers when the browser
onloadstart script starts to load the media data
Triggers when the message is
onmessage script triggered Triggers when a
mouse button is pressed
onmousedown script Triggers when the mouse
pointer moves
onmousemove script Triggers when the mouse
pointer moves out of an
onmouseout script element
Triggers when the mouse
onmouseover script
pointer moves over an
element
onmouseup script Triggers when a mouse button
is released
onmousewheel script Triggers when the mouse
wheel is being rotated
onoffline script Triggers when the document
goes offline
onoine script Triggers when the document
comes online
ononline script Triggers when the document
comes online
onpagehide script Triggers when the window is
hidden
onpageshow script Triggers when the window
becomes visible
onpause script Triggers when media data is
paused
onplay script Triggers when media data is
going to start playing
5.12 Cookies
Web Browsers and Servers use HTTP protocol to communicate and HTTP
is a stateless protocol. But for a commercial website, it is required to maintain
session information among different pages. For example, one user registration
ends after completing many pages. But how to maintain users' session information
across all the web pages.
Page 36
In many situations, using cookies is the most efficient method of remembering
and tracking preferences, purchases, commissions, and other information
required for better visitor experience or site statistics.
5.12.1 How It Works?
Your server sends some data to the visitor's browser in the form of a cookie. The
browser may accept the cookie. If it does, it is stored as a plain text record on the
visitor's hard drive. Now, when the visitor arrives at another page on your site, the
browser sends the same cookie to the server for retrieval. Once retrieved, your
server knows/remembers what was stored earlier.
Cookies are a plain text data record of 5 variable-length fields:
Expires: The date the cookie will expire. If this is blank, the cookie will
expire when the visitor quits the browser.
Domain: The domain name of your site.
Path: The path to the directory or web page that set the cookie. This may
be blank if you want to retrieve the cookie from any directory or page.
Secure: If this field contains the word "secure", then the cookie may only
be retrieved with a secure server. If this field is blank, no such restriction
exists.
Name=Value: Cookies are set and retrieved in the form of key-value
pairs.
Cookies were originally designed for CGI programming. The data contained in a
cookie is automatically transmitted between the web browser and the web server,
so CGI scripts on the server can read and write cookie values that are stored on
the client.
JavaScript can also manipulate cookies using the cookie property of the
Document object. JavaScript can read, create, modify, and delete the cookies that
apply to the current web page. 5.12.2 Storing Cookies The simplest way to create a
Here the expires attribute is optional. If you provide this attribute with a valid
date or time, then the cookie will expire on a given date or time and thereafter, the
cookies' value will not be accessible.
Note: Cookie values may not include semicolons, commas, or whitespace. For
this reason, you may want to use the JavaScript escape() function to encode the
value before storing it in the cookie. If you do this, you will also have to use the
corresponding unescape() function when you read the cookie value.
Page 37
Example
The following. It sets a customer name in an input cookie.
<html>
<head>
<script type="text/javascript">
<!--
function WriteCookie()
{
if( [Link] == "" ){
alert ("Enter some value!");
return;
}
cookievalue= escape([Link]) + ";";
[Link]="name=" + cookievalue;
[Link] ("Setting Cookies : " + "name=" + cookievalue );
}
//-->
</script>
</head>
<body>
<form name="myform" action="">
Enter name: <input type="text" name="customer"/>
<input type="button" value="Set Cookie" onclick="WriteCookie();"/>
</form>
</body>
</html>
Output
Page 38
Now your machine has a cookie called name. You can set multiple cookies using
multiple key=value pairs separated by comma.
5.12.3 Reading Cookies
Reading a cookie is just as simple as writing one, because the value of the
[Link] object is the cookie. So you can use this string whenever you
want to access the cookie. The [Link] string will keep a list of
name=value pairs separated by semicolons, where name is the name of a cookie
and value is its string value.
You can use strings' split() function to break a string into key and values as
follows: Example
The following example to get all the cookies.
<html>
<head>
<script type="text/javascript">
<!--
function ReadCookie()
{
var allcookies = [Link];
[Link] ("All Cookies : " + allcookies );
// Get all the cookies pairs in an array
cookiearray = [Link](';');
// Now take key value pair out of this array
for(var i=0; i<[Link]; i++){
name = cookiearray[i].split('=')[0];
value = cookiearray[i].split('=')[1];
[Link] ("Key is : " + name + " and Value is : " + value);
}
}
//-->
</script>
</head>
<body>
<form name="myform" action="">
<p> click the following button and see the result:</p>
<input type="button" value="Get Cookie" onclick="ReadCookie()"/>
</form>
</body>
</html>
Note: Here length is a method of Array class which returns the length of an
array. We will discuss Arrays in a separate chapter. By that time, please try to
digest it.
Page 39
Note: There may be some other cookies already set on your machine. The above
code will display all the cookies set on your machine.
5.12.4 Setting Cookies Expiry Date You can extend the life of a cookie beyond the
<html>
<head>
<script type="text/javascript">
<!--
function WriteCookie()
{
var now = new Date();
[Link]( [Link]() + 1 );
cookievalue = escape([Link]) + ";"
[Link]="name=" + cookievalue;
[Link] = "expires=" + [Link]() + ";"
[Link] ("Setting Cookies : " + "name=" + cookievalue );
}
//-->
</script>
</head>
<body>
<form name="formname" action="">
Enter name: <input type="text" name="customer"/>
<input type="button" value="Set Cookie" onclick="WriteCookie()"/>
</form>
</body>
</html>
Sometimes you will want to delete a cookie so that subsequent attempts to read
the cookie return nothing. To do this, you just need to set the expiry date to a time
in the past.
Example
The following example. It illustrates how to delete a cookie by setting its expiry
date to one month behind the current date.
<html>
<head>
<script type="text/javascript">
<!--
Page 40
function WriteCookie()
{
var now = new Date();
[Link]( [Link]() - 1 );
cookievalue = escape([Link]) + ";"
[Link]="name=" + cookievalue;
[Link] = "expires=" + [Link]() + ";"
[Link]("Setting Cookies : " + "name=" + cookievalue );
}
//-->
</script>
</head>
<body>
<form name="formname" action="">
Enter name: <input type="text" name="customer"/>
<input type="button" value="Set Cookie" onclick="WriteCookie()"/>
</form>
</body>
</html>
You can refresh a web page using JavaScript [Link] method. This code
can be called automatically upon an event or simply when the user clicks on a
link. If you want to refresh a web page using a mouse click, then you can use the
following code:
<a href="javascript:[Link](true)">Refresh Page</a>
Page 41
5.13.2 Auto Refresh You can also use JavaScript to refresh the page automatically
after a given time period. Here setTimeout() is a built-in JavaScript function which
can be used to execute another function after a given time interval.
Example
The following example. It shows how to refresh a page after every 5 seconds. You
can change this time as per your requirement.
<html>
<head>
<script type="text/JavaScript">
<!--
function AutoRefresh( t ) {
setTimeout("[Link](true);", t);
}
// -->
</script>
</head>
<body onload="JavaScript:AutoRefresh(5000);">
<p>This page will refresh every 5 seconds.</p>
</body>
</html>
Page 42
Example 2 You canshowanappropriate message to your site visitors before
redirecting them
to a [Link] would need a bit time delay to load a new page. The following
exampleshowshow to implement the same. Here setTimeout() is a built-in
JavaScriptfunction which can be used to execute another function after a given
time interval.
<html>
<head>
<script type="text/javascript">
<!--
function Redirect() {
[Link]="[Link]
}
[Link] ("You will be redirected to our main page in 10
seconds!");
setTimeout('Redirect()', 10000);
//-->
</script>
</head>
<body>
</body>
</html>
Example 3
The following example shows how to redirect your site visitors onto a different
page based on their browsers.
<html>
<head>
<script type="text/javascript">
<!--
var browsername=[Link];
if( browsername == "Netscape" )
{
[Link]="[Link]
}
else if ( browsername =="Microsoft Internet Explorer")
{
[Link]="[Link]
}
else
{
[Link]="[Link]
}
//-->
</script>
</head>
<body> </body></html>
Page 43
5.14 Dialogs
For
example,ifoneinputfield requires to enter some text but the user does not
provideanyinput,thenasa part of validation, you can use an alert box to give a
warningmessage.
Nonetheless,analertboxcan still be used for friendlier messages. Alert box gives
onlyonebutton"OK"toselect and proceed.
Example
<html>
<head>
<scripttype="text/javascript">
<!--
function Warn() {
alert("Thisisawarning message!");
[Link]("This is a warning message!");
}
//-->
</script>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type="button" value="Click Me" onclick="Warn();" />
</form>
</body>
</html>
Output
Page 44
5.14.2 Confirmation Dialog Box A confirmation dialog box is mostly used to take
Example
<html>
<head>
<script type="text/javascript">
<!--
function getConfirmation(){
var retVal = confirm("Do you want to continue ?");
if( retVal == true ){
[Link] ("User wants to continue!");
return true;
}else{
[Link] ("User does not want to continue!");
return false;
}
}
//-->
</script>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type="button" value="Click Me" onclick="getConfirmation();" />
</form>
</body>
</html>
Output
Page 45
5.14.3 Prompt Dialog Box The prompt dialog box is very useful when you want to
<html>
<head>
<script type="text/javascript">
<!--
function getValue(){
var retVal = prompt("Enter your name : ", "your name here");
[Link]("You have entered : " + retVal);
}
//-->
</script>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type="button" value="Click Me" onclick="getValue();" />
</form>
</body>
</html>
Output
Page 46
5.15 Void Keyword Void is an important keyword in JavaScript which can be used
as a unary operator that appears before its single operand, which may be of any type.
This operator specifies an expression to be evaluated without returning a value.
Syntax
Page 47
5.16 Printing WebPages using Java Script Many times you would like to place a
button on your webpage to print the content
of that web page via an actual printer. JavaScript helps you to implement this
functionality using the print function of window object. The JavaScript print
function [Link]() prints the current web page when executed. You can call
this function directly using the onclick event as shown in the following example.
Let us create a file named my_test.html
Example
The following example.
<!DOCTYPE html>
<html>
<body>
<p> hello how are you?<br>
How is your health?<br>
when shall you be meeting me?<br>
</p>
<button id ='togglee' onclick="myFunction()">Print this page</button>
<script>
function myFunction() {
</body>
</html>
Page 48
Output
Step-1
Step-2
Upon clicking the print button.
Page 49
When we click the print button the page is printed.
Step-3
Answer:__________________________________________________________
_________________________________________________________________
Q2. What is a Function?
Answer:_________________________________________________________
________________________________________________________________
Q3. What is Cookies?
Answer:__________________________________________________________
_________________________________________________________________
Q4. What is auto refresh?
Answer:__________________________________________________________
_________________________________________________________________
Q5. Which function is used to print the current webpage?
Answer:__________________________________________________________
_________________________________________________________________
Page 50
5.18 Reference
JavaScript code
</script>
Or
Page 51
JavaScript code
</script>
Q5. Write the steps to turn on or turn off JavaScript in Internet Explorer.
Answer:
Here are the steps to turn on or turn off JavaScript in Internet Explorer:
1. Follow Tools InternetOptions from the menu.
2. Select Security tab from the dialog box.
3. Click the Custom Level button.
4. Scroll down till you find the Scripting option.
5. Select Enable radio button under Active scripting.
6. Finally click OK and come out.
Answer: It is a quantity whose value can be changed during the execution of the
program. It can be declare using var keyword.
Answer:
Iterative statements, also called loop statements, specify certain commands
to be executed repeatedly until some condition is met. Or A statement that execute
again and again till condition fulfill.
Answer:
Page 52
Q3. What is Cookies?
Answer:
Cookies are small files which are stored on a user's computer. They are
designed to hold a modest amount of data specific to a particular client and
website, and can be accessed either by the web server or the client computer. This
allows the server to deliver a page tailored to a particular user, or the page itself
can contain some script which is aware of the data in the cookie and so is able to
carry information from one visit to the website (or related site) to the next.
Answer:
Answer:
The JavaScript print function [Link]() prints the current web page when
executed.
Page 53
Unit -6
Advanced Java Script
Learning objectives:
After the Completion of this unit you should be able to know
Structure
6.12
6.13
6.14
6.15
6.16
6.17
6.18
Page 55
6.1 Working with objects
JavaScript is an Object Oriented Programming (OOP) language. A
programming language can be called object-oriented if it provides four basic
capabilities to developers:
Encapsulation: the capability to store related information, whether data or
methods, together in an object.
Aggregation: the capability to store one object inside another object.
Inheritance: the capability of a class to rely upon another class (or
number of classes) for some of its properties and methods.
Polymorphism: the capability to write one function or method that works
in a variety of different ways.
Object properties can be any of the three primitive data types, or any of the
abstract data types, such as another object. Object properties are usually
variables that are used internally in the object's methods, but can also be
globally visible variables that are used throughout the page. The syntax
for adding a property to an object is:
[Link] = propertyValue;
Example:
The following code gets the document title using the "title" property of the
document object.
Methods are the functions that let the object do something or let something
be done to it. There is a small difference between a function and a method
– at a function is a standalone unit of statements and a method is attached
to an object and can be referenced by the this keyword. Methods are
useful for everything from displaying the contents of the object to the
screen to performing complex mathematical operations on a group of local
properties and parameters. Example: Following is a simple example to show
Page 56
document. write ("This is test");
Page 57
Example 2
This example demonstrates how to create an object with a User-Defined
Function. Here this keyword is used to refer to the object that has been
passed to a function.
<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
function book(title, author){
[Link] = title;
[Link] = author;
}
</script>
</head>
<body>
<script type="text/javascript">
var myBook = new book("Java Script", " Dhruba & Sushanta");
[Link]("Book title is : " + [Link] + "<br>");
[Link]("Book author is : " + [Link] + "<br>");
</script>
</body>
</html>
6.1.6 Defining Methods for an Object
The previous examples demonstrate how the constructor creates the object
and assigns properties. But we need to complete the definition of an object
by assigning methods to it.
Example
<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
// Define a function which will work as a method
function addPrice(amount){
[Link] = amount;
}
function book(title, author){
[Link] = title;
[Link] = author;
[Link] = addPrice; // Assign that method as property.
}
</script>
</head>
<body>
Page 58
<script type="text/javascript">
var myBook = new book("Java Script", "Dhruba & Sushanta");
[Link](100);
[Link]("Book title is : " + [Link] + "<br>");
[Link]("Book author is : " + [Link] + "<br>");
[Link]("Book price is : " + [Link] + "<br>");
</script>
</body>
</html>
referencing an object's
properties or methods. The object specified as an argument to with becomes the
default object for the duration of the block that follows. The properties and
methods for the object can be used without naming the object.
Syntax
The syntax for with object is as follows:
with (object)
{
properties used without the object name and dot
}
Example
The following example.
<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
// Define a function which will work as a method
function addPrice(amount){
with(this){
price = amount;
}
}
function book(title, author){
[Link] = title;
Page 59
[Link] = author;
[Link] = 0;
[Link] = addPrice; // Assign that method as property.
}
</script>
</head>
<body>
<script type="text/javascript">
var myBook = new book("Perl", "Mohtashim");
[Link](100);
[Link]("Book title is : " + [Link] + "<br>");
[Link]("Book author is : " + [Link] + "<br>");
[Link]("Book price is : " + [Link] + "<br>");
</script>
</body>
</html>
6.2 Working with numbers
The Number object represents numerical date, either integers or floating-
point numbers. In general, you do not need to worry about Number objects
because the browser automatically converts number literals to instances of
the number class. Syntax The syntax for creating a number object is as
follows:
In the place of number, if you provide any non-number argument, then the
argument cannot be converted into a number, it returns NaN (Not-a-
Number).
Property Description
MAX_VALUE The largest possible value a number in
JavaScript can have
1.7976931348623157E+308
MIN_VALUE The smallest possible value a number in
NaN JavaScript can have 5E-324
NEGATIVE_INFINITY Equal to a value that is not a number.
POSITIVE_INFINITY A value that is less than MIN_VALUE.
prototype A value that is greater than MAX_VALUE
A static property of the Number object. Use
the prototype property to assign new properties
and methods to the Number object in the
current document
constructor Returns the function that created this object's
instance. By default this is the Number object.
Page 60
[Link] MAX_VALUE
Example:
<html>
<head>
<script type="text/javascript">
<!--
function showValue()
{
var val = Number.MAX_VALUE;
[Link] ("Value of Number.MAX_VALUE : " + val );
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="showValue();"
/>
</form>
</body>
</html>
Output
Page 61
[Link] MIN_VALUE
The Number.MIN_VALUE property belongs to the static Number
object. It represents constants for the smallest possible positive numbers that
JavaScript can work with.
The actual value of this constant is 5 x 10-324.
Syntax
Note: Use the isNaN() global function to see if a value is an NaN value.
Syntax
The syntax to use NaN is:
var val = [Link];
[Link] NEGATIVE_INFINITY
This is a special numeric value representing a value less than
Number.MIN_VALUE. This value is represented as "-Infinity". It resembles an
infinity in its mathematical behavior. For example, anything multiplied by
NEGATIVE_INFINITY is NEGATIVE_INFINITY, and anything divided by
NEGATIVE_INFINITY is zero. Because NEGATIVE_INFINITY is a constant,
it is a read-only property of Number.
Syntax
The syntax to use NEGATIVE_INFINITY is as follows:
var val = Number. NEGATIVE_INFINITY;
[Link] POSITIVE_INFINITY
This is a special numeric value representing any value greater than
Number.MAX_VALUE. This value is represented as "Infinity". It resembles an
infinity in its mathematical behavior. For example, anything multiplied by
POSITIVE_INFINITY is POSITIVE_INFINITY, and anything divided by
POSITIVE_INFINITY is zero. As POSITIVE_INFINITY is a constant, it is a
read-only property of Number.
Syntax
Use the following syntax to use POSITIVE_INFINITY.
var val = Number. POSITIVE_INFINITY;
Page 62
[Link] Prototype
The prototype property allows you to add properties and methods to any object
(Number, Boolean, String and Date etc.).
Note: Prototype is a global property which is available with almost all the objects.
Syntax
Use the following syntax to use Prototype.
[Link] = value
[Link] Constructor
6.2.2 NumberMethods
The Number object contains only the default methods that are a part of
every object's definition.
Method Description
toExponential() Forces a number to display in exponential
notation, even if the number is in the range
in which JavaScript normally uses standard
notation.
Page 63
[Link] to Exponential () This method returns a string representing the number
object in exponential
notation.
Syntax
Its syntax is as follows:
[Link]( [fractionDigits] )
Parameter Details
fractionDigits: An integer specifying the number of digits after the decimal point.
Defaults to as many digits as necessary to specify the number.
Return Value
A string representing a Number object in exponential notation with one digit
before the decimal point, rounded to fractionDigits digits after the decimal point.
If the fractionDigits argument is omitted, the number of digits after the decimal
point defaults to the number of digits necessary to represent the value uniquely.
Example
<html>
<head>
<title>Javascript Method toExponential()</title>
</head>
<body>
<script type="text/javascript">
var num=77.1234;
var val = [Link]();
[Link]("[Link]() is : " + val );
[Link]("<br />");
val = [Link](4);
[Link]("[Link](4) is : " + val );
[Link]("<br />");
val = [Link](2);
[Link]("[Link](2) is : " + val);
[Link]("<br />");
val = [Link]();
[Link]("[Link]()is : " + val );
[Link]("<br />");
val = [Link]();
[Link]("77 .toExponential() is : " + val);
</script>
</body>
</html>
Page 64
[Link] to Fixed ()
This method formats a number with a specific number of digits to the right of the
decimal.
Syntax
Its syntax is as follows:
[Link]( [digits] )
Parameter Details
digits: The number of digits to appear after the decimal point.
Return Value
A string representation of number that does not use exponential notation
and has the exact number of digits after the decimal place.
[Link] toLocaleString ()
This method converts a number object into a human readable string representing
the number using the locale of the environment.
Syntax
Its syntax is as follows:
[Link]()
Return Value
Returns a human readable string representing the number using the locale of the
environment.
[Link] toPrecision ()
This method returns a string representing the number object to the specified
precision.
Syntax
Its syntax is as follows:
[Link]( [ precision ] )
Parameter Details
precision: An integer specifying the number of significant digits.
Return Value
Returns a string representing a Number object in fixed-point or exponential
notation rounded toprecision significant digits.
Page 65
[Link] toString () This method returns a string representing the specified object.
The toString() method parses its first argument, and attempts to return a string
representation in the specified radix (base). Syntax Its syntax is as follows:
[Link]( [radix] ) Parameter Details radix: An integer between 2 and 36
specifying the base to use for representing numeric values.
Return Value
Returns a string representing the specified Number object.
Property Description
constructor Returns a reference to
the Boolean function
that created the
object.
prototype The prototype
property allows you
to add properties and
methods to an object.
6.3.2 constructor ()
Javascript boolean constructor() method returns a reference to the
Boolean function that created the instance's prototype.
Syntax
Use the following syntax to create a Boolean constructor() method.
[Link]()
Return Value
Page 66
Example
<html>
<head>
<title>JavaScript constructor() Method</title>
</head>
<body>
<script type="text/javascript">
var bool = new Boolean( );
[Link]("[Link]() is : " + [Link]);
</script>
</body>
</html>
Output
6.3.4 toSource ()
Javascript boolean toSource() method returns a string representing the source
code of the object.
Syntax
Its syntax is as follows:
[Link]()
Return Value
Returns a string representing the source code of the object.
Page 67
Example
<html>
<head>
<title>JavaScript toSource() Method</title>
</head>
<body>
<script type="text/javascript">
function book(title, publisher, price)
{
[Link] = title;
[Link] = publisher;
[Link] = price;
}
var newBook = new book("Java Script","OSOU Inc",200);
[Link]("[Link]() is : "+ [Link]());
</script>
</body>
</html>
6.3.5 valueOf ()
Javascript boolean valueOf() method returns the primitive value of the specified
boolean object.
Syntax
Its syntax is as follows:
[Link]()
Return Value
Returns the primitive value of the specified boolean object.
Example
The following example.
<html>
<head>
<title>JavaScript toString() Method</title>
</head>
<body>
<script type="text/javascript">
var flag = new Boolean(false);
[Link]( "[Link] is : " + [Link]() );
</script>
</body>
</html>
Page 68
Syntax
Use the following syntax to create a String object:
var val = new String(string);
The string parameter is a series of characters that has been properly encoded.
6.4.1 String Properties
Property Description
constructor Returns a reference to the String function that created the
length
object.
prototype
Returns the length of the string.
The prototype property allows you to add properties and
methods to an object.
6.4.2 Length
Syntax
Use the following syntax to find the length of a string:
[Link]
Return Value
Returns the number of characters in the string.
Example
<html>
<head>
<title>JavaScript String length Property</title>
</head>
<body>
<script type="text/javascript">
var str = new String( "This is string" );
[Link]("[Link] is:" + [Link]);
</script>
</body>
</html>
Output
Page 69
6.4.3 String Methods
Here is a list of the methods available in String object along with their description.
Method Description
charAt() Returns the character at the specified index.
charCodeAt() Returns a number indicating the Unicode value of
the character at the given index.
concat() Combines the text of two strings and returns a
new string.
Returns the index within the calling String object
indexOf()
of the first occurrence of the specified value, or -1
if not found.
Syntax
Its syntax is as follows:
Page 70
[Link]( )
Return Value
Returns a string in uppercase with the current locale.
Example
The following example.
<html>
<head>
<title>JavaScript String toLocaleUpperCase() Method</title>
</head>
<body>
<script type="text/javascript">
var str = "Apples are round, and Apples are Juicy.";
[Link]([Link]( ));
</script>
</body>
</html>
Output
6.5 Array and Array Management The Array object lets you store multiple values
in a single variable. It stores a fixed-size sequential collection of elements of the
same type. An array is used to store a collection of data, but it is often more useful
to think of an array as a collection of variables of the same type. Syntax
The Array parameter is a list of strings or integers. When you specify a single
numeric parameter with the Array constructor, you specify the initial length of the
array. The maximum length allowed for an array is 4,294,967,295. You can create
array by simply assigning values as follows:
Page 71
You will use ordinal numbers to access and to set values inside an array as
follows.
Property Description
constructor Returns a reference to the array function that created the
index
input object.
The property represents the zero-based index of the match
in the string
This property is only present in arrays created by regular
expression matches.
6.5.2 Constructor
JavaScript array constructor property returns a reference to the array function
that created the instance's prototype.
Syntax
Its syntax is as follows:
[Link]
Return Value
Returns the function that created this object's instance.
Example
The following example.
<html>
<head>
<title>JavaScript Array constructor Property</title>
</head>
<body>
<script type="text/javascript">
var arr = new Array( 10, 20, 30 );
[Link]("[Link] is:" + [Link]);
</script>
</body>
</html>
Page 72
6.5.3 Array Methods
Here is a list of the methods of the Array object along with their description.
Method Description
concat() Returns a new array comprised of this
array joined with other array(s) and/or
value(s).
every() Returns true if every element in this
array satisfies the provided testing
function.
filter() Creates a new array with all of the
elements of this array for which the
provided filtering function returns true.
forEach() Calls a function for each element in the
array.
indexOf() Returns the first (least) index of an
element within the array equal to the
specified value, or -1 if none is found.
join() Joins all elements of an array into a
lastIndexOf() string.
Returns the last (greatest) index of an
element within the array equal to the
specified value, or -1 if none is found.
map() Creates a new array with the results of
calling a provided function on every
element in this array.
pop() Removes the last element from an array
push() and
Adds one or more elements to the end of
an array and returns the new length of
the array.
Apply a function simultaneously against
reduce() two values of the array (from left-to-
right) as to reduce it to a single value.
Apply a function simultaneously against
reduceRight() two values of the array (from right-to-
left) as to reduce it to a single value.
Reverses the order of the elements of an
reverse() array -- the first becomes the last, and
the last becomes the first.
Removes the first element from an array
shift() and returns that element.
slice()
some() Extracts a section of an array and returns
a new array.
Returns true if at least one element in
this array satisfies the provided testing
function.
Represents the source code of an object
toSource()
Page 73
sort() Sorts the elements of an array. Adds
splice() and/or removes elements from an array.
Returns a string representing the array
toString() and its elements.
Adds one or more elements to the front
unshift() of an array and returns the new length of
the array.
6.5.4 Concat()
Javascript array concat( ) method returns a new array comprised of this array
joined with two or more arrays.
Syntax
The syntax of concat() method is as follows:
[Link](value1, value2, ..., value n);
Parameter Details
valueN : Arrays and/or values to concatenate to the resulting array.
Return Value
Returns the length of the array.
Example
The following example.
<html>
<head>
<title>JavaScript Array concat Method</title>
</head>
<body>
<script type="text/javascript">
var alpha = ["a", "b", "c"];
var numeric = [1, 2, 3];
var alphaNumeric = [Link](numeric);
[Link]("alphaNumeric : " + alphaNumeric );
</script>
</body>
</html>
Output
Page 74
6.6 Working with Date The Date object is a datatype built into the JavaScript
language. Date objects are
created with the new Date() as shown below. Once a Date object is created, a
number of methods allow you to operate on it. Most methods simply allow you to
get and set the year, month, day, hour, minute, second, and millisecond fields of
the object, using either local time or UTC (universal, or GMT) time.
The ECMA Script standard requires the Date object to be able to represent any
date and time, to millisecond precision, within 100 million days before or after
1/1/1970. This is a range of plus or minus 273,785 years, so JavaScript can
represent date and time till the year 275755.
Syntax
You can use any of the following syntaxes to create a Date object using Date()
constructor. new Date( )
new Date(milliseconds)
new Date(datestring)
new Date(year,month,date[,hour,minute,second,millisecond ])
Note: Parameters in the brackets are always optional.
Here is a description of the parameters:
Page 75
6.6.1 Date Properties
Here is a list of the properties of the Date object along with their description.
Property Description
constructor Specifies the function that creates an object's
prototype
prototype.
The prototype property allows you to add
properties and methods to an object.
6.6.2 Constructor
JavaScript date constructor property returns a reference to the array function that
created the instance's prototype.
Syntax
Its syntax is as follows:
[Link]
Return Value
Returns the function that created this object's instance.
Example
The following example.
<html>
<head>
<title>JavaScript Date constructor Property</title>
</head>
<body>
<script type="text/javascript">
var dt = new Date();
[Link]("[Link] is : " + [Link]);
</script>
</body>
</html>
Here is a list of the methods used with Date and their description.
Method Description
Date() Returns today's date and time
getDate() Returns the day of the month for the specified date
according to local time.
getDay()
Returns the day of the week for the specified date
getFullYear() according to local time.
Returns the year of the specified date according to local
getHours() time.
Returns the hour in the specified date according to local
time.
Page 76
getMilliseconds() Returns the milliseconds in the specified date according
to local time. Returns the minutes in the specified date
getMinutes() according to local time.
Returns the month in the specified date according to
getMonth() local time.
Returns the seconds in the specified date according to
getSeconds() local time.
Returns the numeric value of the specified date as the
getTime() number of milliseconds since January 1, 1970, 00:00:00
UTC.
Returns the time-zone offset in minutes for the current
getTimezoneOffset locale.
() Returns the day (date) of the month in the specified date
getUTCDate() according to universal time.
Returns the day of the week in the specified date
getUTCDay() according to universal time. Returns the year in the
specified date according to universal time. Returns the
getUTCFullYear() hours in the specified date according to universal time.
Returns the milliseconds in the specified date
getUTCHours() according to universal time.
Sets the month for a specified date according to
getUTCMillisecon
universal time.
ds()
Sets the seconds for a specified date according to
setUTCMonth() universal time.
Deprecated - Sets the year for a specified date
setUTCSeconds() according to local time. Use setFullYear instead.
Returns the "date" portion of the Date as a human-
setYear() readable string.
Deprecated - Converts a date to a string, using the
toDateString()
Internet GMT conventions. Use toUTCString instead.
Returns the "date" portion of the Date as a string, using
toGMTString()
the current locale's conventions.
Converts a date to a string, using a format string.
toLocaleDateStrin
Converts a date to a string, using the current locale's
g() conventions.
toLocaleFormat() Returns the "time" portion of the Date as a string, using
toLocaleString() the current locale's conventions.
toLocaleTimeStrin Returns a string representing the source for an
g() equivalent Date object; you can use this value to create
toSource() a new object.
Returns a string representing the specified Date object.
Returns the "time" portion of the Date as a human-
readable string.
toString()
toTimeString()
Page 77
toUTCString() Converts a date to a string, using the universal
time convention.
valueOf() Returns the primitive value of a Date object.
6.6.4 Date()
Javascript Date() method returns today's date and time and does not need any
object to be called.
Syntax
Its syntax is as follows:
Date()
Return Value
Returns today's date and time.
Example
The following example.
<html>
<head>
<title>JavaScript Date Method</title>
</head>
<body>
<script type="text/javascript">
var dt = Date();
[Link]("Date and Time : " + dt );
</script>
</body>
</html>
Output
6.7 Doing Mathematical Operation The math object provides you properties and
methods for mathematical constants
and functions. Unlike other global objects, Math is not a constructor. All the
properties and methods of Math are static and can be called by using Math as an
object without creating it.
Thus, you refer to the constant pi as [Link] and you call the sine function as
[Link](x), where x is the method's argument.
Syntax
The syntax to call the properties and methods of Math are as follows:
Page 78
var pi_val = [Link];
var sine_val = [Link](30);
<html>
<head>
<title>JavaScript Math E Property</title>
</head>
<body>
<script type="text/javascript">
var property_value = Math.E
[Link]("Property Value is :" + property_value);
</script>
</body>
</html>
Page 79
Output
Here is a list of the methods associated with Math object and their description.
Method Description
abs() Returns the absolute value of a number.
acos() Returns the arccosine (in radians) of a
number.
asin() Returns the arcsine (in radians) of a number.
atan()
atan2() Returns the arctangent (in radians) of a
ceil()
cos() number.
exp() Returns the arctangent of the quotient of its
arguments.
Returns the smallest integer greater than or
equal to a number.
Returns the cosine of a number.
Returns EN, where N is the argument, and E
is Euler's constant, the base of the natural
logarithm.
floor() Returns the largest integer less than or equal
log() to a number
max()
Returns the natural logarithm (base E) of a
min()
number.
pow() Returns the largest of zero or more numbers.
random() Returns the smallest of zero or more
round() numbers.
Returns base to the exponent power, that is,
sin() base exponent.
sqrt() Returns a pseudo-random number between 0
tan() and 1.
toSource() Returns the value of a number rounded to the
nearest integer.
Returns the sine of a number.
Returns the square root of a number.
Returns the tangent of a number.
Returns the string "Math".
Page 80
6.7.4 sqrt ( )
This method returns the square root of a number. If the value of a number is
negative, sqrt returns NaN.
Syntax
Its syntax is as follows:
[Link] ( x );
Parameter Details
Return Value x: A number.
Returns the square root of a given number.
Example
The following example program.
<html>
<head>
<title>JavaScript Math sqrt() Method</title>
</head>
<body>
<script type="text/javascript">
var value = [Link]( 0.2 );
[Link]("First Test Value : " + value );
var value = [Link]( 81 );
[Link]("<br />Second Test Value : " + value );
var value = [Link]( 13 );
[Link]("<br />Third Test Value : " + value );
var value = [Link]( -4 );
[Link]("<br />Fourth Test Value : " + value );
</script>
</body>
</html>
Output
Page 81
CHECK YOUR PROGRESS 1
Answer:__________________________________________________________
_________________________________________________________________
Q2. Write the use of New Operator ?
Answer:__________________________________________________________
_________________________________________________________________
Q3. Which method returns the square root of a number?
Answer:__________________________________________________________
_________________________________________________________________
Q4. Which method returns the absolute value of a number?
Answer:__________________________________________________________
_________________________________________________________________
Q5. Which property returns a reference to the array function that created the
instance's prototype in java script?
Answ er:__________________________________________________________
_________________________________________________________________
Q6. What is array ?
Answer:__________________________________________________________
_________________________________________________________________
Answer:__________________________________________________________
_________________________________________________________________
Answer:__________________________________________________________
_________________________________________________________________
Page 82
6.8 Working with Regular Expression
Brackets
Brackets ([]) have a special meaning when used in the context of regular
expressions.
Expression Description
Page 83
6.8.1 RegExp Properties
Here is a list of the properties associated with RegExp and their description
Property Description
constructo Specifies the function that creates an object's
r prototype.
specifies whether
a particular regular expression performs multiline matching, i.e., whether it was
created with the "m" attribute.
Syntax
Its syntax is as follows:
[Link]
Return Value
Returns "TRUE" if the "m" modifier is set, "FALSE" otherwise.
Example
<html>
<head>
<title>JavaScript RegExp multiline Property</title>
</head>
<body>
<script type="text/javascript">
var re = new RegExp( "string" );
if ( [Link] ){
[Link]("Test1-multiline property is set");
}else{
[Link]("Test1-multiline property is not set");
}
re = new RegExp( "string", "m" );
if ( [Link] ){
[Link]("<br/>Test2-multiline property is set");
}else{
[Link]("<br/>Test2-multiline property is not set");
}
Page 84
</script>
</body>
</html>
output
[Link] Methods
Method Description
exec() Executes a search for a match in its string parameter.
test() Tests for a match in its string parameter.
toSource() Returns an object literal representing the specified
object; you can use this value to create a new object.
toString() Returns a string representing the specified object.
6.8.4 Test ( )
The test method searches string for text that matches regexp. If it finds a match, it
returns true; otherwise, it returns false.
Syntax
Its syntax is as follows:
[Link]( string );
Parameter Details
string: The string to be searched.
Return Value
Returns the matched text if a match is found, and null if not.
Example
<html>
<head>
<title>JavaScript RegExp test Method</title>
</head>
<body>
<script type="text/javascript">
var str = "Javascript is interesting scripting language: Trisha pattnaik";
var re = new RegExp( "script", "g" );
var result = [Link](str);
[Link]("Test 1 - returned value : " + result);
re = new RegExp( "pushing", "g" );
var result = [Link](str);
Page 85
[Link]("<br />Test 2 - returned value : " + result);
</script>
</body>
</html>
Output
6.9 Document Object Model (DOM) OA Document object represents the HTML
document that is displayed in that
window. The Document object has various properties that refer to other objects
which allow access to and modification of document content.
The way a document content is accessed and modified is called the Document
Object Model, or DOM. The Objects are organized in a hierarchy. This
hierarchical structure applies to the organization of objects in a Web document.
Window object: Top of the hierarchy. It is the outmost element of the object
hierarchy.
Document object: Each HTML document that gets loaded into a window
becomes a document object. The document contains the contents of the page.
Form object: Everything enclosed in the <form>...</form> tags sets the form
object.
Form control elements: The form object contains all the elements defined for
that object such as text fields, buttons, radio buttons, and checkboxes.
This is the model which was introduced in early versions of JavaScript language.
It is well supported by all browsers, but allows access only to certain key portions
of documents, such as forms, form elements, and images.
This model provides several read-only properties, such as title, URL, and last
Modified provide information about the document as a whole. Apart from that,
there are various methods provided by this model which can be used to set and get
document property values.
Page 86
6.9.2 Document Properties in Legacy DOM
Here is a list of the document properties which are
[Link][1]
Page 87
6.9.2 Document Methods in Legacy DOM
Here is a list of methods supported by Legacy DOM.
Example: <html>
<head>
<title> Document Title </title>
<script type="text/javascript">
<!--
functionmyFunc()
{
var ret = [Link];
alert("Document Title : " + ret );
var ret = [Link];
alert("Document URL : " + ret );
var ret = [Link][0];
alert("Document First Form : " + ret );
var ret = [Link][0].elements[1];
alert("Second element : " + ret );
}
//-->
</script>
Page 88
</head>
<body>
<h1 id="title">This is my java program: TEJWASH MOHANTY </h1>
<p>Click the following to see the result:</p>
<form name="FirstForm">
<input type="button" value="Click Me" onclick="myFunc();" />
<input type="button" value="Cancel">
</form>
<form name="SecondForm">
<input type="button" value="Don't ClickMe"/>
</form>
</body>
</html>
Output
6.10 Error and Error Handling There are three types of errors in programming: (a)
Syntax Errors, (b) Runtime
Errors, and (c) Logical Errors.
Syntax Errors
Syntax errors, also called parsing errors, occur at compile time in traditional
programming languages and at interpret time in JavaScript Runtime Errors
Runtime errors, also called exceptions, occur during execution (after
compilation/interpretation). Logical Errors
Logic errors can be the most difficult type of errors to track down. These errors
are not the result of a syntax or runtime error. Instead, they occur when you make
a mistake in the logic that drives your script and you do not get the result you
expected. The try...catch...finallyStatement
Page 89
The latest versions of JavaScript added exception handling capabilities. JavaScript
implements the try...catch...finally construct as well as the throw operator to handle
exceptions. You can catch programmer-generated and runtime exceptions, but you
cannot catch JavaScript syntax errors.
<script type="text/javascript">
<!--
try {
// Code to run
[break;]
} catch ( e ) {
// Code to run if an exception occurs
[break;]
}[ finally {
// Code that is always executed regardless of
// an exception occurring
}]
//-->
</script>
Example
<html>
<head>
<script type="text/javascript">
<!--
functionmyFunc()
{
var a = 100;
[Link] ("Value of variable a is : " + a );
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
<p>Error will happen and depending on your browser: trisha.</p>
</body>
</html>
Page 90
OUTPUT
6.11 Client side validation Validation normally used to occur at the server, after the
client had entered all the
necessary data and then pressed the Submit button. If the data entered by a client
was incorrect or was simply missing, the server would have to send all the data
back to the client and request that the form be resubmitted with correct
information. This was really a lengthy process which used to put a lot of burden
on the server.
JavaScript provides a way to validate form's data on the client's computer before
sending it to the web server. Form validation generally performs two functions.
Basic Validation - First of all, the form must be checked to make sure all
the mandatory fields are filled in. It would require just a loop through each
field in the form and check for data.
Data Format Validation - Secondly, the data that is entered must be
checked for correct form and value. Your code must include appropriate
logic to test correctness of data.
Example
We will take an example to understand the process of validation. Here is a
simple form in html format.
<html>
<head>
<title>Form Validation</title>
<script type="text/javascript">
<!--
// Form validation code will come here.
//-->
</script>
</head>
<body>
<form action="/cgi-bin/[Link]" name="myForm"
Page 91
onsubmit="return(validate());">
<table cellspacing="2" cellpadding="2" border="1">
<tr>
<td align="right">Name</td>
<td><input type="text" name="Name" /></td>
</tr>
<tr>
<td align="right">EMail</td>
<td><input type="text" name="EMail" /></td>
</tr>
<tr>
<td align="right">Zip Code</td>
<td><input type="text" name="Zip" /></td>
</tr>
<tr>
<td align="right">Country</td>
<td>
<select name="Country">
<option value="-1" selected>[choose yours]</option>
<option value="1">USA</option>
<option value="2">UK</option>
<option value="3">INDIA</option>
</select>
</td>
</tr>
<tr>
<td align="right"></td>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form>
</body>
</html>
Output
Page 92
6.11.1 Basic Form Validation First let us see how to do a basic form validation. In
the above form, we are calling validate() to validate data when onsubmit event is
occurring. The following code shows the implementation of this validate() function.
<script type="text/javascript">
<!--
// Form validation code will come here.
function validate()
{
if( [Link] == "" )
{
alert( "Please provide your name!" );
[Link]() ;
return false;
}
if( [Link] == "" )
{
alert( "Please provide your Email!" );
[Link]() ;
return false;
}
if( [Link] == "" ||
isNaN( [Link] ) ||
[Link] != 5 )
{
alert( "Please provide a zip in the format #####." );
[Link]() ;
return false;
}
if( [Link] == "-1" )
{
alert( "Please provide your country!" );
return false;
}
return( true );
}
//-->
</script>
Page 93
<!--
function validateEmail()
{
var emailID = [Link];
atpos = [Link]("@");
dotpos = [Link](".");
if (atpos < 1 || ( dotpos - atpos < 2 ))
{
alert("Please enter correct email ID")
[Link]() ;
return false;
}
return( true );
}
//-->
</script>
6.12 Animation in webpages
You can use JavaScript to create a complex animation having, but not limited to,
the following elements:
Fireworks
Fade Effect
Roll-in or Roll-out
Page-in or Page-out
Object movements
JavaScript can be used to move a number of DOM elements (<img />, <div>, or
any other HTML element) around the page according to some sort of pattern
determined by a logical equation or function.
JavaScript provides the following two functions to be frequently used in
animation programs.
setTimeout (function, duration) - This function calls function after
duration milliseconds from now.
setInterval (function, duration) - This function calls function after
every duration milliseconds.
clearTimeout (setTimeout_variable) - This function clears any timer
set by the setTimeout() function.
JavaScript can also set a number of attributes of a DOM object including its
position on the screen. You can set top and left attribute of an object to position it
anywhere on the screen. Here is its syntax.
Page 94
6.12.1 Manual Animation
So let's implement one simple animation using DOM object properties and
JavaScript functions as follows. The following list contains different DOM
methods.
We are using the JavaScript function getElementById() to get a DOM
object and then assigning it to a global variable imgObj.
We have defined an initialization function init() to initialize imgObj
where we have set its position and left attributes.
We are calling initialization function at the time of window load.
Finally, we are calling moveRight() function to increase the left distance
by 10 pixels. You could also set it to a negative value to move it to the left
Example
The following example.
<html>
<head>
<title>JavaScript Animation</title>
<script type="text/javascript">
<!--
var imgObj = null;
function init(){
imgObj = [Link]('myImage');
[Link]= 'relative';
[Link] = '0px';
}
function moveRight(){
[Link] = parseInt([Link]) + 10 + 'px';
}
[Link] =init;
//-->
</script>
</head>
<body>
<form>
<img id="myImage" src="D:/[Link]" />
<p>Click button below to move the image to right</p>
<input type="button" value="Click Me" onclick="moveRight();"
/>
</form>
</body>
</html>
Page 95
Output
6
6.12.2 Automated Animation In the above example, we saw how an image moves to
right with every click. We can automate this process by using the JavaScript
function setTimeout() as follows. Here we have added more methods. So let's see
what is new here:
The moveRight() function is calling setTimeout() function to set the
position of imgObj.
We have added a new function stop() to clear the timer set by
setTimeout() function and to set the object at its initial position.
Example
The following example code.
<html>
<head>
<title>JavaScript Animation</title>
<script type="text/javascript">
<!--
var imgObj = null;
var animate ;
function init(){
imgObj = [Link]('myImage');
[Link]= 'relative';
[Link] = '0px'; }
Page 96
function moveRight(){ [Link] =
parseInt([Link]) + 10 + 'px'; animate =
setTimeout(moveRight,20); // call moveRight in 20msec } function
stop(){ clearTimeout(animate); [Link] = '0px'; }
[Link] =init; //--> </script> </head> <body> <form> <img
id="myImage" src="/images/[Link]" /> <p>Click the buttons
below to handle animation</p> <input type="button" value="Start"
onclick="moveRight();" /> <input type="button" value="Stop"
onclick="stop();" /> </form> </body> </html>
Output
<html>
<head>
<title>List of Plug-Ins</title>
</head>
<body>
<table border="1">
<tr><th>Plug-in
Name</th><th>Filename</th><th>Description</th></tr>
Page 97
<script LANGUAGE="JavaScript" type="text/javascript">
for (i=0; i<[Link]; i++) {
[Link]("<tr><td>");
[Link]([Link][i].name);
[Link]("</td><td>");
[Link]([Link][i].filename);
[Link]("</td><td>");
[Link]([Link][i].description);
[Link]("</td></tr>");
}
</script>
</table>
</body>
</html>
Each plug-in has an entry in the array. Each entry has the following properties:
name - is the name of the plug-in.
filename - is the executable file that was loaded to install the plug-in.
description - is a description of the plug-in, supplied by the developer.
mimeTypes - is an array with one entry for each MIME type supported
by the plug-in.
You can use these properties in a script to find out the installed plug-ins, and then
using JavaScript, you can play appropriate multimedia file. Take a look at the
following example.
<html>
<head>
<title>Using Plug-Ins</title>
</head>
<body>
<script language="JavaScript" type="text/javascript">
media = [Link]["video/quicktime"];
Page 98
if (media){
[Link]("<embed src='[Link]' height=100 width=100>");
}
else{
[Link]("<img src='[Link]' height=100 width=100>");
}
</script>
</body>
</html>
NOTE: Here we are using HTML <embed> tag to embed a multimedia file.
Let us take a real example which works in almost all the browsers.
<html>
<head>
<title>Using Embeded Object</title>
<script type="text/javascript">
<!--
function play()
{
if (![Link]()){
[Link]();
}
}
function stop()
{
if ([Link]()){
[Link]();
}
}
function rewind()
if ([Link]()){
[Link]();
}
[Link]();
}
//-->
</script>
</head>
<body>
<embed id="demo" name="demo"
src="[Link]
width="318" height="300" play="false" loop="false"
pluginspage="[Link]
swliveconnect="true">
</embed>
Page 99
<form name="form" id="form" action="#" method="get">
<input type="button" value="Start" onclick="play();" />
<input type="button" value="Stop" onclick="stop();" />
<input type="button" value="Rewind" onclick="rewind();" />
</form>
</body>
</html>
<html>
<head>
<title>Using JavaScript Image Map</title>
<script type="text/javascript">
<!--
function show(name){
[Link] = name
}
//-->
</script>
</head>
<body>
<form name="myform">
<input type="text" name="stage" size="20" />
</form>
Page 100
onMouseOut="show('')"/>
<area shape="rect"
coords="22,83,126,125"
href="D:/[Link]" alt="rect"
target="_self"
onMouseOver="show('HTML')"
onMouseOut="show('')"/>
<area shape="circle"
coords="73,168,32"
href="D:/php/[Link]" alt="Circle"
target="_self"
onMouseOver="show('PHP')"
onMouseOut="show('')"/>
</map>
</body>
</html>
Output
6.15.1 Definition:
Extensible Markup Language (XML) is a markup language that defines a
set of rules for encoding documents in a format which is both human-
readable and machine-readable.
Page 101
6.15.2 Characteristics of XML
There are three important characteristics of XML that make it useful in a variety
of systems and solutions:
XML is extensible: XML allows you to create your own self-descriptive
tags, or language, that suits your application.
XML carries the data, does not present it: XML allows you to store the
data irrespective of how it will be presented.
XML is a public standard: XML was developed by an organization
called the World Wide Web Consortium (W3C) and is available as an
open standard.
Answer:_________________________________________________________
________________________________________________________________
________________________________________________________________
Answer:__________________________________________________________
_________________________________________________________________
_________________________________________________________________
Page 102
Q3. What is Regular expression?
Answer:__________________________________________________________
_________________________________________________________________
_________________________________________________________________
Answer:__________________________________________________________
_________________________________________________________________
_________________________________________________________________
Answer:__________________________________________________________
_________________________________________________________________
_________________________________________________________________
Answer:__________________________________________________________
_________________________________________________________________
_________________________________________________________________
Answer:__________________________________________________________
_________________________________________________________________
_________________________________________________________________
Answer:__________________________________________________________
_________________________________________________________________
_________________________________________________________________
Page 103
6.16 Reference
Answer: sqrt( )
Answer: abs( )
Page 104
Q5. Which property returns a reference to the array function that created the
instance's prototype in java script?
Answer: constructor
Q5. What is array? Answer: An array is a collection of data items, all of the same
type, accessed
using a common name. Or The Array object lets you store multiple values in a
single variable. ... An array is used to store a collection of data, but it is often
more useful to think of an array as a collection of variables of the same type.
Q6. What is String? Answer: The String object lets you work with a series of
characters; it wraps
JavaScript‟s string primitive data type with a number of helper methods. As
JavaScript automatically converts between string primitives and String objects,
you can call any of the helper methods of the String object on a string primitive.
Q7. How many values represents by Boolean object?
Answer: The Boolean object represents two values, either "true" or "false".
Answer: The JavaScript navigator object includes a child object called plugins.
This object is an array, with one entry for each plug-in installed on the browser.
The [Link] object is supported only by Netscape, Firefox, and Mozilla
only.
Q2. What is Basic Validation? Answer: First let us see how to do a basic form
Page 105
RegExpdefine methods that use regular expressions to perform powerful pattern-
matching and search-and-replace functions on text.
Answer:
Here is the try...catch...finally block syntax:
<script type="text/javascript">
<!--
try {
// Code to run
[break;]
} catch ( e ) {
// Code to run if an exception occurs
[break;]
}[ finally {
// Code that is always executed regardless of
// an exception occurring
}]
//-->
</script>
Page 106
Characteristics of XML
There are three important characteristics of XML that make it useful in a variety
of systems and solutions:
XML is extensible: XML allows you to create your own self-descriptive
tags, or language, that suits your application.
XML carries the data, does not present it: XML allows you to store the
data irrespective of how it will be presented.
XML is a public standard: XML was developed by an organization called the
World Wide Web Consortium (W3C) and is available as an open standard.
Page 107