0% found this document useful (0 votes)
64 views145 pages

Internet and Web Programming: Dr. Monoj Kumar Muchahari

This document contains an outline and table of contents for a book on JavaScript and web programming. The outline lists 12 chapters, including introductions to operators, statements, functions, objects, arrays, event handling, form handling, JSON, and jQuery. The table of contents provides more details on specific topics within each chapter, such as element selection and effects/animation in the jQuery chapter.

Uploaded by

westo
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)
64 views145 pages

Internet and Web Programming: Dr. Monoj Kumar Muchahari

This document contains an outline and table of contents for a book on JavaScript and web programming. The outline lists 12 chapters, including introductions to operators, statements, functions, objects, arrays, event handling, form handling, JSON, and jQuery. The table of contents provides more details on specific topics within each chapter, such as element selection and effects/animation in the jQuery chapter.

Uploaded by

westo
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/ 145

Internet and Web Programming

Dr. Monoj Kumar Muchahari

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 1
Outline
1 Introduction
2 Operators
3 Statements
4 Object-Related Statements
5 Functions
6 Objects
7 Array
Manipulating Arrays
8 Event Handling
9 Form Handling
10 JSON
11 jQuery
Elements Selection
Effects & Animation
*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 2
Table of Contents
1 Introduction
2 Operators
3 Statements
4 Object-Related Statements
5 Functions
6 Objects
7 Array
Manipulating Arrays
8 Event Handling
9 Form Handling
10 JSON
11 jQuery
Elements Selection
Effects & Animation
*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 3
JavaScript

JavaScript is the premier client-side scripting language used on the Web


today.
It’s widely used in tasks ranging from the validation of form data to
the creation of complex user interfaces.
JavaScript is the interactive member of the trinity of client-side Web
technologies that also includes HTML and CSS.
It can dynamically manipulate the very content, markup, and style of
Web pages.

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 4
First JavaScript

<!DOCTYPE html>
<head>
<meta c h a r s e t =” u t f =8”>
< t i t l e >J a v a S c r i p t H e l l o World </ t i t l e >
</head>
<body>
<h1> F i r s t J a v a S c r i p t </h1>
<hr>

<s c r i p t >
document . w r i t e ( ” H e l l o World from J a v a S c r i p t ! ” ) ;
</ s c r i p t >

</body>
</html>

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 5
Basic Definitions

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 6
Execution Order

JavaScript code found in HTML documents is interpreted line by line


as it is read top to bottom.
As such we should declare code structures like variables and functions
before attempting access.
Because of this standard execution order, we generally place some code
for initial read; for example, in Web documents we might place script
references in the < head > tag.

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 7
Case Sensitivity

JavaScript is case-sensitive.
For example, if you use the identifiers result, Result, and RESULT in
your script, each identifier refers to a separate, distinct variable.
Case sensitivity applies to all aspects of the language: keywords, oper-
ators, variable names, event handlers, object properties, and so on.
All JavaScript keywords are lowercase, so when using a feature such as
an if statement, you need to make sure you type “if” and not “If” or
“IF.”
Because JavaScript uses the “camel-back” naming convention, many
methods and properties use mixed casing.
For example, the M in the name of the lastModified property of the
Document object (document.lastModified) must be uppercase; using a
lowercase m (document.lastmodified) will retrieve an undefined value.

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 8
Whitespace

Whitespace characters are those characters that take up space on the


screen without any visible representation.
Examples include ordinary spaces, tabs, and linebreak characters.
Any sequence of excessive whitespace characters is ignored by JavaScript.
For example:
x = x + 1;

i s t h e same a s ;

x=x +1;

This suggests that the use of whitespace is more for the benefit of the
programmer than the interpreter.
Indeed, thoughtful use of whitespace to offset comments, loop con-
tents, and declarations results in more readable, and hopefully, under-
standable code.
As a rule, JavaScript ignores extra whitespace but there are exceptions.
*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 9
Whitespace (contd.)

One is in strings. Whitespace will be preserved in any string enclosed


in single or double quotes:
var s = ” This spacing i s p r e s e r v e d.”;

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 10
Semicolons

A semicolon indicates the end of a JavaScript statement.


For example, you can group multiple statements on one line by
separating them with semicolons:
x = x + 1; y = y + 1; z = 0;

x = x + 1; ;; i f ( x > 10) { x = 0 ; } ; y = y = 1 ;

This example increments x, skips past two empty statements, sets x


to zero if x is greater than 10, and finally decrements y.
As you can see, including multiple statements on one line is rather
unwieldy if worked on directly and as such should be avoided.

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 11
Semicolons (contd.)

Although statements should be followed by semicolons, they can be


omitted if your statements are separated by a line break. For example:

x = x + 1
y = y = 1

is t r e a t e d as

x = x + 1;
y = y = 1;

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 12
Blocks

Curly braces “{ }” are used to group a list of statements together.


For example, the statements that make up the body of a function are
enclosed in curly braces:
f u n c t i o n add ( x , y )
{
var r e s u l t = x + y ;
return result ;
}

If more than one statement is to be executed as the result of a


conditional or in a loop, the statements are similarly grouped:
i f ( x > 10)
{
x = 0;
y = 10;
}

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 13
Variables

A variable stores data. Every variable has a name, called its identifier.
Variables are declared in JavaScript using var, a keyword that allocates
storage space for new data and indicates to the interpreter that a new
identifier is in use.
Declaring a variable is simple:
var x ;

This statement tells the interpreter that a new variable x is about to


be used.
Variables can be assigned initial values when they are declared:
var x = 2;

In addition, multiple variables can be declared with one ‘var’ statement


if the variables are separated by commas:
var x , y = 2 , z ;

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 14
Variables (contd.)

You should not use variables without first declaring them, although it
is possible to do so in many cases.
In JavaScript, variables are either in the global scope or the local scope.
Variables declared within a function belong strictly to that function and
cannot be accessed outside of that scope.
Variables declared outside of a function are global to the application.
However, if a variable is used without a var declaration, even inside of
a function, that variable will belong to the global scope.

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 15
Basic Data Types

There are five basic data types in JavaScript

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 16
Weak Typing

A major difference between JavaScript and other languages you might


be familiar with is that JavaScript is weakly typed.
Every JavaScript variable has a data type, but the type is inferred from
the variable’s content.
For example, a variable that is assigned a string value assumes the
string data type.
A consequence of JavaScript’s automatic type inference is that a vari-
able’s type can change dynamically.
This explains why there is only one way to declare variables in JavaScript:
there is no need to indicate type in variable declarations.
Being weakly typed is both a blessing and a curse for JavaScript.
While weak typing appears to free the programmer from having to
declare types ahead of time, it does so at the expense of introducing
subtle typing errors.
*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 17
Weak Typing (contd.)

For example, given the following script that manipulates various string
and number values, we
document . write (4*3);
document . w r i t e (”< b r / >”);
document . w r i t e (”5” + 5 ) ;
document . w r i t e (”< b r / >”);
document . w r i t e (”5” = 3 ) ;
document . w r i t e (”< b r / >”);
document . w r i t e (5 * ” 5 ” ) ;

The output of this example when included in an HTML document is


shown here:
12
55
2
25

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 18
Table of Contents
1 Introduction
2 Operators
3 Statements
4 Object-Related Statements
5 Functions
6 Objects
7 Array
Manipulating Arrays
8 Event Handling
9 Form Handling
10 JSON
11 jQuery
Elements Selection
Effects & Animation
*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 19
Arithmetic Operators

Arithmetic operators operate solely on numbers, with one exception,


+, which is overloaded and provides string concatenation as well.

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 20
Assignment Operators

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 21
Table of Contents
1 Introduction
2 Operators
3 Statements
4 Object-Related Statements
5 Functions
6 Objects
7 Array
Manipulating Arrays
8 Event Handling
9 Form Handling
10 JSON
11 jQuery
Elements Selection
Effects & Animation
*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 22
Statements

JavaScript supports a core set of statements that include flow control


(if-else, switch), loops (while, do-while, for), and loop control
(break and continue).
JavaScript also supports some object-related statements (with, for-in),
as well as some basic error handling (try-catch-throw).

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 23
if Statements

The if statement is JavaScript’s basic decision-making control state-


ment.
The basic syntax of the if statement is
i f ( expression )
statement ;

The given expression is evaluated to a Boolean, and, if the condition


is true, the statement is executed.
Otherwise, it moves on to the next statement. For example, given this
script fragment,
var x = 5;
i f ( x > 1)
a l e r t (” x i s g r e a t e r than 1 ” ) ;
a l e r t ( ” moving on . . . ” ) ;

the expression evaluates to true, displays the message “x is greater than


1,” and then displays the second alert dialog afterward.
*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 24
if Statements (contd.)

However, if the value of variable x were something like zero, the ex-
pression would evaluate false, resulting in skipping the first alert and
immediately displaying the second one that the script has moved on.
Additional logic can be applied with an else statement.
When the condition of the first statement is not met, the code in the
else statement will be executed:
i f ( expression )
statement or block
else
statement or block

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 25
if Statements (contd.)
Given this syntax, we could expand the previous example as follows:
var x = 5;
i f ( x > 1)
{ a l e r t (” x i s g r e a t e r than 1 . ” ) ;
a l e r t ( ” Yes x r e a l l y i s g r e a t e r t h a n 1 . ” ) ;
}
else
{ a l e r t (” x i s l e s s than 1 . ” ) ;
a l e r t (” This example i s g e t t i n g o l d . ” ) ;
}
a l e r t ( ” moving on . . . ” ) ;

More advanced logic can be added using else if clauses:


i f ( expression1 )
statement or block
else i f ( expression2 )
statement or block
else i f ( expression3 )
statement or block
...
else
statement or block
*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 26
if Statements (contd.)

This simple example illustrates how if statements might be chained


together:
v a r numbertype , x =6;
// s u b s t i t u t e x v a l u e s w i t h = 5, 0 , and ’ t e s t ’
i f ( x < 0)
{
n u m b e r t y p e=” n e g a t i v e ” ;
a l e r t ( ” N e g a t i v e number ” ) ;
}
e l s e i f ( x > 0)
{
n u m b e r t y p e=” p o s i t i v e ” ;
a l e r t ( ” P o s i t i v e number ” ) ;
}
e l s e i f ( x = = 0)
{
n u m b e r t y p e=” z e r o ” ;
a l e r t (” I t ’ s z e r o . ” ) ;
}
else
a l e r t ( ” E r r o r ! I t ’ s n o t a number ” ) ;

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 27
switch

You can use a switch statement rather than relying solely on if state-
ments to select a statement to execute from among many alternatives.
The basic syntax of the switch statement is to give an expression to
evaluate and several different statements to execute based on the value
of the expression.
The interpreter checks each case against the value of the expression
until a match is found.
If nothing matches, a default condition will be used.
switch ( expression )
{
case condition 1: statement ( s )
break ;
case condition 2: statement ( s )
break ;
...
case condition n : statement ( s )
break ;
d e f a u l t : statement ( s )
}
*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 28
switch (contd.)

