You are on page 1of 241

Learning & Knowledge Education - India

Day 2
2007 IBM Corporation

Learning & Knowledge Education - India

JavaScript
2007 IBM Corporation

Learning & Knowledge Education - India

Objectives

Introduction to JavaScript
Introduction to JavaScript programming language
Using Script tag
Inserting Java Script into tags
Linking Java Script from separate files

JavaScript expression and Operators


Defining and naming variables
Data Types
Expression
Operators Arithmetic, String, Logical, Assignment, typeof

2007 IBM Corporation

Learning & Knowledge Education - India

Objectives (Contd.)

Functions and Flow Control


Flow Control

Ifelse
For loops
while loops
Break and continue statements

Using JavaScript functions

Built in functions
User defined functions
Returning values from functions
Events, Event Handlers
2007 IBM Corporation

Learning & Knowledge Education - India

Objectives (Contd.)

Objects and Arrays


Properties and Methods
Browser Object Hierarchy
Addressing Objects
Creating Objects
Objects and Variables
External Objects
Security Implications
Arrays and Objects

2007 IBM Corporation

Learning & Knowledge Education - India

Objectives (Contd.)

Document Object Model


Introduction to DOM
The Navigator Object
The Window Object
Communicating between windows
Working With Frames in the DOM
The Document object
The Location & History Object
Image Object
Link Object

2007 IBM Corporation

Learning & Knowledge Education - India

Objectives (Contd.)

Form Validation The Form Object Model


Recap of Form Elements
Form Tag Events
Controlling Submission
Forms as Navigation
List Events
Buttons
Text Processing

2007 IBM Corporation

Learning & Knowledge Education - India

Objectives (Contd.)

Cookies
Introduction to HTTP Cookies
Formatting Cookies
Persisting Cookies
Cookie Security
JavaScript & Cookies
Reading / Writing Cookies
Modifying and deleting Cookies

2007 IBM Corporation

Learning & Knowledge Education - India

Introduction
To
JavaScript
2007 IBM Corporation

Learning & Knowledge Education - India

Introduction to Java Scripts

What is JavaScript???
JavaScript is a scripting Language created by Netscape

What is a
Scripting
Language???

10

Scripting Language is a lightweight


programming language.
Scripting Languages are not
needed to be compiled.
The language is interpreted at
runtime.

2007 IBM Corporation

Learning & Knowledge Education - India

Introduction to JavaScript (Contd.)


A JavaScript is usually directly embedded in an HTML page.
External JavaScripts can be created which can be used by
HTML pages.
JavaScript adds interactivity to HTML pages.
JavaScript's are integrated into the browsing environment.

11

2007 IBM Corporation

Learning & Knowledge Education - India

Introduction to JavaScript (Contd.)


Java is a programming
Is
JavaScript
same as
Java???

language which requires


compilation and interpretation.

Java is used to make large


scale applications.

JavaScript is a scripting
language which just requires
interpretation. The script is some
set of commands which the
browser interprets.

JavaScript is used to add


interactivity in HTML Pages.

12

2007 IBM Corporation

Learning & Knowledge Education - India

Types of JavaScript

13

Client-Side JavaScript (CSJS) -- an extended


version of JavaScript that enables the enhancement
and manipulation of web pages and client browsers.

Server-Side JavaScript (SSJS) -- an extended


version of JavaScript that enables back-end access
to databases, file systems, and servers.

Core JavaScript -- the base JavaScript language.

2007 IBM Corporation

Learning & Knowledge Education - India

Core JavaScript

Core JavaScript encompasses all of the statements,

operators, objects, and functions that make up the


basic JavaScript language.

The following objects are part of core JavaScript:


array
date
math
number
string

14

2007 IBM Corporation

Learning & Knowledge Education - India

Client Side Java Scripting

CSJS is composed of core JavaScript and many


additional objects, such as the following:
document
form
frame
window
Navigator
History

15

2007 IBM Corporation

Learning & Knowledge Education - India

Server Side JavaScript

SSJS is composed of core JavaScript and additional


objects and functions for accessing databases and file
systems, sending e-mail, and so on.

16

2007 IBM Corporation

Learning & Knowledge Education - India

Uses of JavaScript (Client Side)


Menus for Navigation
Form Validation
Popup Windows
Password Protecting
Math Functions
Special effects with document and background
Status bar manipulation
Messages
Mouse Cursor Effects
Links

17

2007 IBM Corporation

Learning & Knowledge Education - India

Test Your Understanding

________________ is an extended
version of JavaScript that enables
the enhancement and manipulation
of web pages and client browsers

Client Side JavaScript


Server Side JavaScript
Core JavaScript

18

2007 IBM Corporation

Learning & Knowledge Education - India

Test Your Understanding

________________ is an extended
version of JavaScript that enables
the enhancement and manipulation
of web pages and client browsers

Client Side JavaScript


Server Side JavaScript
Core JavaScript

19

2007 IBM Corporation

Learning & Knowledge Education - India

Syntax rules of JavaScript

Statements may or may not contain a semicolon at


the end.

Multiple statements on one line must be separated by


a semicolon.

JavaScript is case sensitive.

20

2007 IBM Corporation

Learning & Knowledge Education - India

Using <script> tag

The HTML <script> tag is used to enter JavaScript into a HTML.


The <script> tag can be embedded within
<head> tag.
<body> tag.

21

JavaScript in the head section will be executed when called.

Unlimited number of JavaScripts can be placed both in head and


body section in a HTML document.

JavaScript in the body section will be executed while the HTML


page is loaded.

2007 IBM Corporation

Learning & Knowledge Education - India

Using <script> tag


Eg:
<html>
<head><title>Example</title>
</head>
<body>
<script type="text/javascript">
document.write("Hello World!")
</script>
</body>
</html>

Is a standard command for writing output


to a page

22

2007 IBM Corporation

Learning & Knowledge Education - India