The break statements indicate to the interpreter the end of that par-
ticular case.
If they were omitted, the interpreter would continue executing each
statement in each of the following cases.
v a r y o u r G r a d e =’A ’ ;
switch ( yourGrade )
{
c a s e ’A ’ : a l e r t ( ” Good j o b . ” ) ;
break ;
c a s e ’B ’ : a l e r t ( ” P r e t t y good . ” ) ;
break ;
c a s e ’ C ’ : a l e r t ( ” You p a s s e d ! ” ) ;
break ;
c a s e ’D ’ : a l e r t ( ” Not s o good . ” ) ;
break ;
c a s e ’ F ’ : a l e r t ( ” Back t o t h e b o o k s . ” ) ;
break ;
d e f a u l t : a l e r t ( ” Grade E r r o r ! ” ) ;
}

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 29
while Loops

Loops are used to perform some action over and over again.
The most basic loop in JavaScript is the while loop, whose syntax is
shown here:
while ( expression )
statement or block of statements to execute

The purpose of a while loop is to execute a statement or code block


repeatedly as long as expression is true.
Once expression becomes false or a break statement is encountered,
the loop will be exited.
var count = 0;
w h i l e ( count < 10)
{
document . w r i t e ( c o u n t+”<b r / >”);
c o u n t ++;
}
document . w r i t e ( ” Loop done ! ” ) ;

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 30
while Loops (contd.)

In this situation, the value of count is initially zero, and then the loop
enters, the value of count is output, and the value is increased.
The body of the loop repeats until count reaches 10, at which point
the conditional expression becomes false.
At this point, the loop exits and executes the statement following the
loop body.

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 31
do-while Loops

The do-while loop is similar to the while loop except that the condition
check happens at the end of the loop.
This means that the loop will always be executed at least once (unless
a break is encountered first).
The basic syntax of the loop is as follows:
do
{
statement ( s ) ;
}
while ( expression );

The example here shows the do-while loop counting example:


var count = 0;
do
{ document . w r i t e ( ” Number ” + c o u n t + ”< b r / >”);
count = count + 1;
} w h i l e ( count < 1 0 ) ;

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 32
for Loops

The for loop is the most compact form of looping and includes the loop
initialization, test statement, and iteration statement all in one line.
The basic syntax is shown here:
for ( i n i t i a l i z a t i o n ; test condition ; i t e r a t i o n statement )
loop statement or block

The initialization statement is executed before the loop begins, the


loop continues executing until test condition becomes false, and at
each iteration the iteration statement is executed.
f o r ( v a r i = 0 ; i < 1 0 ; i ++)
document . w r i t e ( ” Loop ” + i + ”< b r / >”);

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 33
Table of Contents
1 Introduction
2 Operators
3 Statements
4 Object-Related Statements
5 Functions
6 Objects
7 Array
Manipulating Arrays
8 Event Handling
9 Form Handling
10 JSON
11 jQuery
Elements Selection
Effects & Animation
*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 34
with Statement

JavaScript’s with statement allows programmers to use a shorthand


notation when referencing objects.
For example, to write to an HTML document, normally we would use
the write() method of the Document object:
document . w r i t e ( ” H e l l o from J a v a S c r i p t ” ) ;
document . w r i t e (”< b r / >”);
document . w r i t e ( ” You can w r i t e what you l i k e h e r e ” ) ;

The with statement indicates an object that will be used implicitly


inside the statement body.
The general syntax is
with ( object )
{
statement ( s ) ;
}

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 35
with Statement (contd.)

Using a with statement, we could shorten the reference to the object,


as shown here:
w i t h ( document )
{
w r i t e ( ” H e l l o from J a v a S c r i p t ” ) ;
w r i t e (”< b r / >”);
w r i t e ( ” You can w r i t e what you l i k e h e r e ” ) ;
}

The with statement is certainly a convenience as it avoids having to


type the same object names over and over again.

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 36
Object Iteration Using for...in

Another statement that is useful with objects is for...in, which is used


to loop through an object’s properties.
The basic syntax is this:
for ( variablename in object )
statement or block to execute

Consider the following example, which prints out the properties of a


Web browser’s Navigator object.
var aProperty ;
document . w r i t e (”<h1>N a v i g a t o r O b j e c t P r o p e r t i e s </h1 >”);
for ( aProperty in navigator )
{
document . w r i t e ( a P r o p e r t y ) ;
document . w r i t e (”< b r / >”);
}

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 37
Table of Contents
1 Introduction
2 Operators
3 Statements
4 Object-Related Statements
5 Functions
6 Objects
7 Array
Manipulating Arrays
8 Event Handling
9 Form Handling
10 JSON
11 jQuery
Elements Selection
Effects & Animation
*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 38
Functions

Functions can be used to create code fragments that can be used over
and over again.
When written properly, functions are abstract -they can be used in
many situations and are ideally completely self-contained, with data
passing in and out through well-defined interfaces.
The most common way to define a function in JavaScript is by using
the keyword function, followed by a unique function name, a list of
parameters (that might be empty), and a statement block surrounded
by curly braces.
The basic syntax is shown here:
f u n c t i o n functionname ( parameter= l i s t )
{
statements
}

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 39
Functions (contd.)

A simple function that takes no parameters called sayHello is defined


here:
function sayHello ()
{
a l e r t (” H e l l o t h e r e ” ) ;
}

To invoke the function somewhere later in the script, you would use
this statement:
sayHello ();

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 40
Parameter Passing Basics

Very often we will want to pass information to functions to be used in


a calculation or to change the operation the function performs.
Data passed to functions, whether in literals or variables, are termed
parameters, or occasionally arguments.
Consider the following modification of the sayHello() function to take
a single parameter called someName:
f u n c t i o n s a y H e l l o ( someName )
{
i f ( someName != ” ” )
a l e r t ( ” H e l l o t h e r e ”+someName ) ;
else
a l e r t ( ” Don ’ t be s h y ” ) ;
}

In this case, the function receives a value that determines which output
string to display. Calling the function with
s a y H e l l o (” George ” ) ;

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 41
Return Statements

The inclusion of a return statement indicates that a function should


exit and potentially return a value as well.
f u n c t i o n addThree ( arg1 , arg2 , arg3 )
{
r e t u r n ( a r g 1+a r g 2+a r g 3 ) ;
}
var x = 5 , y = 7 , r e s u l t ;
r e s u l t = addThree ( x , y , 1 1 ) ;
alert ( result );

Functions also can include multiple return statements, as demonstrated


by the example here:
f u n c t i o n myMax ( a r g 1 , a r g 2 )
{
i f ( a r g 1 >= a r g 2 )
r e t u r n arg1 ;
else
r e t u r n arg2 ;
}

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 42
Parameter Passing

Primitive data types are passed by value in JavaScript.


This means that a copy is effectively made of a variable when it is
passed to a function, so any manipulation local to the function leaves
the original variables untouched.
f u n c t i o n f i d d l e ( arg1 )
{
arg1 = ” Fiddled with ”;
document . w r i t e ( ” I n f u n c t i o n f i d d l e a r g 1 = ”+a r g 1+”<b r / >”);
}
var s t r = ” O r i g i n a l Value ” ;
document . w r i t e ( ” B e f o r e f u n c t i o n c a l l x = ”+ s t r +”<b r / >”);
fiddle ( str );
document . w r i t e ( ” A f t e r f u n c t i o n c a l l x =”+ s t r +”<b r / >”);

Notice that the function fiddle() does not modify the value of the
variable str because, as a primitive type, it only receives a copy of str.

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 43
Parameter Passing (contd.)

However, if composite types such as arrays and objects are used, they
are passed by reference rather than value.
f u n c t i o n f i d d l e ( arg1 )
{
arg1 [ 0 ] = ” Fiddled with ”;
document . w r i t e ( ” I n f u n c t i o n f i d d l e a r g 1 = ”+a r g 1+”<b r / >”);
}
var arr = [” Original ” , ” Original ” , ” Original ” ] ;
document . w r i t e ( ” B e f o r e f u n c t i o n c a l l a r r = ”+ a r r +”<b r / >”);
fiddle ( arr );
document . w r i t e ( ” A f t e r f u n c t i o n c a l l a r r =”+ a r r +”<b r / >”);

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 44
Functions as Objects

In JavaScript just about everything is an object, and functions are no


exception.
Thus it is possible to define functions in a much different way than we
have seen up until now by treating a function just like any plain object
and instantiating it using the keyword new.
v a r s a y H e l l o = new F u n c t i o n ( ” a l e r t ( ’ H e l l o t h e r e ’ ) ; ” ) ;

Notice that Function is capitalized since it is a constructor and we are


creating an instance of JavaScript’s built-in Function object.
Later on, we can then use the assigned variable sayHello just like a
regular function call:
sayHello ();

Because functions are first-class data types, the function can even be
assigned to another variable and used by that name instead:
var sayHelloAgain = sayHello ;
sayHelloAgain ( ) ;

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 45
Functions as Objects (contd.)

We could define a function with a parameter to print out, as follows,


v a r s a y H e l l o 2 = new F u n c t i o n ( ” msg ” , ” a l e r t ( ’ H e l l o t h e r e ’+msg ) ; ” ) ;

and call it:


s a y H e l l o 2 ( ’ Thomas ’ ) ;

The general syntax for the Function() constructor is


v a r f u n c t i o n N a m e = new F u n c t i o n ( ” a r g u m en t 1 ” , . . . ” a rg u m e n t n ” ,
” s t a t e m e n t s f o r f u n c t i o n body ” ) ;

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 46
Static Variables

You can create static variables that persist beyond function invocations
by adding an instance property for the defined function.
For example, consider the code here that defines a function doSum()
that adds two numbers and keeps a running sum:
f u n c t i o n doSum ( x , y )
{
// u p d a t e t h e r u n n i n g sum
doSum . t o t a l S u m = doSum . t o t a l S u m + x + y ;
r e t u r n ( doSum . t o t a l S u m ) ; // r e t u r n t h e c u r r e n t sum
}
// D e f i n e a s t a t i c v a r i a b l e t o h o l d t h e r u n n i n g sum o v e r a l l calls
doSum . t o t a l S u m = 0 ;
document . w r i t e ( ” F i r s t C a l l = ”+doSum(5 ,10)+” < b r / >”);
document . w r i t e ( ” Second C a l l = ”+doSum(5 ,10)+” < b r / >”);
document . w r i t e ( ” T h i r d C a l l = ”+doSum(100 ,100)+” < b r / >”);

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 47
Table of Contents
1 Introduction
2 Operators
3 Statements
4 Object-Related Statements
5 Functions
6 Objects
7 Array
Manipulating Arrays
8 Event Handling
9 Form Handling
10 JSON
11 jQuery
Elements Selection
Effects & Animation
*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 48
Objects

JavaScript is actually an “object-based” language.


In JavaScript, practically everything is an object, except for language
constructs, keywords, and operators.
Objects in JavaScript play many different roles, from representing data
types to manipulation of HTML documents via the Document Object
Model (DOM), to interfacing with the browser, and more.
Objects in JavaScript fall into four groups: User-defined objects, Native
objects, Host objects and Document objects.

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 49
User-defined objects

User-defined objects are custom objects created by the programmer to


bring structure and consistency to a particular programming task.
Objects can be nested within other objects, and this allows the pro-
grammer to create arbitrarily complex data structures consisting of data
(properties) and behavior (methods) for desired tasks.
The programmer can collect all the data and functions related to a
specific task into a single unit: an object.

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 50
Native objects

Native objects are provided by the JavaScript language itself.


These include objects associated with data types such as String, Num-
ber, and Boolean, as well as objects that allow creation of user-defined
objects and composite types, such as Object and Array.
Native objects also include JavaScript functions, such as Function, as
well as other objects that simplify common tasks, such as Date, Math,
and RegExp manipulation.
Other miscellaneous objects for exception handling, such as Error, are
also native.

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 51
Host objects

Host objects are those objects that are not specified as part of the
JavaScript language but that are supported by most host environments,
typically browsers.
Examples of browser-based host objects include window, the object
that enables the manipulation of browser windows and interaction with
the user, and navigator, the object that provides information about
client configuration.

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 52
Document objects

Document objects are part of the Document Object Model (DOM), as


defined by the W3C.
These objects present the programmer with a structured interface to
HTML and XML documents.
Access to the document objects is provided by the browser via the
document property of the window object (window.document).

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 53
Object Creation

An object is created with a constructor, a special type of function that


prepares a new object for use by initializing the memory it takes up.
Objects are created by applying the new operator to their constructors.
This operator causes the constructor to which it is applied to create
a brand-new object, and the nature of the object that is created is
determined by the particular constructor that is invoked.
For example, the String() constructor creates String objects while the
Array() constructor creates Array objects.
A simple example of object creation is shown here:
v a r c i t y = new S t r i n g s ( ) ;

This statement creates a new String object and places a reference to


it in the variable city.
Because no argument was given to the constructor, city is assigned the
default value for strings, the empty string.
*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 54
Object Creation (contd.)

We could have made the example more interesting by passing the con-
structor an argument specifying an initial value:
v a r c i t y = new S t r i n g s ( ” K o l k a t a ” ) ;

This places a reference to a new String object with the value “Kolkata”
in city.
We are not limited to declaring only native objects such as String and
Array; the creation of Object objects is also possible.
These generic objects can be used to create user-defined data types,
and they are, therefore, one of the most powerful tools available for
writing nontrivial JavaScript code.
As with any object in JavaScript, you can add properties to a user-
defined object dynamically.
v a r r o b o t = new O b j e c t ( ) ;
r o b o t . name = ” J a r v i s ” ;
robot . hasJetpack = true ;

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 55
Object Creation (contd.)

You can, also add functions dynamically.


The following code extends the previous simple example by adding a
method to the robot object.
We first define the function and then add it to the object:
function s t r i k e I n t r u d e r ()
{
a l e r t ( ”ZAP ! ” ) ; }

robot . attack = s t r i k e I n t r u d e r ;

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 56
Object Literals

Object literals are also supported in JavaScript.


The syntax is a curly braces–enclosed, comma-separated list of proper-
ty/value pairs.
Property/value pairs are specified by giving a property name, followed
by a colon, and then its value.
var robot = { name : ” J a r v i s ” ,
hasJetpack : true ;
a t t c k : f u n c t i o n ( ) { a l e r t ( ”ZAP ! ” ) ; }
};

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 57
Properties

A property of an object is some piece of named data it contains.


Properties are accessed with the dot (.) operator applied to an object.
For example, accesses the length property of the String object refer-
enced by myString.
v a r m y S t r i n g = new S t r i n g ( ” H e l l o w o r l d ” ) ;
a l e r t ( myString . length ) ;

Accessing a property that does not exist returns an undefined value:


v a r m y S t r i n g = new S t r i n g ( ” H e l l o w o r l d ” ) ;
a l e r t ( myString . noSuchValue ) ; // u n d e f i n e d

It is easy to use instance properties, properties added dynamically by


script code:
v a r m y S t r i n g = new S t r i n g ( ” H e l l o w o r l d ” ) ;
myString . simpleExample = true ;
a l e r t ( myString . simpleExample ) ; // t r u e

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 58
Properties (contd.)

You can remove instance properties with the delete operator.


v a r m y S t r i n g = new S t r i n g ( ” H e l l o w o r l d ” ) ;
myString . simpleExample = true ;

d e l e t e myString . simpleExample ;

a l e r t ( ” The v a l u e o f m y S t r i n g . s i m p l e E x a m p l e i s : ” +
myString . SimpleExample ) ; // u n d e f i n e d

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 59
Detecting if Properties Exist on an Object

Very common task for developers is how to determine if a property


currently exists on an object.
There are a few ways to accomplish this:
v a r o b j = new O b j e c t ( ) ;
obj . prop 1 = ” Hello ”;

// U s i n g ” t r u t h y ” t e s t
i f ( o b j . p r o p 1 ) {}

// U s i n g t y p e o f t e s t
i f ( t y p e o f o b j . p r o p 1 != ” u n d e f i n e d ” ) {}

// U s i n g i n o p e r a t o r
i f ( ” p r o p 1 ” i n o b j ) {}

// U s i n g h a s O w n P r o p e r t y
i f ( o b j . h a s O w n P r o p e r t y ( ” p r o p 1 ” ) ) {}

These different techniques have different implications, so their use


should be considered carefully.
*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 60
Detecting if Properties Exist on an Object (contd.)

Use of the “truthy” test for an object’s property is a common pattern,


and under specific conditions is safe.
But if the property in question can ever be assigned any kind of non-
truthy value, such as false, 0, “ ”, null, undefined, or NaN, this test
will fail even if the property exists on the object but has one of those
values.
The typeof operator check for property existence is effective, but its
wordiness may be stylistically undesirable.
As opposed to the previous two techniques, the in operator requires
the property name to be expressed as a string, which also may be awk-
ward; however, this technique has become popular, particularly when
detecting properties in DOM objects.
The hasOwnProperty() technique also requires the property name as
a string and will check if an object has the property directly on that
instance (and thus is not just an inherited prototype property).
*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 61
Accessing Properties with the Array Syntax

An equivalent, but sometimes more convenient, alternative to the dot


operator is the array ([ ]) operator.
It enables you to access the property given by the string passed within
the brackets. For example:
v a r m y S t r i n g = new S t r i n g ( ” H e l l o w o r l d ” ) ;
a l e r t ( myString [” length ” ] ) ;

myString [” simpleExample ”] = true ;


a l e r t ( myString . simpleExample ) ;
d e l e t e myString [” simpleExample ” ] ;

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 62
Methods

Object members that are functions are called methods.


Like properties, they are typically accessed with the dot operator.
The following example illustrates invoking the toUpperCase() method
of the String object:
v a r m y S t r i n g = new S t r i n g ( ”am i s p e a k i n g l o u d l y ? ” ) ;
a l e r t ( myString . toUpperCase ( ) ) ;

Setting instance methods is just like setting instance properties:


v a r m y S t r i n g = new S t r i n g ( ”Am I s p e a k i n g l o u d l y ? ” ) ;
m y S t r i n g . sayNo = f u n c t i o n ( ) { a l e r t ( ” Nope . ” ) ; } ;
m y S t r i n g . sayNo ( ) ;

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 63
Table of Contents
1 Introduction
2 Operators
3 Statements
4 Object-Related Statements
5 Functions
6 Objects
7 Array
Manipulating Arrays
8 Event Handling
9 Form Handling
10 JSON
11 jQuery
Elements Selection
Effects & Animation
*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 64
Array

Array is an composite type that store ordered lists of data.


Arrays may be declared using the Array() constructor or an array literal.
We start first with the object constructor syntax.
v a r f i r s t A r r a y = new A r r a y ( ) ;
v a r s e c o n d A r r a y = new A r r a y ( ” r e d ” , ” g r e e n ” , ” b l u e ” ) ;
v a r t h i r d A r r a y = new A r r a y ( 5 ) ;

The first declaration creates an empty array called firstArray.


The second declaration creates a new array secondArray with the first
value equal to “red,” the second value equal to “green,” and the last
value equal to “blue.”
The third declaration creates a new empty array thirdArray whose
length property has value 5.
JavaScript 1.2+ allows you to create arrays using array literals.

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 65
Array (contd.)

The following declarations are functionally equivalent to those of the


previous example:
var f i r s t A r r a y = [ ] ;
var secondArray = [” red ” , ” green ” , ” blue ” ] ;
var thirdArray = [ , , , , ] ;

The first two declarations should not be surprising, but the third looks
rather odd.
The given literal has four commas, but the values they separate seem
to be missing.
The interpreter treats this example as specifying five undefined values
and sets the array’s length to 5 to reflect this.
The values used to initialize arrays need not be literals. The following
example is perfectly legal and in fact very common:
var x = 2.0 , y = 3.5 , z = 1;
v a r myValues = [ x , y , z ] ;

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 66
Accessing Array Elements

Accessing the elements of an array is done using the array name with
square brackets and a value.
For example, we can define a three-element array like so:
v a r myArray = [ 1 , 5 1 , 6 8 ] ;

Given that arrays in JavaScript are indexed beginning with zero, to


access the first element we would specify myArray[0], then myArray[1],
and so on.
var myArray = [ 1 , 51 , 6 8 ] ;
var s t r = ””;
str += ” myArray [ 0 ] = ” + myArray [ 0 ] + ”\ n ” ;
str += ” myArray [ 1 ] = ” + myArray [ 1 ] + ”\ n ” ;
str += ” myArray [ 2 ] = ” + myArray [ 2 ] + ”\ n ” ;

The nice thing about JavaScript arrays, unlike those in many other pro-
gramming languages, is that you don’t have to allocate more memory
explicitly as the size of the array grows.
*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 67
Accessing Array Elements (contd.)

For example, to add a fourth value to myArray, you would use


myArray [ 3 ] = 5 7 ;

You do not have to set array values contiguously (one after the other),
so below code is valid as well.
myArray [ 1 1 ] = 2 8 ;

Modifying the values of an array is just as easy: just reassign a preex-


isting indexed value.
For example, to change the second value of the array, just assign it like
this:
myArray [ 1 ] = 1 0 1 ;

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 68
Removing Array Elements

Array elements can be removed using the delete operator.


This operator sets the array element it is invoked on to undefined but
does not change the array’s length. For example,
var myColors = [ ” red ” , ” green ” , ” b l u e ” ] ;
d e l e t e myColors [ 1 ] ;
a l e r t ( ” The v a l u e o f m y C o l o r s [ 1 ] i s : ” +m y C o l o r s [ 1 ] ) ; // u n d e f i n e d

The length property retrieves the index of the next available (unfilled)
position at the end of the array.
Even if some lower indices are unused, length gives the index of the
first available slot after the last element.
v a r myArray = new A r r a y ( ) ;
myArray [ 1 0 0 0 ] = ” T h i s i s t h e o n l y e l e m e n t i n t h e a r r a y ” ;
a l e r t ( myArray . l e n g t h ) ;

Even though myArray has only one element at index 1000, as we see
by the alert dialog myArray.length, the next available slot is at the end
of the array, 1001.
*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 69
Removing Array Elements (contd.)