How to Handle Older Browsers


Browsers that do not support JavaScript will display the

script as it is. Use the HTML comment tag to prevent this.

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

23

The two forward slashes at the end of comment line


(//) are a JavaScript comment symbol. This prevents
the JavaScript compiler from compiling the line.
2007 IBM Corporation

Learning & Knowledge Education - India

Using an External JavaScript

A JavaScript can be written in an external file, which


can be used by different HTML pages.

The external script cannot contain the <script> tag.


The external file needs to end with the .js extension.

24

2007 IBM Corporation

Learning & Knowledge Education - India

Using External JavaScript (contd.)


document.write("This line
has been writen in the
External JavaScript!!!")
External.js

<html>
<head><title>Example</title>
</head>
<body>
<script src="External.js">
</script>>
<p >
This line has been written in the
html page!!!
</p>
</body>
</html>
JavaScript.html

25

2007 IBM Corporation

Learning & Knowledge Education - India

Test Your Understanding

Select the Correct Statement/s

<script></script> is embedded
within
<head> </head>
<script></script is embedded
within <body></body>
<script></script> is embedded
within <title></title>

26

2007 IBM Corporation

Learning & Knowledge Education - India

Test Your Understanding

Select the Correct Statement/s

<script></script> is embedded
within
<head> </head>
<script></script is embedded
within <body></body>
<script></script> is embedded
within <title></title>

27

2007 IBM Corporation

Learning & Knowledge Education - India

JavaScript
Operators &
Expressions
2007 IBM Corporation

Learning & Knowledge Education - India

JavaScript Variables and expression

JavaScript Variables
Variable:
A variable is a symbolic name that represents
some data in the memory.
A variable value can change during the execution
of the JavaScript.
A variable can be referred by its name to see or
change its value.
Variables are name are case sensitive.
Must begin with a letter or underscore.

29

2007 IBM Corporation

Learning & Knowledge Education - India

Rules of a Variable

Variable Declaration
Variables can be declared using the var statement
var <variable name>=some value
Variables can also be created without using var statement
<variable name>=some value
Eg
var firstname=Samuel
OR
firstname=Samuel

30

2007 IBM Corporation

Learning & Knowledge Education - India

Data Type in JavaScript

JavaScript is a loosely typed language.


Data Type of Variable
Loosely
Typed??

need not be specified


during declaration.

Data types are


automatically converted
during script execution.

31

2007 IBM Corporation

Learning & Knowledge Education - India

Data Type in JavaScript (contd.)

JavaScript recognizes the following type of values:


Values

numbers
string

boolean

9, 3.56

Samuel, Samuel J Palmisano

true or false

null
A Special keyword which refers to
nothing

32

2007 IBM Corporation

Learning & Knowledge Education - India

Data Type in JavaScript (contd.)

33

2007 IBM Corporation

Learning & Knowledge Education - India

JavaScript Operators
Operators

Arithmetic

Assignment

String

Comparison
Logical

34

Conditional

typeof

2007 IBM Corporation

Learning & Knowledge Education - India

JavaScript Operator (contd.)


Arithmetic

35

2007 IBM Corporation

Learning & Knowledge Education - India

JavaScript Operator (contd.)


Comparison

36

2007 IBM Corporation

Learning & Knowledge Education - India

JavaScript Operator (contd.)


Assignment

37

2007 IBM Corporation

Learning & Knowledge Education - India

JavaScript Operator (contd.)


Logical

38

2007 IBM Corporation

Learning & Knowledge Education - India

JavaScript Operator (contd.)


String

39

2007 IBM Corporation

Learning & Knowledge Education - India

JavaScript Operator (contd.)


Conditional

40

2007 IBM Corporation

Learning & Knowledge Education - India

JavaScript Operator (contd.)


typeof

41

2007 IBM Corporation

Learning & Knowledge Education - India

Test Your Understanding


x=20
x=Test
typeof(x) evaluates to

number
string
null

42

2007 IBM Corporation

Learning & Knowledge Education - India

Test Your Understanding


x=20
x=Test
typeof(x) evaluates to

number
string
null

43

2007 IBM Corporation

Learning & Knowledge Education - India

Flow Control
&
Functions
2007 IBM Corporation

Learning & Knowledge Education - India

Flow Control

Conditional Statements
if statement - use this statement if you want to execute some
code only if a specified condition is true.
if...else statement - use this statement if you want to execute
some code if the condition is true and another code if the
condition is false.
if...else if....else statement - use this statement if you want to
select one of many blocks of code to be executed.
switch statement - use this statement if you want to select
one of many blocks of code to be executed.

45

2007 IBM Corporation

Learning & Knowledge Education - India

while statement

46

2007 IBM Corporation

Learning & Knowledge Education - India

break and continue Statements

There are two special statements that can be used inside loops:
break.
continue.

Break
The break command will break the loop and continue executing the
code that follows after the loop (if any).

Continue
The continue command will break the current loop and continue with
the next value.

47

2007 IBM Corporation

Learning & Knowledge Education - India

Example of break statement


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

48

Result

The number is 0
The number is 1
The number is 2

2007 IBM Corporation

Learning & Knowledge Education - India

Example of continue statement


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

49

Result
The number is 0
The number is 1
The number is 2
The number is 4
The number is 5

2007 IBM Corporation

Learning & Knowledge Education - India

For loop

50

2007 IBM Corporation

Learning & Knowledge Education - India

Functions

A function is a reusable piece of code that will be


executed when called for.

A function can be called from anywhere from within


the page or even from other pages if the function is
stored in an external JavaScript (.js) file.

Functions can be embedded in the <head></head>


and within the<body> </body> tag.

51

2007 IBM Corporation

Learning & Knowledge Education - India

Predefined functions in JavaScript

DialogBoxes
alert( message)
Displays an alert box with a
message defined by the
string message.
Eg.
alert(An Error Occurred!)

52

2007 IBM Corporation

Learning & Knowledge Education - India

Predefined functions in JavaScript (contd.)

confirm(message)
When called, it will display the
message and two boxes. One box
is "OK" and the other is "Cancel". If
OK is selected, a value of true is
returned, otherwise a value of false
is returned.
Eg.
confirm(Do you wish to Continue?)

53

2007 IBM Corporation

Learning & Knowledge Education - India

Predefined functions in JavaScript (contd.)

prompt(message)
Displays a box with the message
passed to the function displayed.
The user can then enter text in
the prompt field, and choose OK
or Cancel.
If the user chooses Cancel, a
NULL value is returned. If the
user chooses OK, the string value
entered in the field is returned.
Eg:
prompt(enter your Name)

54

2007 IBM Corporation

Learning & Knowledge Education - India

Predefined functions in JavaScript (contd.)

Conversion Functions
eval(string)
Converts a string to an integer or a float value.
Eg
x=20
y=eval(x)+10
y contains the value 30

55

2007 IBM Corporation

Learning & Knowledge Education - India

Predefined functions in JavaScript (contd.)


isNaN(value)
If the value passed is not a number then a boolean value of
true is returned else the boolean value of false is returned.
Eg
x=Samuel
y=isNaN(x)
The value stored in y is true

56

2007 IBM Corporation

Learning & Knowledge Education - India

Predefined functions in JavaScript (contd.)


parseInt(string)
Converts a string to an integer returning the first integer
encountered which is contained in the string.
Eg
x=77AB67
y=parseInt(x)
y stores the value 77

57

2007 IBM Corporation

Learning & Knowledge Education - India

Predefined functions in JavaScript (contd.)


parseFloat(string)
Converts a string to an float value .
Eg
x=77.5AB67
y=parseFloat(x)
y stores the value 77.5

58

2007 IBM Corporation

Learning & Knowledge Education - India

User Defined Functions

59

2007 IBM Corporation

Learning & Knowledge Education - India

User Defined Functions (contd.)

60

2007 IBM Corporation

Learning & Knowledge Education - India

User Defined Functions (contd.)

61

2007 IBM Corporation

Learning & Knowledge Education - India

Events

62

2007 IBM Corporation

Learning & Knowledge Education - India

Events (contd.)

63

2007 IBM Corporation

Learning & Knowledge Education - India

Event Handlers

64

2007 IBM Corporation

Learning & Knowledge Education - India

Common Event Handlers

65

2007 IBM Corporation

Learning & Knowledge Education - India

Common Event Handlers (contd.)

66

2007 IBM Corporation

Learning & Knowledge Education - India

Common Event Handlers (contd.)

onLoad and onUnload


The onload and onUnload events are triggered when the user
enters or leaves the page.
The onload event is also triggered when the image is loaded.

The showstatus() function will be called when a user enters a page


<body onload=showStatus()>

67

2007 IBM Corporation

Learning & Knowledge Education - India

Common Event Handlers (contd.)

onFocus, onBlur and onChange


The onFocus, onBlur and onChange events are often used in
combination with validation of form fields.

The checkEmail() function will be called whenever the user changes the content of the field:

<input type="text" size="30" id="email"


onchange="checkEmail()">;

68

2007 IBM Corporation

Learning & Knowledge Education - India

Common Event Handlers (contd.)

onSubmit
The onSubmit event is used to validate ALL form fields before
submitting it.
The checkForm() function will be called when the user clicks the submit
button in the form.
<form method="post" action="xxx.htm" onsubmit="return checkForm()">

69

2007 IBM Corporation

Learning & Knowledge Education - India

Common Event Handlers (contd.)

onMouseOver and onMouseOut


onMouseOver and onMouseOut are often used to create
"animated" buttons.

An alert box appears when an onMouseOver event is


detected:
<a href="http://www.ibm.com" onmouseover="alert('An
onMouseOver event)> <img src=ibmlogo.gif" width="100"
height="30"> </a>

70

2007 IBM Corporation

Learning & Knowledge Education - India

Test Your Understanding

71

2007 IBM Corporation

Learning & Knowledge Education - India

Test Your Understanding

72

2007 IBM Corporation

Learning & Knowledge Education - India

Example

73

2007 IBM Corporation

Learning & Knowledge Education - India

Example (contd.)

74

2007 IBM Corporation

Learning & Knowledge Education - India

Example (contd.)

75

2007 IBM Corporation

Learning & Knowledge Education - India

Example (contd.)

76

2007 IBM Corporation

Learning & Knowledge Education - India

Example (contd.)

77

2007 IBM Corporation

Learning & Knowledge Education - India

Example (contd.)

78

2007 IBM Corporation

Learning & Knowledge Education - India

Example (contd.)
function Addition(x,y)
{
var x1=document.form1.text1.value
var y1=document.form1.text2.value
var Ans=document.form1.text3.value
var temp=x1+y1
}

79

2007 IBM Corporation

Learning & Knowledge Education - India

Example (contd.)
function Addition (x,y) {
var x1=parseInt(x)
var y1=parseInt(y)
var Ans=document.form1.text3.value
var temp=x1+y1
}

80

2007 IBM Corporation

Learning & Knowledge Education - India

Example (contd.)
function Addition (x,y) {
var x1=parseInt(x)
var y1=parseInt(y)
var Ans=document.form1.text3.value
var temp=x1+y1
}
<INPUT TYPE=button value= +op
onClick=Addition(text1.value,text2.value)>

81

2007 IBM Corporation

Learning & Knowledge Education - India

Example (contd.)
function Addition (x,y)

var x1=parseInt(x)
var y1=parseInt(y)
var Ans=document.form1.text3.value
var temp=x1+y1
if(Ans==temp){
alert(Your Result agrees with JavaScript!)
document.form1.text1.value=
document.form1.text2.value=
document.form1.text3.value=
}
else{
alert(No, JavaScript evalutes this operation differently)
document.form1.text3.value=
}}

82

2007 IBM Corporation

Learning & Knowledge Education - India

Test Your Understanding

83

2007 IBM Corporation

Learning & Knowledge Education - India

Test Your Understanding

84

2007 IBM Corporation

Learning & Knowledge Education - India

A Complete Program
<html>
<head>
<script type="text/javascript">
function myfunction(txt)

<input type="button"
onClick="myfunction('Good Morning!')"
value="In the Morning">
<input type="button"

onClick="myfunction('Good Evening!')"

alert(txt)

value="In the Evening">

</form>

</script>

<p>

</head>

When you click on one of the buttons, a


function will be called. The function will alert

<body>

the argument that is passed to it.

<form>

</p>
</body>
</html>

85

2007 IBM Corporation

Learning & Knowledge Education - India

Output

86

2007 IBM Corporation

Learning & Knowledge Education - India

myfunction (txt) receives Good Morning!

87

2007 IBM Corporation

Learning & Knowledge Education - India

myfunction (txt) receives Good Evening !

88

2007 IBM Corporation

Learning & Knowledge Education - India

Objects
&
Arrays
2007 IBM Corporation

Learning & Knowledge Education - India

JavaScript Objects
JavaScript is not a true Object Oriented language as C++ or Java
but rather an Object Based language.
Objects in JavaScript are software entities such as the browser
window or an HTML document.