Assigning values in a noncontiguous manner leads to arrays that have


“holes” between indices holding defined values-the so-called “sparsely
populated array”.
It merely means that you have to be careful that the undefined values
in the “holes” are not accidentally used.
The length property is automatically updated as new elements are
added to the array.
For this reason, length is commonly used to iterate through all elements
of an array.

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 70
Removing Array Elements (contd.)

We now present a “careful” version of an example, which gives the


expected result:
var r e s u l t = 1;
v a r myValues = new A r r a y ( ) ;
myValues [ 0 ] = 2 ;
myValues [ 2 ] = 3 ;
f o r ( v a r i n d e x = 0 ; i n d e x < myValues . l e n g t h ; i n d e x ++)
{
// c h e c k i f e l e m e n t i s v a l i d o r n o t
i f ( myValues [ i n d e x ] != u n d e f i n e d )
r e s u l t = r e s u l t * myValues [ i n d e x ] ;
}
a l e r t ( ” The v a l u e o f r e s u l t i s : ” + r e s u l t ) ;

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 71
Removing Array Elements (contd.)

In addition to providing information, the length property can be set to


perform certain functions.
Any indices containing data that are greater than the value assigned
to length are immediately reset to undefined.
So, for example, to remove all elements from an array, you could set
length to zero:
v a r myArray = [ ” r e d ” , ” g r e e n ” , ” b l u e ” ] ;
myArray . l e n g t h = 0 ;
a l e r t ( ” myArray=” +myArray ) ;

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 72
concat() Method

The concat() method returns the array resulting from appending its
arguments to the array on which it was invoked. Given the script:
v a r myArray = [ ” r e d ” , ” g r e e n ” , ” b l u e ” ] ;
a l e r t ( myArray . c o n c a t ( ” c y a n ” , ” y e l l o w ” ) ) ;
// r e d , g r e e n , b l u e , cyan , y e l l o w

Be careful, though: concat() does not modify the array in place.


v a r myArray = [ ” r e d ” , ” g r e e n ” , ” b l u e ” ] ;
myArray . c o n c a t ( ” c y a n ” , ” y e l l o w ” ) ;
a l e r t ( myArray ) ; // r e d , g r e e n , b l u e

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 73
join() Method

The join() method of JavaScript converts the array to a string and


allows the programmer to specify how the elements are separated in
the resulting string.
Typically, when you print an array, the output is a comma separated
list of the array elements. You can use join() to format the list
v a r myArray = [ ” r e d ” , ” g r e e n ” , ” b l u e ” ] ;
v a r s t r i n g V e r s i o n = myArray . j o i n ( ” / ” ) ;
a l e r t ( s t r i n g V e r s i o n ) ; // r e d / g r e e n / b l u e

One important thing to note is that the join() method will not destroy
the array as a side-effect of returning the joined string of its elements.

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 74
reverse() Method

JavaScript allow you to reverse the elements of the array in place,


meaning you don’t have to save the result as some of the other array
methods we have seen.
v a r myArray = [ ” r e d ” , ” g r e e n ” , ” b l u e ” ] ;
myArray . r e v e r s e ( ) ;
a l e r t ( myArray ) ; // b l u e / g r e e n / r e d

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 75
slice() Method

The slice() method of Array returns a “slice” (subarray) of the array


on which it is invoked.
As it does not operate in place, the original array is unharmed.
The syntax of slice() is
a r r a y . s l i c e ( s t a r t , end ) ;

where the method returns an array containing the elements from index
start up to but not including index end.
If only one argument is given, the method returns the array composed
of all elements from that index to the end of the array.
Note that start and end are allowed to take on negative values.
When negative, these values are interpreted as an offset from the end
of the array.

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 76
slice() Method (contd.)

For example, calling slice(-2) returns an array containing the last two
elements of the array.
v a r myArray = [ 1 , 2 , 3 , 4, 5];
myArray . s l i c e ( 2 ) ; // returns [3 , 4 , 5]
myArray . s l i c e ( 1 , 3 ) ; // returns [2 , 3]
myArray . s l i c e ( = 3 ) ; // returns [3 , 4 , 5]
myArray . s l i c e ( = 3 , = 1); // returns [3 , 4]
myArray . s l i c e ( = 4 , 3 ) ; // returns [2 , 3]
myArray . s l i c e ( 3 , 1 ) ; // returns []

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 77
Table of Contents
1 Introduction
2 Operators
3 Statements
4 Object-Related Statements
5 Functions
6 Objects
7 Array
Manipulating Arrays
8 Event Handling
9 Form Handling
10 JSON
11 jQuery
Elements Selection
Effects & Animation
*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 78
Event Handling

An event is some notable action to which a script can respond.


The browser may trigger some events such as page loading, but most
often they are initiated by user interactions such as when they click,
use a form widget, or even move the mouse over some page element.
An event handler is JavaScript code associated with a particular part
of the document and a particular event.
A handler is executed if and when the given event occurs at the part
of the document to which it is associated.
For example, an event handler associated with a button element could
open an alert dialog when the button is clicked, or a handler associated
with a form field could be used to verify the data the user entered
whenever the value of the form field changes.
Traditionally, the handler associated with a particular action is named
with the event name prefixed by “on.”
For example, a handler for the click event is called onclick.
*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 79
Event Handling (contd.)

Events are not limited to basic user actions associated with the docu-
ment, such as click and mouseover.
For example, browsers support events such as resize, load, and unload,
which are related to window activity such as resizing the window or
loading or unloading a document.
Browsers provide detailed information about the event occurring through
an Event object that is made available to handlers.
The Event object contains contextual information about the event, such
as the exact x and y screen coordinates where some event occurred,
whether modifiers such as the shift key were depressed at the time of
the event, and so on.
Events that are the result of user actions typically have a target -the
HTML element at which the event is occurring.
For example, a click event’s target would be the element, such as
< img > or < p >, that the user clicked on.
*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 80
Event Handling (contd.)
Event handlers are therefore bound to particular DOM elements.
When the event that a handler handles occurs on the element to which
it is bound, the handler is executed.
Handlers can be bound to elements in numerous ways, including:
Using traditional HTML event handler attributes directly in markup.
<p o n c l i c k =”m y F u n c t i o n”> C l i c k me</p>

Using script to set handlers to be related to an object. For example:


document . g e t E l e m e n t B y I d ( ” p l ” ) . o n c l i c k=m y F u n c t i o n ;

Using proprietary methods such as Internet Explorer’s attachEvent()


method. For example:
document . g e t E l e m e n t B y I d ( ” p l ” ) . a t t a c h E v e n t ( ” o n c l i c k ” ,
myFunction ) ;

Using DOM methods to set event listeners using a node’s


addEventListener() method. For example:
document . g e t E l e m e n t B y I d ( ” p l ” ) . a d d E v e n t L i s t e n e r ( ” o n c l i c k ” ,
myFunction , f a l s e ) ;
*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 81
Event Handling (contd.)

Just as there are many ways to bind events to elements, there are
several ways events are triggered:
Implicitly by the browser in response to some user-or JavaScript-initiated
action
Explicitly by JavaScript using DOM1 methods. For example:
document . f o r m s [ 0 ] . s u b m i t ( ) ;

Explicitly using proprietary methods such as Internet Explorer’s fireEvent()


method
Explicitly by JavaScript using the DOM2 dispatchEvent() method

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 82
Event Binding with HTML Attributes

HTML5 supports core event bindings for most elements.


These bindings are element attributes, such as onclick and onmouseover,
which can be set equal to the JavaScript that is to be executed when
the given event occurs at that object.
As the browser parses the page and creates the document object hier-
archy, it populates event handlers with the JavaScript code bound to
elements using these attributes.
For example, consider the following simple binding that defines a click
handler for a paragraph element:
<p o n c l i c k =” a l e r t ( ’ You h a v e c l i c k e d me’ ) ; ” > C l i c k Me</p>

The attribute onclick is not JavaScript; it is markup that relates to the


event handler onclick.

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 83
Event Binding with HTML Attributes (contd.)

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 84
Event Binding with HTML Attributes (contd.)

<head>< t i t l e >Document</ t i t l e >


<s t y l e >
l a b e l [ f o r ] { c u r s o r : p o i n t e r ; c u r s o r : hand }
l i { m a r g i n : 0 0 10 px}</ s t y l e >
</head>
<body o n l o a d =” a l e r t ( ’ E v e n t demo h a s l o a d e d ’ ) ; ” >
<form o n r e s e t =” a l e r t ( ’ Form r e s e t ’ ) ; ” o n s u b m i t=” a l e r t ( ’ Form s u b m i t ’ ) ;
r e t u r n f l a s e ;” >
<u l >
<l i >
< l a b e l f o r =” f o n b l u r ”> o n b l u r : </ l a b e l >
<i n p u t t y p e =” t e x t ” v a l u e =” C l i c k i n t o f i e l d and t h e n l e a v e ”
s i z e =”40” i d =” f o n b l u r ”
o n b l u r =” a l e r t ( ’ L o s t F o c u s ! ’ ) ; ” >
</ l i >
<l i >
< l a b e l f o r =” f o n c l i c k ”> o n c l i c k : </ l a b e l >
<i n p u t t y p e =”b u t t o n ” v a l u e =” c l i c k me” i d =” f o n c l i c k ”
o n c l i c k =” a l e r t ( ’ B u t t o n C l i c k e d ! ’ ) ; ” >
</ l i >
<l i >
< l a b e l f o r =”f o n c h a n g e ”>o n c h a n g e : </ l a b e l >
<i n p u t t y p e =” t e x t ” v a l u e =”c h a n g e t h i s t e x t t h e n l e a v e ”
*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 85
Event Binding with HTML Attributes (contd.)

s i z e =”40” i d =” f o n c c h a n g e ”
o n c h a n g e=” a l e r t ( ’ Changed ! ’ ) ; ” >
</ l i >
<l i >
< l a b e l f o r =” f o n d b l c l i c k ”> o n d b l c l i c k : </ l a b e l >
<i n p u t t y p e =”b u t t o n ” v a l u e =”D o u b l e c l i c k me” i d =” f o n d b l c l i c k ”
o n d b l c l i c k =” a l e r t ( ’ B u t t o n d o u b l e C l i c k e d ! ’ ) ; ” >
</ l i >
<l i >
< l a b e l f o r =” f o n f o c u s ”> o n f o c u s : </ l a b e l >
<i n p u t t y p e =” t e x t ” v a l u e =” c l i c k i n t o f i e l d ”
i d =” f o n f o c u s ” o n f o c u s =” a l e r t ( ’ G a i n e d f o c u s ’ ) ; ” >
</ l i >
<l i >
< l a b e l f o r =”f o n k e y d o w n”>onkeydown : </ l a b e l >
<i n p u t t y p e =” t e x t ” v a l u e =” P r e s s k e y and r e l e a s e ” s i z e =”40”
i d =”f o n k e y d o w n ” onkeydown=” a l e r t ( ’ Key down ! ’ ) ; ” >
</ l i >
<l i >
< l a b e l f o r =” f o n k e y p r e s s ”> o n k e y p r e s s : </ l a b e l >
<i n p u t t y p e =” t e x t ” v a l u e =”Type h e r e ” s i z e =”40” i d =” f o n k e y p r e s s ”
o n k e y p r e s s =” a l e r t ( ’ Key p r s s e d ’ ) ; ” >
</ l i >
*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 86
Event Binding with HTML Attributes (contd.)