90

2007 IBM Corporation

Learning & Knowledge Education - India

JavaScript Objects (contd.)

91

2007 IBM Corporation

Learning & Knowledge Education - India

JavaScript Objects (contd.)

92

2007 IBM Corporation

Learning & Knowledge Education - India

JavaScript Objects (contd.)

93

2007 IBM Corporation

Learning & Knowledge Education - India

JavaScript Objects (contd.)

94

2007 IBM Corporation

Learning & Knowledge Education - India

JavaScript Objects (contd.)

95

2007 IBM Corporation

Learning & Knowledge Education - India

JavaScript Objects (contd.)

96

2007 IBM Corporation

Learning & Knowledge Education - India

JavaScript Objects (contd.)

97

2007 IBM Corporation

Learning & Knowledge Education - India

JavaScript Objects (contd.)

98

2007 IBM Corporation

Learning & Knowledge Education - India

JavaScript Objects (contd.)

99

2007 IBM Corporation

Learning & Knowledge Education - India

Instances of Computer Objects (contd.)

100

2007 IBM Corporation

Learning & Knowledge Education - India

JavaScript Core Objects

101

2007 IBM Corporation

Learning & Knowledge Education - India

JavaScript Core Objects (contd.)

102

1.

Boolean

2.

Date

3.

Function

4.

Math

5.

Number

6.

String

Boolean

Math

Date

Number

Function

String

2007 IBM Corporation

Learning & Knowledge Education - India

JavaScript Core Objects (contd.)

103

1.

Boolean

2.

Date

3.

Function

4.

Math

5.

Number

6.

String

Boolean

Math

Date

Number

Function

String

2007 IBM Corporation

Learning & Knowledge Education - India

JavaScript Core Objects (contd.)


Boolean Object
This object is used to convert a non boolean value to a
boolean value.
The Boolean Object is an Object Wrapper for a Boolean
value
Boolean object is defined with the new keyword
var BooleanObj=new Boolean()

104

2007 IBM Corporation

Learning & Knowledge Education - India

JavaScript Core Objects (contd.)


All the following lines of code create Boolean objects with an
initial value of false :
var myBoolean=new Boolean()
var myBoolean=new Boolean(0)
var myBoolean=new Boolean(null)
var myBoolean=new Boolean("")
var myBoolean=new Boolean(false)
var myBoolean=new Boolean(NaN)

105

2007 IBM Corporation

Learning & Knowledge Education - India

JavaScript Core Objects (contd.)


All the following lines of code create Boolean objects with an
initial value of true:
var myBoolean=new Boolean(true)
var myBoolean=new Boolean("true")
var myBoolean=new Boolean("false")
var myBoolean=new Boolean("Richard")

106

2007 IBM Corporation

Learning & Knowledge Education - India

Test Your Understanding

107

2007 IBM Corporation

Learning & Knowledge Education - India

Test Your Understanding

108

2007 IBM Corporation

Learning & Knowledge Education - India

JavaScript Core Objects (contd.)

109

1.

Boolean

2.

Date

3.

Function

4.

Math

5.

Number

6.

String

Boolean

Math

Date

Number

Function

String

2007 IBM Corporation

Learning & Knowledge Education - India

JavaScript Core Objects (contd.)


Date Object
The Date object is used to work with dates and times.
An instance of the Date object with the "new" keyword.
An instance of Date object can be created as:
var myDate=new Date()
var myDate=new Date("Month dd, yyyy hh:mm:ss")
var myDate=new Date("Month dd, yyyy")
var myDate=new Date(yy,mm,dd,hh,mm,ss)
var myDate=new Date(yy,mm,dd)
var myDate= new Date(milliseconds)

110

2007 IBM Corporation

Learning & Knowledge Education - India

JavaScript Core Objects (contd.)

111

2007 IBM Corporation

Learning & Knowledge Education - India

JavaScript Core Objects (contd.)

112

2007 IBM Corporation

Learning & Knowledge Education - India

JavaScript Core Objects (contd.)

113

2007 IBM Corporation

Learning & Knowledge Education - India

JavaScript Core Objects (contd.)

114

2007 IBM Corporation

Learning & Knowledge Education - India

JavaScript Core Objects (contd.)

115

2007 IBM Corporation

Learning & Knowledge Education - India

JavaScript Core Objects (contd.)

116

2007 IBM Corporation

Learning & Knowledge Education - India

JavaScript Core Objects (contd.)

117