<l i >
< l a b e l f o r =”f o n k e y u p ”>o n k e y u p : </ l a b e l >
<i n p u t t y p e =” t e x t ” v a l u e =” P r e s s k e y and r e l e a s e ” s i z e =”40”
i d =”f o n k e y u p ” o n k e y u p=” a l e r t ( ’ Key up ! ’ ) ; ” >
</ l i >
< l i >o n l o a d : An a l e r t was shown when t h e document l o a d e d </ l i >
<l i >
< l a b e l f o r =”fonmousedown”>onmousedown : </ l a b e l >
<i n p u t t y p e =”b u t t o n ” v a l u e =” C l i c k and h o l d ” i d =”fonmousedown ”
onmousedown=” a l e r t ( ’ Mouse down ! ’ ) ; ” >
</ l i >
<l i >
onmousemove : Move mouse o v e r t h i s <a h r e f =”#”
onmousemove=” a l e r t ( ’ Mouse moved ! ’ ) ; ” > l i n k </a>
</ l i >
<l i >
onmouseout : P o s i t i o n mouse <a h r e f =”#”
onmouseout=” a l e r t ( ’ Mouse o u t ! ’ ) ; ” > h e r e </a> and t h e n h e r e
</ l i >
<l i >
< l a b e l f o r =”fonmouseup”>onmouseup : </ l a b e l >
<i n p u t t y p e =”b u t t o n ” v a l u e =” C l i c k and r e l e a s e ”
i d =”fonmouseup ” onmouseup=” a l e r t ( ’ Mouse up ! ’ ) ; ” >
*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 87
Event Binding with HTML Attributes (contd.)

</ l i >
<l i >
< l a b e l f o r =” f o n r e s e t ”> o n r e s e t : </ l a b e l >
<i n p u t t y p e =” r e s e t ” v a l u e =” R e s e t demo” i d =” f o n r e s e t ”>
</ l i >
<l i >
< l a b e l f o r =” f o n s e l e c t ”> o n s e l e c t : </ l a b e l >
<i n p u t t y p e =” t e x t ” v a l u e =” S e l e c t t h i s t e x t ” s i z e =”40”
i d =” f o n s e l e c t ” o n s e l e c t =” a l e r t ( ’ S e l e c t e d ! ’ ) ; ” >
</ l i >
<l i >
< l a b e l f o r =” f o n s u b m i t ”>o n s u b m i t : </ l a b e l >
<i n p u t t y p e =”s u b m i t ” v a l u e =”s u b m i t ” i d =” f o n s u b m i t ”>
</ l i >
< l i >o n u n l o a d : Try t o l e a v e document by f o l l o w i n g t h i s
<a h r e f =” J a v a S c r i p t T e s t i n g . h t m l”>L i n k </a></ l i >
</u l >
</form>

</body>
</html>

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 88
Binding Event Handler Attributes with JavaScript

While you can bind event handlers to parts of a document using event
attributes in markup, it is generally much more appropriate to bind
them within JavaScript instead, especially if you wish to add or remove
handlers dynamically.
Further, doing things in code tends to improve the separation between
the structure of the document and its logic and presentation.
To use JavaScript for this task, it is important to understand that
event handlers are accessed as methods of the objects to which they
are bound.
<p i d =”pDemo”> C l i c k Me</p>

< s c r i p t t y p e =” t e x t / j a v a s c r i p t ”>

document . g e t E l e m e n t B y I d ( ” pDemo ” ) . o n c l i c k=f u n c t i o n ( )


{
a l e r t ( ” You c l i c k e d me ” ) ;
};
</ s c r i p t >

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 89
Binding Event Handler Attributes with JavaScript (contd.)

Of course, you do not have to use an anonymous function when setting


a handler. For example, notice here how we set a mouseover handler
to an existing function:
<p i d =”pDemoOver”>Mouse Over Me</p>

< s c r i p t t y p e =” t e x t / j a v a s c r i p t ”>
function showAlert ()
{
a l e r t ( ” Mouse Over Me ” ) ;
}
document . g e t E l e m e n t B y I d ( ” pDemoOver ” ) . o n m o u s e o v e r=s h o w A l e r t ;
</ s c r i p t >

Regardless of how the function used is defined, you must make sure to
register the event handler after the HTML element has been added to
the DOM tree; otherwise, you’ll cause a runtime error by trying to set
a property (an event handler) of a nonexistent object.

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 90
Return Values

A very useful feature of traditional element-placed event handlers is


that their return values can affect the default behavior of the event.
The default behavior is what would normally happen when the event
occurs if left unhandled.
For example, the default behavior of a click on a link (< a > tag) is to
load the link target specified in the href attribute in the browser.
The default behavior of activating a submit button is the submission
of the form.
The default behavior of a reset button is to clear form field values, and
so on.

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 91
Return Values (contd.)

To cancel the default behavior of an event, simply return false from its
event handler. For example, to kill a link load, we return false:
<a h r e f =” h t t p s : / /www . g o o g l e . com/” o n c l i c k =” r e t u r n f a l s e ;” >
To g o o g l e </a>

In this example, with JavaScript on, you never leave the page. Of
course, more likely you aren’t going to do this, but you might imagine
something like a confirmation:
<a h r e f =” h t t p s : / /www . g o o g l e . com/”
o n c l i c k =” r e t u r n c o n f i r m ( ’ Do you want t o v i s i t G o og l e ’ ) ; ” >
To g o o g l e </a>

A positive response to confirm() returns true, and the default action of


page loading occurs.
A false response cancels the link load.

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 92
Table of Contents
1 Introduction
2 Operators
3 Statements
4 Object-Related Statements
5 Functions
6 Objects
7 Array
Manipulating Arrays
8 Event Handling
9 Form Handling
10 JSON
11 jQuery
Elements Selection
Effects & Animation
*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 93
Form Handling

One of the most common uses of JavaScript is for checking the con-
tents of forms before sending them to server-side programs. Commonly
known as form validation.
It can be quite annoying to fill out a form on a Web site only to have
the page returned with complaints about malformed data after a round
trip to the server.
With JavaScript, we can cut down on the frustration of waiting for
failure and improve the usability of Web forms by checking the data
before it is submitted to the server for processing.
There are two primary approaches we can take to validate form entries
using JavaScript.
The first involves checking each field as it is filled in, either upon blur
or using a keyboard mask if appropriate.
The second approach is to check all the fields of a form when a sub-
mission is triggered.
*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 94
Form Basics

JavaScript provides access to the forms within an HTML document


through the Form object (known as an HTMLFormElement in the
DOM), which is a child of the Document object.
As with all Document objects, the properties and methods of this object
correspond to the various features and attributes of a < form > tag,
the common attributes of which are summarized here:
<form>
i d =”U n i q u e a l p h a n u m e r i c i d e n t i f i e r ”
name=”U n i q u e a l p h a n u m e r i c i d e n t i f i e r ( s u p e r s e d e d by i d a t t r i b u t e ) ”
a c t i o n =”URL t o w h i c h form d a t a w i l l be s u b m i t t e d ”
e n c t y p e =”E n c o d i n g t y p e f o r form d a t a ”
method=”Method by w h i c h t o s u b m i t form d a t a ( e i t h e r GET o r POST) ”
t a r g e t =”Name o f f r a m e i n w h i c h r e s u l t o f s u b m i s s i o n w i l l a p p e a r ”>

Form f i e l d e l e m e n t s and o t h e r markup g i v i n g form s t r u c t u r e

</form>

Traditionally, form objects have only two form-specific methods.


*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 95
Form Basics (contd.)
The reset() method clears the form’s fields, similar to clicking a button
defined by <input type=“reset”>.
The submit() method triggers the submission of the form, similar to
clicking the button defined by <input type=“submit”>.
In addition to the ability to trigger form reset and submission, you often
want to react to these events as well, so the < form > tag supports
the corresponding onreset and onsubmit event handler attributes.
As with all events, handler scripts can return a value of false to cancel
the reset or submit.
Returning true (or not returning a value) permits the event to occur
normally.
Given this behavior, the following form would allow all form resets but
deny submissions:
<form a c t i o n =” s e n d i t . c g i ” method=” g e t ” o n r e s e t =” r e t u r n t r u e ; ”
o n s u b m i t=” r e t u r n f a l s e ;” >
. . . form f i e l d s h e r e . . .
</form>
*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 96
Accessing Forms and Fields
In general, a form is accessed by name, or id.
<form name=”c u s t o m e r f o r m ” i d =”c u s t o m e r f o r m ” a c t i o n =”#”
method=” g e t ”>
<i n p u t t y p e =” t e x t ” name=” f i r s t n a m e =” i d =” f i r s t n a m e =” /><b r />
<i n p u t t y p e =” t e x t ” name=” l a s t n a m e =” i d =” l a s t n a m e =” />
. . . more f i e l d s . . .
</form>

If we assume this is the first form in the document, we might access


the form using the traditional document.forms[] collection indexed by
numeric value:
a l e r t ( document . f o r m s [ 0 ] . method ) ;

Alternatively, we could use the name attribute of the form to retrieve


it via the collection:
a l e r t ( document . f o r m s [ c u s t o m e r f o r m ] . method ) ;

Since standard DOM methods can be employed, we can use the com-
mon getElementById() method:
a l e r t ( document . g e t E l e m e n t B y I d ( ” c u s t o m e r f o r m ” ) . method ) ;
*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 97
Accessing Forms and Fields (contd.)

Retrieving the fields of the forms is easily performed using the getEle-
mentById() method, assuming a unique id value.
<!DOCTYPE html>
<html>
<head>
< t i t l e >Form O b j e c t Test </ t i t l e >
</head>
<body>
<h2 a l i g n =” c e n t e r ”>T e s t Form</h2>
<form a c t i o n =” J S A c c e s s i n g . h t m l ”
method=” p o s t ” name=” t e s t f o r m ” i d =” t e s t f o r m ”
o n r e s e t =” r e t u r n c o n f i r m ( ’ Are you s u r e ? ’ ) ; ”
o n s u b m i t=” a l e r t ( ’ Not r e a l l y s e n d i n g da ta ’ ) ; r e t u r n f a l s e ;” >
< l a b e l >Name :
<i n p u t t y p e =” t e x t ” i d =” f i e l d 1 ” name=” f i e l d 1 ” s i z e =”20”
v a l u e =”J o e Smith ” /></ l a b e l >
<b r />
< l a b e l >P a s s w o r d :
<i n p u t t y p e =”p a s s w o r d ” i d =” f i e l d 2 ” name=” f i e l d 2 ”
s i z e =”8” m a x l e n g t h =”8” /></ l a b e l >
<b r />
*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 98
Accessing Forms and Fields (contd.)