2007 IBM Corporation

Learning & Knowledge Education - India

JavaScript Core Objects (contd.)

118

2007 IBM Corporation

Learning & Knowledge Education - India

JavaScript Core Objects (contd.)

119

2007 IBM Corporation

Learning & Knowledge Education - India

JavaScript Core Objects (contd.)


Commonly used methods of the Date Object

120

2007 IBM Corporation

Learning & Knowledge Education - India

JavaScript Core Objects (contd.)

121

2007 IBM Corporation

Learning & Knowledge Education - India

JavaScript Core Objects (contd.)

122

1.

Boolean

2.

Date

3.

Function

4.

Math

5.

Number

6.

String

Boolean

Math

Date

Number

Function

String

2007 IBM Corporation

Learning & Knowledge Education - India

JavaScript Core Objects (contd.)

123

2007 IBM Corporation

Learning & Knowledge Education - India

JavaScript Core Objects (contd.)

124

2007 IBM Corporation

Learning & Knowledge Education - India

JavaScript Core Objects (contd.)

125

2007 IBM Corporation

Learning & Knowledge Education - India

JavaScript Core Objects (contd.)

126

2007 IBM Corporation

Learning & Knowledge Education - India

JavaScript Core Objects (contd.)

127

1.

Boolean

2.

Date

3.

Function

4.

Math

5.

Number

6.

String

Boolean

Math

Date

Number

Function

String

2007 IBM Corporation

Learning & Knowledge Education - India

JavaScript Core Objects (contd.)


Math Object
Math object allows to perform common mathematical
functions.
The Math object includes several Mathematical values and
functions.
The Math object need not be defined before using it.

128

2007 IBM Corporation

Learning & Knowledge Education - India

JavaScript Core Objects (contd.)


Mathematical values provided by JavaScript

Math.E
Math.PI
Math.SQRT2
Math.SQRT1_2
Math.LN2
Math.LN10
Math.LOG2E
Math.LOG10E

129

2007 IBM Corporation

Learning & Knowledge Education - India

JavaScript Core Objects (contd.)


Methods of Math object

130

2007 IBM Corporation

Learning & Knowledge Education - India

Test Your Understanding

131

2007 IBM Corporation

Learning & Knowledge Education - India

Test Your Understanding

132

2007 IBM Corporation

Learning & Knowledge Education - India

JavaScript Core Objects (contd.)

133

1.

Boolean

2.

Date

3.

Function

4.

Math

5.

Number

6.

String

Boolean

Math

Date

Number

Function

String

2007 IBM Corporation

Learning & Knowledge Education - India

JavaScript Core Objects (contd.)

134

2007 IBM Corporation

Learning & Knowledge Education - India

JavaScript Core Objects (contd.)

135

2007 IBM Corporation

Learning & Knowledge Education - India

JavaScript Core Objects (contd.)

136

2007 IBM Corporation

Learning & Knowledge Education - India

JavaScript Core Objects (contd.)

137

1.

Boolean

2.

Date

3.

Function

4.

Math

5.

Number

6.

String

Boolean

Math

Date

Number

Function

String

2007 IBM Corporation

Learning & Knowledge Education - India

JavaScript Core Objects (contd.)


String object
The String object is used to manipulate a stored piece of text.
String objects must be created using the new keyword.
JavaScript automatically converts the string primitive to a
temporary String object
A string literal can be embedded within a single or double
quotation marks.

138

2007 IBM Corporation

Learning & Knowledge Education - India

JavaScript Core Objects (contd.)


String primitives and String objects give different results when
evaluated as JavaScript.
Primitives are treated as source code, but String objects are
treated as a character sequence object.

s1 = "2 + 2

// creates a string primitive

s2 = new String("2 + 2") // creates a String object

139

eval(s1)

// returns the number 4

eval(s2)

// returns the string "2 + 2

eval(s2.valueOf());

// returns the number 4

2007 IBM Corporation

Learning & Knowledge Education - India

JavaScript Core Objects (contd.)


Common Methods of String Object

140

2007 IBM Corporation

Learning & Knowledge Education - India

Defining Arrays
An Array object is used to store a set of values in a single
variable name.
An Array object is created with the new keyword.
An array can be created as:
var MyArray=new Array()
An array can also be created by specifying the array size.
var MyArray=new Array(3)

141

2007 IBM Corporation

Learning & Knowledge Education - India

Arrays (contd.)
Data can be entered into an array as:
var MyArray=new Array()
MyArray[0]=Paul
MyArray[1]=Sam
MyArray[2]=Niel
Data can also be entered into an array as:
var MyArray=new Array(Paul,Sam, Niel)

142

2007 IBM Corporation

Learning & Knowledge Education - India

Arrays (contd.)
Accessing Arrays
You can refer to a particular element in an array by referring to
the name of the array and the index number.
The index number starts at 0 .
var MyArray=new Array()
Myarray [0]

143

The starting index

2007 IBM Corporation

Learning & Knowledge Education - India

Document
Object
Model
2007 IBM Corporation

Learning & Knowledge Education - India

Document Object Model


The DOM is a programming API for documents.
It is based on an object structure that closely resembles the structure of the
documents it models.
For instance, consider this table, taken from an HTML document:
<TABLE>
<TBODY>
<TR> <TD>Shady Grove</TD> <TD>Aeolian</TD> </TR>
<TR> <TD>Over the River, Charlie</TD> <TD>Dorian</TD> </TR>
</TBODY>
</TABLE>

145

2007 IBM Corporation

Learning & Knowledge Education - India

Document Object Model (contd.)


Graphical
Graphicalrepresentation
representationof
ofthe
theDOM
DOMof
ofthe
theexample
exampletable
table

146

2007 IBM Corporation

Learning & Knowledge Education - India

Document Object Model (contd.)


With JavaScript you can restructure an entire HTML document.
You can add, remove, change, or reorder items on a page.
To change anything on a page, JavaScript needs access to all
elements in the HTML document. This access, along with
methods and properties to add, move, change, or remove HTML
elements, is given through the Document Object Model (DOM).
In 1998, W3C published the Level 1 DOM specification. This
specification allowed access to and manipulation of every single
element in an HTML page.
All browsers have implemented this recommendation, and
therefore, incompatibility problems in the DOM have almost
disappeared.

147

2007 IBM Corporation

Learning & Knowledge Education - India

Document Object Model (contd.)

Document
Document Tree
Tree

148

2007 IBM Corporation

Learning & Knowledge Education - India

How to access the nodes in an HTML


You can find the element you want to manipulate in several ways:
By using the getElementById() and getElementsByTagName()
methods
By using the parentNode, firstChild, and lastChild properties
of an element node

149

2007 IBM Corporation

Learning & Knowledge Education - India

Navigator Object
Navigator object is the object representation of the client internet
browser or web navigator program that is being used.
This is a top level object to all others object in DOM hierarchy.

150

2007 IBM Corporation

Learning & Knowledge Education - India

Navigator Object Properties


appCodeName The name of the browsers code such as
Internet Explorer
appName The name of the browser.
appVersion The version of the browser.
plugins An array of plug-ins supported by the browser and
installed on the browser.
cpuClass The type of CPU which may be x86.
cookieEnabled A boolean value of true or false depending on
whether cookies are enabled in the browser.

151

2007 IBM Corporation

Learning & Knowledge Education - India

Navigator Object Methods


javaEnabled() Returns a boolean telling if the browser has
JavaScript enabled.

152

2007 IBM Corporation

Learning & Knowledge Education - India

Window Object
The Window object is the top level object in the JavaScript
hierarchy.
The Window object represents a browser window.
A Window object is created automatically with every instance of a
<body> or <frameset> tag.

153

2007 IBM Corporation

Learning & Knowledge Education - India

Window Object Collections


Frames[] Returns all named frames in the window.

154

2007 IBM Corporation

Learning & Knowledge Education - India

Window Object Properties


name sets of return the name of the window.
status sets or returns the name of the window.
length sets or returns the number of frames in the window.
self returns a reference to the current window.
statusbar - sets whether or not the browsers statusbar should be
visible.
toolbar - sets whether or not the browsers toolbar should be
visible.
closed Returns all named frames in the window
document
history
155

2007 IBM Corporation

Learning & Knowledge Education - India

Window Object Methods


open() Opens a new browser window.
createPopup() Creates a popup window.
setInterval(code,millisec[,lang]) Evaluates an expression at
specified intervals.
clearInterval(id_of_setInterval) cancels a timeout that is set with
the setInterval() method.
setTimeout(code,millisec[,lang]) Evaluates an expression after a
specified number of milliseconds.
clearTimeout(id_of_setTimeout) cancels a timeout that is set with
the setTimeout() method.
focus() sets the focus to the current window.
blur() removes focus from the current window.
close() closes the current window.
156

2007 IBM Corporation

Learning & Knowledge Education - India

Frame Object
Frame object represents an HTML frame.
For each instance of a <frame> tag in an HTML document, a
Frame object is created.

157

2007 IBM Corporation

Learning & Knowledge Education - India

Frame Object (contd.)

In
Document Object
Model
Frames are
instances of Window
object

158

2007 IBM Corporation

Learning & Knowledge Education - India

Frame Object (contd.)

159

2007 IBM Corporation

Learning & Knowledge Education - India

Frame Object (contd.)

160

2007 IBM Corporation

Learning & Knowledge Education - India

Frame Object (contd.)

161

2007 IBM Corporation

Learning & Knowledge Education - India

Frame Object (contd.)

162

2007 IBM Corporation

Learning & Knowledge Education - India

Frame Object (contd.)

163

2007 IBM Corporation

Learning & Knowledge Education - India

Frame Object (contd.)

164

2007 IBM Corporation

Learning & Knowledge Education - India

Frame Object (contd.)

165

2007 IBM Corporation

Learning & Knowledge Education - India

Frame Object (contd.)

166

2007 IBM Corporation

Learning & Knowledge Education - India

Frame Object (contd.)

167

2007 IBM Corporation

Learning & Knowledge Education - India

Frame Object (contd.)

168

2007 IBM Corporation

Learning & Knowledge Education - India

Frame Object (contd.)

169

2007 IBM Corporation

Learning & Knowledge Education - India

Frame Object (contd.)

170

2007 IBM Corporation

Learning & Knowledge Education - India

Frame Object (contd.)

171

2007 IBM Corporation

Learning & Knowledge Education - India

Frame Object (contd.)

172

2007 IBM Corporation

Learning & Knowledge Education - India

Frame Object (contd.)

173

2007 IBM Corporation

Learning & Knowledge Education - India

Frame Object (contd.)

174

2007 IBM Corporation

Learning & Knowledge Education - India

Test Your Understanding

175

2007 IBM Corporation

Learning & Knowledge Education - India

Test Your Understanding

176

2007 IBM Corporation

Learning & Knowledge Education - India

Document Object
The document object represents the entire HTML document and
can be used to access all elements in a page.
The document object is part of the window object and is
accessed through the window.document property or simply
document.

177

2007 IBM Corporation

Learning & Knowledge Education - India

Document Object Collections


anchors[] - Returns a reference to all Anchor objects in the
document.
forms[] - Returns a reference to all Form objects in the document.
images[] - Returns a reference to all Image objects in the
document.
links[] - Returns a reference to all Area and Link objects in the
document.

178

2007 IBM Corporation

Learning & Knowledge Education - India

Document Object Properties


Body gives direct access to the <body> element.
Cookie Sets or returns all cookies associated with the current
document.
lastModified Returns the date and time a document was last
modified.
Title Returns the title of the current document.
URL Returns the URL of the current document.