<i n p u t t y p e =” r e s e t ” v a l u e =” r e s e t ”/>
<i n p u t t y p e =”s u b m i t ” v a l u e =”s u b m i t ” />
<i n p u t t y p e =”b u t t o n ” v a l u e =”Do r e s e t ”
o n c l i c k =”document . t e s t f o r m . r e s e t ( ) ; ” />
<i n p u t t y p e =”b u t t o n ” v a l u e =”Do s u b m i t ”
o n c l i c k =”document . t e s t f o r m . s u b m i t ( ) ; ” />
</form>
<h r />
<h2 a l i g n =” c e n t e r ”>Form O b j e c t P r o p e r t i e s </h2>
< s c r i p t t y p e =” t e x t / j a v a s c r i p t ”>
<!= =
// Change document . t e s t f o r m t o document . f o r m s [ 0 ] and you w i l l
// g e t t h e same r e s u l t .
w i t h ( document . t e s t f o r m )
{
document . w r i t e ( ” a c t i o n : ”+ a c t i o n +”<b r / >”);
document . w r i t e ( ” e n c o d i n g : ”+ e n c o d i n g+”<b r / >”);
document . w r i t e ( ” l e n g t h : ”+ l e n g t h +”<b r / >”);
document . w r i t e ( ” method : ”+method+”<b r / >”);
document . w r i t e ( ” name : ”+name+”<b r / >”);
document . w r i t e ( ” a c t i o n : ”+ a c t i o n +”<b r / >”);
document . w r i t e ( ” t a r g e t : ”+ t a r g e t +”<b r / >”);

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 99
Accessing Forms and Fields (contd.)

f o r ( v a r i =0; i <document . t e s t f o r m . l e n g t h ; i ++)


document . w r i t e ( ” e l e m e n t [”+ i + ” ] . t y p e=”+
document . t e s t f o r m . e l e m e n t s [ i ] . t y p e+”<b r / >”);
}
= =>
</ s c r i p t >
</body>
</html>

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 100
Form Validation

Checking form contents before submission saves server processor cycles


as well as the user’s time waiting for the network round trip to see if
the proper data has been entered into the form.
The first issue to consider with form validation is when to catch form
fill-in errors. There are three possible choices:
Before they happen (prevent them from happening)
As they happen
After they happen
Typically, a set of validation functions in the form’s onsubmit event
handler is responsible for the validation.
If a field contains invalid data, a message is displayed and submission
is canceled by returning false from the handler.
If the fields are valid, the handler returns true and submission continues
normally.

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 101
Form Validation (contd.)

<html>
<head>
< t i t l e >O v e r l y S i m p l i s t i c Form V a l i d a t i o n </ t i t l e >
< s c r i p t t y p e =” t e x t / j a v a s c r i p t ”>
function validate ()
{
i f ( document . myform . u s e r n a m e . v a l u e = = ” ” )
{
a l e r t ( ” Username i s r e q u i r e d ” ) ;
return false ;
}
return true ;
}
</ s c r i p t >
</head>
<body><form name=”myform ” i d =”myform ” method=” g e t ”
a c t i o n =” J S A c c e s s i n g . h t m l ” o n s u b m i t=” r e t u r n v a l i d a t e ( ) ; ” >
Username :
<i n p u t t y p e =” t e x t ” name=”u s e r n a m e ” i d =”u s e r n a m e ” s i z e =”30” />
<i n p u t t y p e =”s u b m i t ” v a l u e =”s u b m i t ” />
</form>
</body></html>

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 102
Form Validation

The previous example is not terribly abstract in that the validation


function works with only the username field in that document; it can’t
be applied to a generic field.
Also, the validation doesn’t bring the field that is in error into focus.
Finally, the check of an empty value can be better handled with a
regular expression.
A better example for correcting these deficiencies is presented here:

<!DOCTYPE html>
<html>
<head>
<meta c h a r s e t =” u t f =8”>
< t i t l e >B e t t e r Form V a l i d a t i o n </ t i t l e >
<s c r i p t >
f u n c t i o n isEmpty ( s ) {
v a r v a l i d = /\S+/. t e s t ( s ) ;
return ! valid ;
}
*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 103
Form Validation (contd.)

function validate ()
{
i f ( i s E m p t y ( document . myform . u s e r n a m e . v a l u e ) )
{
a l e r t ( ” E r r o r : Username i s r e q u i r e d . ” ) ;
document . myform . u s e r n a m e . f o c u s ( ) ;
return false ;
}
i f ( i s E m p t y ( document . myform . u s e r p a s s . v a l u e ) )
{
a l e r t ( ” E r r o r : Non=empty p a s s w o r d r e q u i r e d . ” ) ;
document . myform . u s e r p a s s . f o c u s ( ) ;
return false ;
}
return true ;
}

window . o n l o a d = f u n c t i o n ( ) {
document . g e t E l e m e n t B y I d ( ” myform ” ) . o n s u b m i t = v a l i d a t e ;
};
</ s c r i p t >
</head>
*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 104
Form Validation (contd.)

<body>
<form name=”myform ” i d =”myform ” method=” g e t ”
a c t i o n =” h t t p : / /www . j a v a s c r i p t r e f . com”>
Username :
<i n p u t t y p e =” t e x t ” name=”u s e r n a m e ” i d =”u s e r n a m e ”
s i z e =”30” m a x l e n g t h =”60”>
<br>
Password :
<i n p u t t y p e =”p a s s w o r d ” name=” u s e r p a s s ” i d =” u s e r p a s s ”
s i z e =”8” m a x l e n g t h =”8”>
<br>
<i n p u t t y p e =”s u b m i t ” v a l u e =”Submit”>
</form>
</body>
</html>

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 105
Table of Contents
1 Introduction
2 Operators
3 Statements
4 Object-Related Statements
5 Functions
6 Objects
7 Array
Manipulating Arrays
8 Event Handling
9 Form Handling
10 JSON
11 jQuery
Elements Selection
Effects & Animation
*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 106
JSON

For many years, XML was the standard format for structured data.
It was easy to use and similar to HTML with tags that contained data.
Then, JavaScript Object Notation (JSON) was introduced at the be-
ginning of the millennium.
What makes JSON an interesting option is that it’s completely platform
and language independent.
You can use JSON in older systems such as Classic ASP and Java or
newer languages such as C#, Ruby, and PHP.
The data content is text-based, so it’s easily read across all platforms,
and even humans can read and understand a JSON file’s content.
XML is still used in some applications, but JSON is quickly overtaking
the older format as the standard API communication tool.
JSON also works well with Ajax and jQuery, so you can send and receive
asynchronous communications.
*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 107
JSON (contd.)

Asynchronous communication is more user friendly and reduces load


on the web server.
Instead of refreshing the entire web page, you can code your site to
send and receive JSON communication with one HTTP request.
The problem with XML is that it’s an extremely bulky and has a lot of
overhead to use it.
Tags, properties and other bulky data were included in an XML file.
For a small data set, the overhead was huge.
JSON is much simpler, has little overhead to use, and it has a format
that is easy to read.
There are no properties and markup in JSON, which also makes it much
more lightweight.
With XML, properties and markup determined a file’s syntax structure.
Any missing tag could throw off any XML parser.
*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 108
JSON (contd.)

JSON also requires proper structure, but it’s much easier to implement
and create.
JSON is also universal, so you can use JSON with any language or
platform.

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 109
JSON used for

Most people use JSON for asynchronous transactions.


The Ajax or jQuery code passes information asynchronously to the main
language such as C# or PHP.
Traditionally, when a user sent data to a web application, the user
clicked a “Submit” button and the browser would send the information
to the web server.
Once the data was processed, a response is sent back to the user’s
browser and a new page is displayed.
All elements of the new web page were retrieved and rerendered on the
user’s browser including navigation, sidebars, footers and any common
content.
This was sufficient for older web applications, but users have become
more demanding and want faster web responses.
Asynchronous web calls solve the issue of speed and fast responses.
*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 110
JSON used for (contd.)

Asynchronous web calls only send the form portion of a web page back
to the web server.
The footer, header, sidebars and any other static components on the
page aren’t sent to the server.
The result? A faster response and users don’t have to wait for a re-
sponse.
It only needs to process the data, which is usually processed on a
database.
JSON is used to pass data back and forth in a web application.
JSON is also used in APIs.

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 111
Basic Syntax

The basic JSON syntax is a variable-value pair.


” F i r s t N a m e ” : ” John ”
” F i r s t N a m e ” : ” John ” , ” F i r s t N a m e ” : ” J a n e ” , ” F i r s t N a m e ” : ” Joan ”

You must always specify the variable name when you work with JSON
data even if it’s the same variable name throughout the entire file.
After each variable name is a colon. This is also standard and must be
used to separate the variable names from the values.
Finally, notice the comma in between each pair. A comma separates
the variable-value pairs.
Whether it’s 2 or 1000 records, each record must be separated with a
comma.
A JSON variable-value pair with integers or decimal numbers don’t use
quotes around the values.
” AccountNumber ” : 1 0 0 1 , ” AccountNumber ” : 1 0 0 2 , ” AccountNumber ” : 1 0 0 3

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 112
Basic Syntax (contd.)

You can also use true and false values and even arrays.
” ActiveAccount ”: true , ” ActiveAccount ”: f a l s e , ” ActiveAccount ”: true

How a list of phone numbers contained in an array would look like in


JSON.
” PhoneNumbers ”:[”555 = 555 = 5555” , ”666 = 666 = 6666” , ”777 = 777 = 7777”]

You can also have multiple arrays. For instance, you probably have
more than one phone number for more than one customer.
” PhoneNumbers ”:[”555 = 555 = 5555” , ”666 = 666 = 6666” , ”777 = 777 = 7777”] ,
” PhoneNumbers ”:[”444 = 444 = 4444” , ”333 = 333 = 3333” , ”222 = 222 = 2222”]

One last type of value is null. Notice that the last pair has no value.
” F i r s t N a m e ” : ” John ” , ” F i r s t N a m e ” : ” J a n e ” , ” F i r s t N a m e ” :

JSON objects can also be passed within a parent object.

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 113
JSON Object

The pairs are not complete, valid JSON syntax.


If you tried to send any of the above data in an application, it would
tell you that the JSON format is not valid, because you don’t have it
in an object.
JSON objects are similar to JavaScript objects.
var user = { };
u s e r . F i r s t N a m e = ” John ” ;
u s e r . LastName = ” Smith ” ;

Now let’s take a look at how an object is created in JSON


{ ” F i r s t N a m e ” : ” John ” , ” LastName ” : ” Smith ” }

JSON uses the open and closing brackets, but no object is assigned.
That’s because we don’t need an object named yet.
We let the processing language determine the object name.
Remember that JSON only cares about data and formatting data.
*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 114
JSON Object (contd.)
It does not care about the processing language whether it’s C#, Ruby,
PHP, or Java.
{
” F i r s t N a m e ” : ” John ” , ” LastName ” : ” Smith ” , ” PhoneNumbers ” :
{ ” t y p e ” : ”Home ” , ” number ” : ”333 = 333 = 3333”} ,

{ ” t y p e ” : ” C e l l ” , ” number ” : ”444 = 444 = 4444”}


}