179

2007 IBM Corporation

Learning & Knowledge Education - India

Document Object Methods


write() - Writes HTML expressions or JavaScript code to a document
writeln() Similar to write(), with the addition of writing a new line
character after each expression.
open() - Opens a stream to collect the output from any document.write()
or document.writeln() methods.
close() - Closes an output stream opened with the document.open()
method, and displays the collected data
getElementByID() Returns a reference to the first object with the
specified id.
getElementsByName() Returns a collection of objects with the
specified name.
getElementsByTagName() Return a collection of objects with the
specified tag name.

180

2007 IBM Corporation

Learning & Knowledge Education - India

Location Object
Location object is an JavaScript object it is not an DOM object.
The Location object is automatically created by the JavaScript
runtime engine and contains information about the current URL.
The Location object is part of the Window object and is accessed
through the window.location property.

181

2007 IBM Corporation

Learning & Knowledge Education - India

Location Object (contd.)

182

2007 IBM Corporation

Learning & Knowledge Education - India

Location Object (contd.)

183

2007 IBM Corporation

Learning & Knowledge Education - India

Location Object (contd.)

184

2007 IBM Corporation

Learning & Knowledge Education - India

Location Object (contd.)

185

2007 IBM Corporation

Learning & Knowledge Education - India

Location Object (contd.)

186

2007 IBM Corporation

Learning & Knowledge Education - India

Location Object (contd.)

187

2007 IBM Corporation

Learning & Knowledge Education - India

Location Object Methods


Assign (url) It loads a new document.
Reload() the current document.
Replace() Replaces the current document with a new one.

188

2007 IBM Corporation

Learning & Knowledge Education - India

Location Object Example


<html>
<body>
<script>
switch (window.location.protocol)
{
case "http:":
document.write("From Web<BR>\n")
break
case "file:":
document.write("From Local computer<BR>\n")
break
default:
document.write("Unknown Source<BR>\n")
break
}
</script>
</body>
</html>
189

2007 IBM Corporation

Learning & Knowledge Education - India

Output:
If Accessed from the Local File System

190

2007 IBM Corporation

Learning & Knowledge Education - India

Output:
If the page is delivered by a Web Server.

191

2007 IBM Corporation

Learning & Knowledge Education - India

History Object
History object is a JavaScript object.
The History object is automatically created by the JavaScript
runtime engine and consists of and array of URLs.
It is a part of window object & accessed through window.history
property.

192

2007 IBM Corporation

Learning & Knowledge Education - India

History Object (contd.)

193

2007 IBM Corporation

Learning & Knowledge Education - India

History Object (contd.)

194

2007 IBM Corporation

Learning & Knowledge Education - India

History Object (contd.)

195

2007 IBM Corporation

Learning & Knowledge Education - India

History Object (contd.)

196

2007 IBM Corporation

Learning & Knowledge Education - India

Test Your Understanding

197

2007 IBM Corporation

Learning & Knowledge Education - India

Test Your Understanding

198

2007 IBM Corporation

Learning & Knowledge Education - India

Form Object Model

199

2007 IBM Corporation

Learning & Knowledge Education - India

Form Object Model (contd.)

200

2007 IBM Corporation

Learning & Knowledge Education - India

Form Object Model (contd.)

201

2007 IBM Corporation

Learning & Knowledge Education - India

Test Your Understanding

202

2007 IBM Corporation

Learning & Knowledge Education - India

Test Your Understanding

203

2007 IBM Corporation

Learning & Knowledge Education - India

Form Object Model (contd.)

204

2007 IBM Corporation

Learning & Knowledge Education - India

Form Object Model (contd.)

205

2007 IBM Corporation

Learning & Knowledge Education - India

Form Object Model (contd.)

206

2007 IBM Corporation

Learning & Knowledge Education - India

Form Object Model (contd.)

207

2007 IBM Corporation

Learning & Knowledge Education - India

Form Object Model (contd.)

208

2007 IBM Corporation

Learning & Knowledge Education - India

Test Your Understanding

209

2007 IBM Corporation

Learning & Knowledge Education - India

Test Your Understanding

210

2007 IBM Corporation

Learning & Knowledge Education - India

Form Object Model (contd.)

211

2007 IBM Corporation

Learning & Knowledge Education - India

Form Object Model (contd.)

212

2007 IBM Corporation

Learning & Knowledge Education - India

Test Your Understanding

213

2007 IBM Corporation

Learning & Knowledge Education - India

Test Your Understanding

214

2007 IBM Corporation

Learning & Knowledge Education - India

Form Object Model (contd.)

215

2007 IBM Corporation

Learning & Knowledge Education - India

Form Object Model (contd.)

216

2007 IBM Corporation

Learning & Knowledge Education - India

Form Object Model (contd.)

217

2007 IBM Corporation

Learning & Knowledge Education - India

Form Object Model (contd.)

218

2007 IBM Corporation

Learning & Knowledge Education - India

Test Your Understanding

219

2007 IBM Corporation

Learning & Knowledge Education - India

Test Your Understanding

220

2007 IBM Corporation

Learning & Knowledge Education - India

Test Your Understanding

221

2007 IBM Corporation

Learning & Knowledge Education - India

Test Your Understanding

222

2007 IBM Corporation

Learning & Knowledge Education - India

Cookies
2007 IBM Corporation

Learning & Knowledge Education - India

Cookies

A cookie can store a small amount of information


about a user visiting a site.

A cookie is a small text file that is stored on the site


visitor's computer by their browser .

Because the cookie is stored on the users computer,


it does not require any server space no matter how
many users you have .

With JavaScript, you can both create and retrieve


cookie values.

224

2007 IBM Corporation

Learning & Knowledge Education - India

Cookies (contd.)

You can use cookies to :


save user preferences.
customize data.
remember the last visit.
Keep track of items in an order while a user browses.
Remember the information your sites visitors gave last time.