We have the opening and closing brackets for the main object, and
then we see another opening and closing brackets.
These secondary brackets also indicate an object, but it’s an object
within an object.
Notice that the object is set after the “PhoneNumbers” variable.
When you use these structures, the JSON engine then knows that the
variable contains an object.
The object is referred to with the variable name, so this object is re-
ferred to as the PhoneNumber object.
*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 115
HTML Example

JSON is written in the script tags. You can also create external JSON
files.
JSON files have the .json file extension.
<html><body>
<h2>JSON U s e r A cc o un t Example </h2>
<p i d =”m y u s e r”></p>
<s c r i p t >
var u s e r = ’{
” F i r s t N a m e ” : ” John ” , ” LastName ” : ” Smith ” , ” PhoneNumbers ” :
{
” t y p e ” : ”Home ” , ” number ” : ”333 = 333 = 3333”
},
{
” t y p e ” : ” C e l l ” , ” number ” : ”444 = 444 = 4444”
}
} ’;
v a r j o b j e c t = JSON . p a r s e ( u s e r ) ;
document . g e t E l e m e n t B y I d ( ” m y u s e r ” ) . innterHTML = j o b j e c t . F i r s t N a m e
</ s c r i p t >
</body></html>

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 116
HTML Example (contd.)

We’ve turned the JSON object into a string and assigned it to a


JavaScript variable named “user.
The string is important, because JavaScript won’t recognize the plain
text values as a JSON object until we call a specific JSON function.
The next step is to parse the JSON into an object.
You can use the JSON parse function to turn the string into an object.
The JSON string is now converted into an object and transferred to
the jobject JavaScript object variable.
Finally, you probably want to display the object to your users.
We set up a < p > object to display the JSON information.
You can use the JavaScript innterHTML property to write data to your
web page.
The above code takes the FirstName property from the object and
displays it in the myuser < p > tag.
*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 117
JSON Arrays

JSON arrays use one variable name to contain several values.


A visual representation of an JSON array variable.
All array variables start with index 0.
Let’s first take a look at the properly created JSON array.
{ ” C u s t o m e r O r d e r s ” : [ 1 0 0 , 1 0 1 , 102 ] }

We use a CustomerOrders array that contains a list of customer order


IDs.
Finally, you should know how to create multiple arrays within a JSON
object.
{ ” C u s t o m e r O r d e r s ” : [ 1 0 0 , 1 0 1 , 102 ] ,
” C u s t o m e r O r d e r s ” : [ 2 0 0 , 2 0 1 , 202 ] }

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 118
Using JSON Arrays in JavaScript

<html>
<body>
<h2>JSON U s e r A cc o un t Example </h2>
<p i d =”m y u s e r”></p>
<s c r i p t >
var u s e r = ’{
” FirstName ” : ” Joe ” ,
” LastName ” : ” Smith ” ,
” CustomerOrders ” : [
{ ” t y p e ” : ” Red ” , ” O r d e r I d ” : 100 } ,
{ ” t y p e ” : ” B l u e ” , ” O r d e r I d ” : 101 } ,
{ ” t y p e ” : ” G r e e n ” , ” O r d e r I d ” : 102 } ]
} ’;
v a r j o b j e c t = JSON . p a r s e ( u s e r ) ;
var f i r s t n a m e = j o b j e c t . FirstName ;
v a r l a s t n a m e = j o b j e c t . LastName ;
var f i r s t o r d e r = j o b j e c t . CustomerOrders [ 0 ] . OrderId ;
document . g e t E l e m e n t B y I d ( ” m y u s e r ” ) . innerHTML = f i r s t n a m e +
”<br >” + l a s t n a m e + ”<br >” + f i r s t o r d e r ;
</ s c r i p t >
</body>

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 119
JSON Data Types

The following data types are the basic, primitive types available in
JSON.
Numbers - decimal and integers
{ ” L a s t O r d e r I d ” : 100 }

Strings - the text you see with any character, number or special character
{ ” F i r s t N a m e ” : ” John ” }

Booleans - these values equal true or false. True and false are translated
to one and zero respectively
{ ” L a s t O r d e r I d ” : 100 , ” OrderShipped ” : false }

Null - this is a special value that represents no value was given


{ ” CustomerOrders ” : [ 100 , 101 , ] }

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 120
JSON Data Types (contd.)

JSON has two more data types


Object - a variable that contains a list of records
{
” F i r s t N a m e ” : ” J o e ” , ” LastName ” : ” Smith ” ,

” CustomerOrders ” : {
{ ” type ” : ” Red ” , ” O r d e r I d ” : 100 } ,
{ ” type ” : ” B l u e ” , ” O r d e r I d ” : 101 } ,
{ ” type ” : ” G r e e n ” , ” O r d e r I d ” : 102 }
}
}

Array - a variable that contains several values


{ ” C u s t o m e r O r d e r s ” : [ 1 0 0 , 1 0 1 , 102 ] }

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 121
External JSON

[
{
” ID ” : 1 ,
”Name ” : ” M e s s i ” ,
” Age ” : 3 5
},
{
” ID ” : 2 ,
”Name ” : ” Neymar ” ,
” Age ” : 3 5
}
]

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 122
External JSON (contd.)

<h t m l l a n g =”en”>
<body>
<h1>Show d a t a from e x t e r n a l JSON f i l e </h1>
<p i d =”pData”></p>
<s c r i p t >
f e t c h (” j E x t e r n a l . j s o n ”)
. then ( f u n c t i o n ( r e s p o n s e ){
return response . json ( ) ;
})
. then ( f u n c t i o n ( j E x t e r n a l ){
f o r ( v a r i =0; i <j E x t e r n a l . l e n g t h ; i ++){
document . g e t E l e m e n t B y I d ( ” pData ” ) . innerHTML +=
j E x t e r n a l [ i ] . ID + ” = ” + j E x t e r n a l [ i ] . Name +
” = ” + j E x t e r n a l [ i ] . Age + ”< b r />”
}

})
</ s c r i p t >
</body>
</html>

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 123
Table of Contents
1 Introduction
2 Operators
3 Statements
4 Object-Related Statements
5 Functions
6 Objects
7 Array
Manipulating Arrays
8 Event Handling
9 Form Handling
10 JSON
11 jQuery
Elements Selection
Effects & Animation
*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 124
jQuery

JQuery is a client side-scripting library of JavaScript.


You can access any element, make animation, and validate input by
using the library.
No extra code can achieve the result by writing one or few lines of code
instead of writing dozen lines of codes.
You can handle the events easily in the html document; get fast results
from server using Ajax.

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 125
Install jQuery

We can use jQuery in two ways:


If you want to use jQuery file locally, then download it.
Download jQuery from http://jquery.com/download/, put the down-
loaded file in the same folder with your jQuery files, and reference it in
< head > section of html document as following:
<head>
<s c r i p t s r c =” j q u e r y = 1 . 1 1 . 3 . j s ”></ s c r i p t >
</head>

If you do not want to download jQuery, then you can include it in html
document as following:
<head>
< s c r i p t s r c =” h t t p : / / c o d e . j q u e r y . com/ j q u e r y = l a t e s t . j s ”>
</ s c r i p t >
</head>

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 126
First jQuery