225

Cookies can be created, read and erased by JavaScript. They


are accessible through the property document.cookie

2007 IBM Corporation

Learning & Knowledge Education - India

Cookies (contd.)

What does a cookie contain?


Name value pair
The first element in a cookie is a "name" attribute, followed
by the data to be stored in the cookie.

The expiry date


specifies how long the cookie is valid for.

226

2007 IBM Corporation

Learning & Knowledge Education - India

Cookies (contd.)

What does a cookie contain?


The path
this states where the cookie may be accessed from on the
Web site. Most often, this is set to the server's document
root.

The domain
The "domain" attribute allows you to set a domain name for
the cookie. Again, this is optional.

227

2007 IBM Corporation

Learning & Knowledge Education - India

Question
The name-value pair is the

first

_____________ element in the


Cookie

second
third

228

2007 IBM Corporation

Learning & Knowledge Education - India

Answer
The name-value pair is the

first

_____________ element in the


Cookie

second
third

229

2007 IBM Corporation

Learning & Knowledge Education - India

Cookies and Security

Turn up security level on your browser to disable


cookies or prompt for cookie.

Delete the content of a cookie and then write protect


it.

Use 3rd party software:


Cookie Pal, CookieMaster, CookieCrusher to monitor, browse
and edit cookies.

230

2007 IBM Corporation

Learning & Knowledge Education - India

Format of Cookie

First the name value pair.


Then a semicolon and a space.
Then the expiry date.
Expiry date should be in UTC format.

Then again a semicolon and a space.


Then the path.

231

2007 IBM Corporation

Learning & Knowledge Education - India

Format of Cookie (contd.)

document.cookie=<name of cookie>=<value of
cookie>;<blank space>expires=<date in UTC
format>;<blank space>path=<path location>

Example

document.cookie = user=Paul; expires=Thu, 2 Aug 2008 20:47:11 UTC;


path=/'

232

2007 IBM Corporation

Learning & Knowledge Education - India

Example of Setting a Cookie


<html>
<head>
<script language="JavaScript">
function setCookie(name, value) {

</script>
</head>
<body>

var exp=new Date("January 31,2008") <form>


<input type="button" value="Set
document.cookie=name+"="+escape
a Cookie"
(value)+"; expires="+exp.toGMTString() onClick="setCookie(user',Paul
+"; path=/
Smith')">
document.write(Cookie has been set) </form>
)

</body>
</html>

What does the


escape function
do?

Set an expiry date

233

2007 IBM Corporation

Learning & Knowledge Education - India

escape() function
There's no escape!
Strictly speaking, we should be escaping our cookie values -encoding non-alphanumeric characters such as spaces and
semicolons.
This is to ensure that our browser can interpret the values
properly.
Fortunately this is easy to do with JavaScript's escape() function.
For example
document.cookie = "username=" + escape(Paul Smith") + ";
expires=15/02/2003 00:00:00";

234

2007 IBM Corporation

Learning & Knowledge Education - India

Example of Setting a Cookie


<html>
<head>
<script language="JavaScript">
function setCookie(name, value) {
var exp=new Date("January 31,2008")
document.cookie=name+"="+escape
(value)+"; expires="+exp.toGMTString()
+"; path=/
document.write(Cookie has been set)
)

</script>
</head>
<body>
<form>
<input type="button" value="Set a
Cookie"
onClick="setCookie(user',Paul
Smith')">
</form>
</body>
</html>

The value stored is


user=Paul Smith

235

Setting the cookie

2007 IBM Corporation

Learning & Knowledge Education - India

Reading a Cookie
<html>

</script>

<head>

</head>

<script language="JavaScript">

<body>

function readCookie() {

<form><input type="button"
value="read"
onClick="readCookie()">

var ca = document.cookie
document.write(ca)
}

</form>
</body>

Value retrieved is

</html>

user=Paul Smith

Returns the cookie


name value pair

236

2007 IBM Corporation

Learning & Knowledge Education - India

Extracting only the value from the Cookie


<html>
<head>

document.write( document.cookie.substri
ng(c_start,c_end))

<script language="JavaScript">

function readCookie(c_name)

if (document.cookie.length>0)

</script>

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

</head>

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

237

Displays the value:


Paul Smith

<body>
<form> <input type="button" value="read"
onClick="readCookie('user')">
</form>
</body>
</html>

2007 IBM Corporation

Learning & Knowledge Education - India

Delete Cookies
<html>
<head>

<body>

<script language="JavaScript">

<form>

function deleteCookie ( cookie_name)

<input type="button"
value=delete"
onClick="deleteCookie(user')
">

{
var cookie_date = new Date ( )
cookie_date.setTime
( cookie_date.getTime() - 1 )
document.cookie = cookie_name += "=;
expires=" + cookie_date.toGMTString()
}
</script>
</head>

238

</form>
</body>
</html>

The cookie's expiry date is set


to one second less then the
current date.

2007 IBM Corporation

Learning & Knowledge Education - India

Modifying a cookie

To modify a cookie simply reset

the values and use


the same procedure for setting the cookie.

Ensure that the cookie name is existing or a new


cookie will be created.

239

2007 IBM Corporation

Learning & Knowledge Education - India

Summary
Cookies are small text files that sit on your hard disk.
Cookies are created when you visit websites that use cookies to store
information that they need (or prefer).

Websites often use cookies to personalize the user experience - such


as remembering your name (assuming you supplied it previously) or
remembering the items in your shopping cart from previous visits.

Despite the many misconceptions about cookies being malicious, they


are quite harmless.

Cookies can't give your personal details to other websites, or transmit a


virus or anything like that.

A cookie can only be read by the server that created it.


Websites normally use cookies to make its users' lives easier, not
harder.

240

2007 IBM Corporation

Learning & Knowledge Education - India

Thank You
For Your
Participation
2007 IBM Corporation

You might also like