<html>
<head>
< t i t l e >j Q u e r y H e l l o World </ t i t l e >
< s c r i p t s r c =” h t t p : / / c o d e . j q u e r y . com/ j q u e r y = l a t e s t . j s ”></ s c r i p t >
< s c r i p t t y p e =” t e x t / j a v a s c r i p t ”>
<!== r u n t h e f u n c t i o n a u t o m a t i c a l l y when web page i s c o m p l e t e l y
l o a d e d .==>
$ ( document ) . r e a d y ( f u n c t i o n ( ) {
$ (”# d i v I D ” ) . h t m l (”<h1>H e l l o World !</h1 >”);
});
</ s c r i p t >
</head>
<body>
<d i v i d =” d i v I D ”> </ d i v >
</body>
</html>

“$” is a symbol of jQuery.

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 127
First jQuery (contd.)

“$( )” accesses an element in current html document.


For example:
$ ( ” s p a n ” ) a c c e s s e s a tag , i t s t a g name i s ” s p a n ” .
$ (”#3”) a c c e s s e s a tag , i t s i d i s ” 3 ” .
$ ( ” . c l s s 5 ” ) a c c e s s e s a tag , i t s c l a s s name i s ” c l s s 5 ” .

$ (” tag ” ) . html ( )

$(“tag”) accesses the “tag”.


.html( ) shows the contents without html symbol.
$ (” tag ” ) . t e x t ( )

$(“tag”) accesses the “tag”.


.text( ) shows contents with html symbol.

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 128
Set CSS Style

$ (” s e l e c t o r ” ) . c s s (” s t y l e ”)

All HTML elements based on their id, classes, types (text, radio etc.),
attributes (id, title, src etc), tag name (div, p, form, table, tr, th, td
etc.) etc are jQuery selectors.
$ (” s e l e c t o r ” ) . c s s (” s t y l e ”)

accesses a specified element, and sets a css style for it.

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 129
Set CSS by ID

$ (”# i d ” ) . c s s ( )

If we want to access any element by its “id”, then we have to use “#”
to select that element. css( ) method can set or change any property.
<html>
<head>
< s c r i p t s r c =” j q u e r y = 3 . 6 . 0 . j s ”></ s c r i p t >
< s c r i p t t y p e =” t e x t / J a v a S c r i p t ”>
function changeColor ( ) {
$ (”# d i v T e s t ” ) . c s s ( ” b a c k g r o u n d = c o l o r ” , ” r e d ” ) ;
}
</ s c r i p t >
</head>
<body>
<d i v i d =” d i v T e s t ” o n c l i c k =” c h a n g e C o l o r ( ) ”
s t y l e =” c u r s o r : p o i n t e r ; w i d t h : 300 px ; H e i g h t : 2 0 px ;
b a c k g r o u n d = c o l o r : #c c c c c c ;” >
C l i c k h e r e to change background c o l o r .
</ d i v >
</body>
</html>

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 130
Set CSS by Tag
$ (”# t a g ” ) . c s s ( )

If we want to access any element by its “tag” name, then we have to


use “tag” name to select that element, css( ) method can set or change
any property.
<html>
<head>
< s c r i p t s r c =” j q u e r y = 3 . 6 . 0 . j s ”></ s c r i p t >
< s c r i p t t y p e =” t e x t / J a v a S c r i p t ”>
function changeColor ( ) {
$ ( ” d i v ” ) . c s s ( ” b a c k g r o u n d =c o l o r ” , ” r e d ” ) ;
}
</ s c r i p t >
</head>
<body>
<d i v o n c l i c k =” c h a n g e C o l o r ( ) ”
s t y l e =” c u r s o r : p o i n t e r ; w i d t h : 300 px ; H e i g h t : 2 0 px ;
b a c k g r o u n d = c o l o r : #c c c c c c ;” >
C l i c k h e r e to change background c o l o r .
</ d i v >
</body>
</html>
*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 131
Set CSS by Class
$ (”. class ”). css ( )

If we want to access any element by “class” name then we have to use


“class name” to select that element, css( ) method can set or change
any property.
<html>
<head>
< s c r i p t s r c =” j q u e r y = 3 . 6 . 0 . j s ”></ s c r i p t >
< s c r i p t t y p e =” t e x t / J a v a S c r i p t ”>
function changeColor ( ) {
$ ( ” . d i v C l a s s ” ) . c s s ( ” b a c k g r o u n d =c o l o r ” , ” r e d ” ) ;
}
</ s c r i p t >
</head>
<body>
<d i v c l a s s =” d i v C l a s s ” o n c l i c k =” c h a n g e C o l o r ( ) ”
s t y l e =” c u r s o r : p o i n t e r ; w i d t h : 300 px ; H e i g h t : 2 0 px ;
b a c k g r o u n d = c o l o r : #c c c c c c ;” >
C l i c k h e r e to change background c o l o r .
</ d i v >
</body>
</html>
*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 132
Set CSS by Specified Tag

” $ ( ” p : nth = c h i l d ( n ) ” ) . c s s ( ) ”
a c c e s s e s t h e ”n” tag , and s e t s a c s s s t y l e .

” $ ( ” p : nth = c h i l d ( 1 ) ” ) . c s s ( ) ”
a c c e s s e s t h e f i r s t tag , and s e t s a c s s s t y l e .

” $ ( ” p : nth = c h i l d ( 4 ) ” ) . c s s ( ) ”
a c c e s s e s t h e f o u r t h tag , and s e t s a c s s s t y l e .

If we want to access any element by “class” name then we have to use


“class name” to select that element, css( ) method can set or change
any property.
<html>
<head>
< s c r i p t s r c =” j q u e r y = 1 . 1 1 . 3 . j s ”> </ s c r i p t >
< s c r i p t t y p e =” t e x t / j a v a s c r i p t ”>
f u n c t i o n setCSS ( ) {
$ ( ’ p : nth = c h i l d ( 1 ) ’ ) . c s s ( ” f o n t = s t y l e ” , ” i t a l i c ” ) ;
$ ( ’ p : nth = c h i l d ( 4 ) ’ ) . c s s ( ” f o n t = s t y l e ” , ” i t a l i c ” ) ;
}
</ s c r i p t >
</head>
*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 133
Set CSS by Specified Tag (contd.)

<body>
<h1>S e l e c t i n g t h e f i r s t and l a s t tag </h1>
<d i v >
<p>I l o v e j Q u e r y 1 tim e </p>
<p>I l o v e j Q u e r y 2 tim e </p>
<p>I l o v e j Q u e r y 3 tim e </p>
<p>I l o v e j Q u e r y 4 tim e </p>
</ d i v >
<i n p u t t y p e =”b u t t o n ” v a l u e =” C l i c k Me” o n c l i c k =”s e t C S S ()” >
</ i n p u t >
</body>
</html>

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 134
$(document).ready( )

“$(document).ready( )” is used to specify a function to execute after


loading web page.
<html>
<head>
< t i t l e >T h i s i s T e s t Page </ t i t l e >
< s c r i p t s r c =” j q u e r y = 3 . 6 . 0 . j s ”></ s c r i p t >
< s c r i p t t y p e =” t e x t / j a v a s c r i p t ”>
$ ( document ) . r e a d y ( f u n c t i o n ( ) {
a l e r t (” ready f u n c t i o n c a l l e d ” ) ; } ) ;
</ s c r i p t ></head>
<body>
<p>Ready F u n c t i o n Example : </p>
</p>
</body>
</html>

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 135
show(duration, callback)

The “show( duration, callback )” shows element with duration.


It has two optional parameters (duration, callback).
The first parameter “duration” is a speed (slow - 600 ms, normal - 400
ms, fast - 200 ms) or you can set a time in milliseconds.
The second parameter “callback” is a function, which is executed after
the show() method is completed.
<html>
<head>
< t i t l e >j Q u e r y show Method</ t i t l e >
< s c r i p t s r c =” j q u e r y = 3 . 6 . 0 . j s ”></ s c r i p t >
< s c r i p t t y p e =” t e x t / j a v a s c r i p t ”>
$ ( document ) . r e a d y ( f u n c t i o n ( ) {
$ (”#btnShow ” ) . c l i c k ( f u n c t i o n ( ) {
$ ( ” p ” ) . show ( ” s l o w ” , f u n c t i o n ( ) {
a l e r t ( ” I am c a l l e d a f t e r p a r a g r a p h i s f u l l y shown ” ) ;
});
});
});
</ s c r i p t >
*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 136
show(duration, callback) (contd.)

</head>
<body>
<i n p u t t y p e =”b u t t o n ” i d =”btnShow ” v a l u e =”Show Me” />
<p s t y l e =” d i s p l a y : none”> T h i s i s a p a r a g r a p h </p>
</body>
</html>

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 137
hide(duration, callback)

The “hide( duration, callback )” hides element with duration.


It has two optional parameters(duration, callback).
The first parameter “duration” is a speed (slow, normal, fast) or you
can set a time in milliseconds.
The second parameter “callback” is a function which is executed after
completing the hide() method.
<h t m l l a n g =”en”>
<head>
< t i t l e >Document</ t i t l e >
< s c r i p t s r c =” j q u e r y = 3 . 6 . 0 . j s ”></ s c r i p t >
< s c r i p t t y p e =” t e x t / j a v a s c r i p t ”>
$ ( document ) . r e a d y ( f u n c t i o n ( ) {
$ (”# b t n H i d e ” ) . c l i c k ( f u n c t i o n ( ) {
$ (” p ” ) . h i d e (” slow ” , f u n c t i o n (){
a l e r t ( ” I am c a l l a f t e r p a r a g r a p h i s f u l l y hidden ” ) ;
});
});
});
</ s c r i p t >
</head>
*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 138
hide(duration, callback) (contd.)

<body>
<i n p u t t y p e =”b u t t o n ” i d =”b t n H i d e ” v a l u e =”H i d e Me” />
<p>T h i s i s a p a r a g r a p h </p>
</body>
</html>

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 139
fadeOut(duration, callback)

The fadeOut(duration, callback) changes the opacity for selected ele-


ments, from visible to hidden.
It has two optional parameters(duration, callback).
The first parameter “duration” is a speed (slow, normal, fast) or you
can set a time in milliseconds.
The second parameter “callback” is a function, which is executed after
the fadeOut() method is completed.
<h t m l l a n g =”en”>
<head>
< t i t l e >Document</ t i t l e >
< s c r i p t s r c =” j q u e r y = 3 . 6 . 0 . j s ”></ s c r i p t >
< s c r i p t t y p e =” t e x t / j a v a s c r i p t ”>
f u n c t i o n fadeOutDiv () {
$ (”# divMsg ” ) . f a d e O u t ( 5 0 0 , f u n c t i o n ( ) {
a l e r t ( ” The f a d e O u t method i s c o m p l e t e d ! ” )
;});
}
</ s c r i p t >
</head>
*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 140
fadeOut(duration, callback) (contd.)

<body>
<d i v >
<i n p u t t y p e =”b u t t o n ” o n c l i c k =”f a d e O u t D i v ( ) ; ” v a l u e =”FadeOut D i v”>
<d i v >
<d i v i d =”divMsg ”
s t y l e =”b a c k g r o u n d = c o l o r : maroon ; c o l o r : w h i t e ; w i d t h :
200 px ; h e i g h t : 200 px ;” > I am d i v </d i v >
</body>
</html>

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 141
fadeIn(duration, callback)

The fadeIn(duration, callback) changes the opacity for selecting ele-


ments, from hidden to visible.
It has two optional parameters(duration, callback).
The first parameter “duration” is a speed (slow, normal, fast) or you
can set a time in milliseconds.
The second parameter “callback” is a function, which is executed after
the fadeIn() method is completed.
<h t m l l a n g =”en”>
<head>
< t i t l e >Document</ t i t l e >
< s c r i p t s r c =” j q u e r y = 3 . 6 . 0 . j s ”></ s c r i p t >
< s c r i p t t y p e =” t e x t / j a v a s c r i p t ”>
function fadeInDiv () {
$ (”# divMsg ” ) . f a d e I n ( 5 0 0 , f u n c t i o n ( ) {
a l e r t ( ” The f a d e I n method i s c o m p l e t e d ! ” ) ; } ) ; }
</ s c r i p t >
</head>
<body>
<d i v >
*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 142
fadeIn(duration, callback) (contd.)

<i n p u t t y p e =”b u t t o n ” o n c l i c k =” f a d e I n D i v ( ) ; ” v a l u e =”F a d e I n D i v”>


<d i v >
<d i v i d =”divMsg ”
s t y l e =”b a c k g r o u n d = c o l o r : maroon ; c o l o r : w h i t e ; w i d t h : 200 px ;
h e i g h t : 200 px ; d i s p l a y : none ;” > I am d i v </d i v >
</body>
</html>

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 143
animate( )

The “animate(arguments)” method is used to create customized ani-


mations.
( s e l e c t o r ) . animate ({ s t y l e s } , speed , e a s i n g , c a l l b a c k )

The “width, height, opacity, fontSize, opposition” parameters define


the CSS properties to be animated.
The parameter “duration” has three possible values: Slow, Normal,
Fast, or you can set the time in milliseconds.
easing is optional. Specifies the speed of the element in different points
of the animation. Default value is “swing”.
Possible values: “swing” - moves slower at the beginning/end, but
faster in the middle and “linear” - moves in a constant speed
The parameter “callback” is a function, which is executed after the
animation completes.

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 144
animate( ) (contd.)

<h t m l l a n g =”en”>
<head>
< t i t l e >Document</ t i t l e >
< s c r i p t s r c =” j q u e r y = 3 . 6 . 0 . j s ”></ s c r i p t >
< s c r i p t t y p e =” t e x t / j a v a s c r i p t ”>
f u n c t i o n animateDiv () {
$ (”# divMsg ” ) . a n i m a t e ( {
w i d t h : ’ 3 5 0 px ’ , h e i g h t : ’ 3 5 0 px ’ , o p a c i t y : ’ 0 . 5 ’ ,
f o n t S i z e : ’ 3 em ’ , l e f t : ’ 4 5 0 px ’ } ,
’ slow ’ , f u n c t i o n ( ){
a l e r t ( ” The a n i m a t e method i s c o m p l e t e d ! ” ) }
); }
</ s c r i p t >
</head>
<body>
<d i v ><i n p u t t y p e =”b u t t o n ” o n c l i c k =”a n i m a t e D i v ( ) ; ”
v a l u e =”a n i m a t e t o D i v”><d i v ><b r />
<d i v i d =”divMsg ”
s t y l e =”b a c k g r o u n d : g r e e n ; h e i g h t : 200 px ; w i d t h : 200 px ;
p o s i t i o n : a b s o l u t e ;” > I am d i v w i t h some custom a n i m a t i o n </d i v >
</body>
</html>

*JavaScript - The Complete Reference (Thomas A. Powell) Dr. Monoj Kumar Muchahari 145

You might also like