You are on page 1of 65

1 Content

BAYON HOSTING

Javascript &
DOM Scripting


ITEC Bayon Hosting

2 Content

BAYON HOSTING

Content
Content ................................................................................................................................................... 1
Module 1: Introduction to JavaScript ..................................................................................................... 6
What is JavaScript? ............................................................................................................................. 6
Function of JavaScript ......................................................................................................................... 6
JavaScript History ................................................................................................................................ 6
JavaScript Creation.............................................................................................................................. 6
Internal JavaScript ........................................................................................................................... 7
External JavaScript .......................................................................................................................... 7
<noscript/> tag .................................................................................................................................... 7
Module 2: JavaScript Basics .................................................................................................................... 8
Generalization of JavaScript................................................................................................................ 8
Comments ........................................................................................................................................... 8
Single Line Comments ..................................................................................................................... 8
Multiline Commnets ....................................................................................................................... 8
Using Variables.................................................................................................................................... 8
Data Type ............................................................................................................................................ 9
Data Type Conversion ....................................................................................................................... 10
Number Conversion ...................................................................................................................... 10
String Conversion .......................................................................................................................... 10
Boolean Conversion ...................................................................................................................... 11
Operator............................................................................................................................................ 11
Arithmetic Operator...................................................................................................................... 11
Comparative Operator .................................................................................................................. 12
Logical Operator............................................................................................................................ 13
Control Flow Statements .................................................................................................................. 14
If Statements ................................................................................................................................. 14
Switch Statements ........................................................................................................................ 14
Iterative or Loop Statements ............................................................................................................ 15
While Statement ........................................................................................................................... 15
Do While Statement ...................................................................................................................... 15
For Statement ............................................................................................................................... 16

3 Content

BAYON HOSTING

Break, Continue and Label Implementation ..................................................................................... 16


Break and Continue....................................................................................................................... 16
Label .............................................................................................................................................. 17
Functions ........................................................................................................................................... 17
Using Arguments ........................................................................................................................... 17
Using return .................................................................................................................................. 18
Module 3: Array and String ................................................................................................................... 19
Array.................................................................................................................................................. 19
Creating an Array .......................................................................................................................... 19
Input and Output from an array ................................................................................................... 19
String ................................................................................................................................................. 21
Property in String .......................................................................................................................... 21
Methods in String.......................................................................................................................... 21
Module 4: Date and Math..................................................................................................................... 23
Date Object ....................................................................................................................................... 23
Creating a Date Object .................................................................................................................. 23
Methods in date object ................................................................................................................. 23
Static Method................................................................................................................................ 25
Math Object ...................................................................................................................................... 26
Math Properties ............................................................................................................................ 26
Math Methods .............................................................................................................................. 26
Module 5: Browser Object Model ........................................................................................................ 28
window object .................................................................................................................................. 28
Methods in window object ........................................................................................................... 29
history object .................................................................................................................................... 30
screen object ..................................................................................................................................... 31
location object .................................................................................................................................. 31
navigator object ................................................................................................................................ 32
document object ............................................................................................................................... 33
Module 6: Document Object Model ..................................................................................................... 34
Properties and Methods in DOM ...................................................................................................... 34
Accessing Element Object ................................................................................................................. 35
By Hierarchy .................................................................................................................................. 36
Access Element By Elements Id.................................................................................................... 37

4 Content

BAYON HOSTING

Access Element By Elements Name ............................................................................................. 38


Access Element By Elements TagName ....................................................................................... 39
Using document.all ....................................................................................................................... 40
Creating andm Manipulate nodes .................................................................................................... 40
Creating node ................................................................................................................................ 40
Using removeChild(), replaceChild(), insertBefore() ..................................................................... 41
Using createDocumentFragement() ............................................................................................. 42
Module 7: Error Handling ..................................................................................................................... 44
Kind of Error ...................................................................................................................................... 44
Handling Errors ................................................................................................................................. 44
onerror event handler................................................................................................................... 44
try...catch statement..................................................................................................................... 45
Module 8: Form Validation ................................................................................................................... 47
Form Basics ....................................................................................................................................... 47
Referencing to Form ..................................................................................................................... 47
Referencing to Form Field ............................................................................................................. 47
Form Vaidation ................................................................................................................................. 48
Submitting Forms .......................................................................................................................... 48
Submitting Once............................................................................................................................ 48
Select Element .................................................................................................................................. 48
List Boxes and Combo Boxes......................................................................................................... 48
Accessing Options Collection ........................................................................................................ 49
Getting Text from Option.............................................................................................................. 49
Accessing Selected Option ............................................................................................................ 49
Accessing Multiple Selected Option ............................................................................................. 49
Module 10: Events ................................................................................................................................ 50
Event Handlers/Listeners .................................................................................................................. 50
attachEvent(), detachEvent() ............................................................................................................ 50
addEventListener(), removeEventListener() ..................................................................................... 51
Module 11: File System Object ............................................................................................................. 52
Working with Text File ...................................................................................................................... 52
Create Text file .............................................................................................................................. 52
Write Data Into Text File ............................................................................................................... 52
Open Text File and Read Out ........................................................................................................ 52

5 Content

BAYON HOSTING

Appending Text File ...................................................................................................................... 53


Excercises .............................................................................................................................................. 54
Exercise I ....................................................................................................................................... 54
Exercise 2 ...................................................................................................................................... 55
Exercise 3 ...................................................................................................................................... 56
Exercise 4 ..................................................................................................................................... 56
Exercise 5 ...................................................................................................................................... 56
Exercise 6 ...................................................................................................................................... 56
Exercise 7 ...................................................................................................................................... 57
Exercise 8 ...................................................................................................................................... 58
Exercise 10 .................................................................................................................................... 59
Exercise 11 .................................................................................................................................... 59
Appendix A: Key Words and Reserved Word........................................................................................ 61
Keywords........................................................................................................................................... 61
Reserved Words ................................................................................................................................ 61
Appendix B: ASCII Code......................................................................................................................... 62
ASCII CODE ........................................................................................................................................ 62
Special ASCII Code ............................................................................................................................. 63
Appendix C: JavaScript Version ............................................................................................................. 64
JavaScript Versions............................................................................................................................ 64
Reference .............................................................................................................................................. 65

6 Module 1: Introduction to JavaScript

BAYON HOSTING

Module 1: Introduction to JavaScript


What is JavaScript?
JavaScript

client-side scripting language

HTML, CSS

Web Development

web page

(Dynamic)

Function of JavaScript

JavaScript

message box, input box, confirm box

validate

Form Field

blank field

status bar

drop down menu

JavaScript History
Netscape

user

validate form

Server

Network

28.8 kbps

client script

live script

Netscape
live script

JavaScript

Netscape Navigation 2.0


JavaScript 1.1

JavaScript 1.0

Netscape Navigation 3.0


Internet Browser

Microsoft

Sun Microsystem

Microsoft

Internet Explorer 3.0

client script

JScript 1.0

JavaScript Creation
javascript
Notepad, Dreamweaver, Frontpage

HTML

Text editor

7 Module 1: Introduction to JavaScript

BAYON HOSTING

Internal JavaScript
JavaScript
<script/> tag

file

javascript

file HTML

Syntax
<script type=text/javascript>
statements;
</script>

External JavaScript
javascript
html file
javascript

file

<script/> tag
file javascript

file HTML

link

src attribute
save

javascript
file

extension .js . global.js

Syntax
<script src=path></script>

<noscript/> tag
tag

HTML
support

User
disable javascript

<noscript>
Your Browser Not Support JavaScript or JavaScript was
disabled.
</noscript>

Browser

8 Module 2: JavaScript Basics

BAYON HOSTING

Module 2: JavaScript Basics


Generalization of JavaScript
JavaScript

case-sensitive

variable

student

variable

Student

variable

variable

statement

variable

semi-colon(;)
{}

code block

if statement, for statement,

function

Comments
javascript
comments

browser

Comments

programmer

Single Line Comments


Comment
Syntax
// comments

Multiline Commnets
Comment
Syntax
/* Comments
Comments
Comments
Comments */

Using Variables
Variable
Object

reference

9 Module 2: JavaScript Basics

BAYON HOSTING

Declaration
variable

var statement

syntax
var variableName;
var variableName=value;

statement

commas(,)

variable

var variable1,variable2,variable3;
var variable1=value1,variable2=value2;
Input into Variable
variable

assignement (=)

variable
syntax
variable1=value1;
Output from Variable
variable

variable

var sText = Hello;


alert(sText);

Naming Convention

variable

, underscore(_), Dollar Sign($)

, underscore(_), dollar sign($),

variable

keyword reserved word

JavaScript

Data Type

variable

keyword

typeof

string typeof (variableName)


JavaScript

syntax

10 Module 2: JavaScript Basics

BAYON HOSTING

Undefined
variable

Boolean
true

false

String

Number

Data Type Conversion

method

Number Conversion

Table: Number Coversion


parseInt()

Value

parseFloat()

Number()

eval()

false

NaN

NaN

false

true

NaN

NaN

true

undefined

NaN

NaN

NaN

undefined

2.3

2.3

2.3

2.3

34

34

34

34

34

3+5

NaN

String Conversion

Table: String Coversion


Value
false

String()

.toString()

false

false

.toString(2)

false

.toString(8)

false

.toString(16)

false

11 Module 2: JavaScript Basics

BAYON HOSTING

true

true

undefined

undefined

10

10

10

1010

12

14

14

14

1110

16

true

true

true

true

error

Boolean Conversion
Boolean

Table: Boolean Conversion


Boolean()

Value

false

Letter

true

undefined

false

false

14

true

oObject

true

Operator

symbol

Arithmetic Operator

var iNum1 = 9;
var iNum2 = 2;
var vResult;

variables

12 Module 2: JavaScript Basics

BAYON HOSTING

Table: Arithmetic Operator

Operator

Meaning

Example

alert(vResult)

iNum1 + iNum2

11

iNum1 - iNum2

iNum1 * iNum2

18

iNum1 / iNum2

4.5

iNum1 % iNum2

++

vResult=5;

vResult++;
vResult=5;

++vResult;
--

vResult=5

vResult--;
vResult=5;

--vResult;
+=

vResult=5;

vResult+=4;
-=

vResult=5;
vResult-=4;

Comparative Operator
operator

boolean

var iNum1 = 9;
var iNum2 = 2;
var vResult;

variables

13 Module 2: JavaScript Basics

BAYON HOSTING

Table: Comparative Operator

Meaning

Operator
==

(equal)

!=
<
<=
>
>=

expression

alert(expression)

iNum1 == iNum2

false

iNum1 != iNum2

true

iNum1 < iNum2

false

iNum1 <= iNum2

false

iNum1 > iNum2

true

iNum1 >= iNum1

true

Logical Operator
true
(&&)

false

operand

operand

(||)

oprand

operand true

false

variables

var iNum1 = 9;
var iNum2 = 2;
var vResult;

Table: Logical Operator

expression

alert(expression)

&&

(iNum1 > iNum2) &&


(iNum1 != iNum2)

true

||

(iNum1 < iNum2) ||


(iNum1 = iNum2)

false

!(iNum1<iNum2)

true

Operator

Meaning

14 Module 2: JavaScript Basics

BAYON HOSTING

Control Flow Statements


If Statements
statement

statements
Syntax
if(expression){
}
Syntax
if(expression){
statements;
}else if(expression){
statements;
}else if(expression){
statements;
}else{
statements;
}

Switch Statements
expression

statement label

case clause expression

case

switch statement statement label default


Syntax:
switch(expression){
case value1: statement1;
break;
case value2: statement2;
break;
...
case valueN: statementn;
break;
default: default_statement
}
expression: variable expression

15 Module 2: JavaScript Basics

BAYON HOSTING

value: expression
break: execute statement

Iterative or Loop Statements


While Statement
pre-test loop execute code.
execute statements

expression true.

syntax:
while(expression){
statements;
}

var i=0;
while(i<10){
document.write( Number + i + <br/>)
i++;
}

Do While Statement
post-loop excecute code

statements execute
syntax:
do{
statements;
} while(expression);

16 Module 2: JavaScript Basics

BAYON HOSTING

var i=0;
do{
document.write( Number + i + <br/>);
i++;
}

For Statement
while

initialization, condition,

increment statement
Syntax:
for(initialization,condition,increment_statement){
statements;
}

for(i=1;i<=31;i++){
document.write(Number : + i);
}

Break, Continue and Label Implementation


Break and Continue
Break
statement

loop

for(i=0;i<10;i++){
if(i==5)break;
document.write(Number : + <br/>);
}

Continue
statement

loop

for(i=0;i<10;i++){
if(i==5)continue;
document.write(Number : + <br/>);
}

17 Module 2: JavaScript Basics

BAYON HOSTING

Label

loop
break continue

loop

loop

Syntax
label_Name:
loop

Functions
statements function
keyword function, arguments
{}

Syntax:
function functionName(){
statements
}

function showMessage(){
alert(Hello world);
}

Using Arguments
arguments
dynamic

function
argument

arguments
Syntax
function functionName(arg0,arg1,.....,argN){
statements;
}

function showMessage(sMessage){
alert(sMessage);

functions
varaibles

function

18 Module 2: JavaScript Basics

BAYON HOSTING

}
showMessage(Welcome to my Site !);

Using return
return

function

Syntax
function functionName(arg0,arg1,.....,argN){
statements;
return value;
}

function sum(fOperand1,fOperand2){
return (fOperand1+fOperand2);
}
showMessage(Welcome to my Site !);

19 Module 3: Array and String

BAYON HOSTING

Module 3: Array and String


Array
Array

Array

loop
index

array

index

array

Creating an Array
array

Empty Array

array

new Array()

[ ]

Example
var arrStudent = new Array();
var arrColor = [];

Specified number of items in Array


array

new

Array(n)
Example
var arrStudent = new Array(39);//there are 39 items in array

Specified items in Array

array

(,)

var arrColor = new Array(Blue,Black,Red,Yellow);


var arrFruit = [Apple,Book,Car,Door,Eye];

Input and Output from an array


array object
array object

index

array

Index

index

var oStudent=new Array(Dara,Kagha,Yarern);

20 Module 3: Array and String

BAYON HOSTING

alert(oStudent[0]); // Dara
oStudent[0]=Thea;
alert(oStudent[0]);// Thea

Array
Array

4294967295
Property

length

array object

var arrStudent = new Array(15);


alert(oArray.length);// Output: 15
oInfo=[2,Thera,Male];
alert(oArray.length); //output: 3

Table: Array Methods


Methods

array concat( value, ...)


array concat( array, ...)

array

string join( separator)

String

value array
array
separator

string

variant pop( )

array

number push( value, ...)

value

array

void reverse( )

array

variant shift( )

array

array slice( start, end)

array

start
end-1.

void sort()

array

ASCII

Code
array splice( start,
deleteCount, value,...)

deleteCount
start

array

values

start

array
string toLocaleString( )

String
String

21 Module 3: Array and String

BAYON HOSTING

string toString( )

String
(,)

variant unshift( value, ...)

value

array

String

String
String

search, replace,

method

ascii code,

case

Property in String
String

array
string

property

length

var sText = Hello;


alert(sText);//Ouput 5

Methods in String
String

methods

Table: String Methods


Methods

string charAt( n)

number charCodeAt( n)
string concat( value, ...)
number indexOf( substring[,
start])

ASCII Code n

String value
substring String

start (0 Default)
-1
substring String

number lastIndexOf( substring[,

start (length is

start])

Default) -1
String
end(

string slice( start[, end])


end

string
) (-)

start

22 Module 3: Array and String

array split( delimiter[, limit])

BAYON HOSTING

Array
delimiter
String

string substring( from, to)

string
) (-)

to(

from
to

String

string

length

substr( start, length)

length

toLowerCase( )

toUpperCase( )

String

string
lowercase

String

string
uppercase

start

23 Module 4: Date and Math

BAYON HOSTING

Module 4: Date and Math


Date Object
,

Creating a Date Object


var oNow = new Date( );
timestamp
var oDate = new Date(timestamp);
Timestamp

datestring
new Date(datestring);

javaScript

Thu Sep 11 2008


Thu, 11 Sep 2008 10:24:39 UTC
Thursday, September 11, 2008
Thursday, September 11, 2008 5:24:39 PM
5:24:39 PM
Thu Sep 11 17:24:39 UTC+0700 2008
17:24:39 UTC+0700
Thu, 11 Sep 2008 10:24:39 UTC

argument
new Date(year, month, day, hours, minutes, seconds, ms);
Range
Year
Month
Day
Hours
Minutes
Seconds
Ms

argument
:
:
:
:
:
:
:

4-digit
0-11
1-31
0-23
0-59
0-59
0-999

Methods in date object

UTC = Universal Time Coordinate

24 Module 4: Date and Math

BAYON HOSTING

GMT= Greenwich Mean Time


methods

[UTC]

Table: Date Methods


Methods

number get[UTC]Date( )

number get[UTC]Day( )

number get[UTC]FullYear( )
number get[UTC]Hours( )

number get[UTC]Milliseconds( )

number get[UTC]Minutes( )

number get[UTC]Month( )

( )

number get[UTC]Seconds( )

number getTime( )

(UTC)
Date Object

number getTimezoneOffset( )

Greenwich
getFullYear()

number getYear( )

number set[UTC]Date( day_of_month)


number set[UTC]FullYear( year, [month,
number day])
number set[UTC]Hours( hours[, mins,
number secs, ms])
number set[UTC]Milliseconds( millis)
number set[UTC]Minutes( minutes,
number [seconds, millis])
number set[UTC]Month( month, [day])

Date Object
timestamp

Date

Date Object
timestamp

Date

Date Object
timestamp

Date

Date Object
timestamp

Date

Date Object
timestamp

Date

Date Object
timestamp

Date

25 Module 4: Date and Math

BAYON HOSTING

number set[UTC]Seconds( seconds,


number [millis])

Date Object
timestamp

timestamp

number setTime( milliseconds)

Date

Date Object

timestamp

Date

setFullYear()

number setYear( year)

Date object

Thu Sep 11 2008


Date object

Thu, 11 Sep 2008 10:24:39 UTC


Date object

string toDateString( )
string toGMTString( )
string toLocaleDateString( )

Thursday, September 11, 2008


Date object
Thursday,
September 11, 2008 5:24:39 PM
Date object

5:24:39 PM
Date object

Thu Sep 11 17:24:39 UTC+0700 2008


Date object

17:24:39 UTC+0700
Date object

Thu, 11 Sep 2008 10:24:39 UTC


getTime()

string toLocaleString( )
string toLocaleTimeString( )
string toString( )
string toTimeString( )
string toUTCString( )
number valueOf( )

Static Method
Date
instance

methods
date class

Table: Static Methods


Methods
number Date.parse( datestring)
number Date.UTC( yr, mon, day, hr, min,
sec, ms)

t in

timestamp

timestamp
arguments

26 Module 4: Date and Math

BAYON HOSTING

Math Object

Object methods properties

, e,

Math Properties
Table: Math Properties
Property

Math.E

2.718.

Math.LN10

Math.LN2

Math.LOG10E

e.

Math.LOG2E

e.

Math.PI

Math.SQRT1_2

Math.SQRT2

Math Methods
Table: Math Methods
Methods

Math.abs( x)

Math.acos( x)

arc cosine x

Math.asin( x)

arc sine x

Math.atan( x)

arc tangent x

Math.atan2( y, x)

arc cosine y/x

Math.ceil( x)

Math.cos( x)

cosine x

Math.exp( x)

ex

Math.floor( x)

Math.log( x)

log(x)

Math.max( args...)

args

27 Module 4: Date and Math

Math.min( args...)

BAYON HOSTING

args

Math.pow( x, y)

xy

Math.random( )

0.0 1.0

Math.round( x)

Math.sin( x)

sine x

Math.sqrt( x)

Math.tan( x)

tangent x

28 Module 5: Browser Object Model

BAYON HOSTING

Module 5: Browser Object Model


Browser Object Model

Object

Browser Object Model

Browser window
Objects

window object
Object

Browser window

window

content

Browser
window object

properties

Table: Window Object Properties


Property
closed

true

window

false
status bar

defaultStatus

status

document

document object

frames[ ]

frames array object

history

history object

length
location

frames
location object

window

browser

29 Module 5: Browser Object Model

BAYON HOSTING

window
name

window.open()

frame
frame

name attribute

navigator

naivagator object

opener

window object

window

parent

window object

window frame

screen

screen object

self

window object

status bar
status

browser

status

top

window obejct

window

window object

window object

Methods in window object


Table: Window Object Methods
Method
void alert( message)

Message Box
focus

void blur( )

method setInterval()

void clearInterval( intervalId)


intervalId.

method setTImeout()

void clearTimeout( timeoutId)


timeoutId.
void close( )

window
message

boolean confirm( question)

question

OK

Cancel

true

Cancel

cursor

void focus( )

OK
false

browser

browser
window

void moveBy( dx, dy)

pixel
void moveTo( x, y)

x,y
address

open( url, name, features)

url

window

name

window

features
string

void print( )

window print

current page

30 Module 5: Browser Object Model

BAYON HOSTING

InputBox
prompt( message, default)

message

default

Textbox

user
void resizeBy( dw, dh)

string

window

void resizeTo( width, height)

window
pixel

void scroll( x, y)

scroll

browser window

scroll

browser window

y
void scrollBy( dx, dy)

dx
scroll

void scrollTo( x, y)

dy

browser window

y
intervalId
execute

setInterval( code, interval)

Interval
code

interval

Interval
clearInterval(InvervalID);
timeoutId
execute
setTimeout( code, delay)

timeout
code

timeout

timeoutId
clearTimeout(timeoutID);

history object
object
history

history
methods

page

Table: History Object Methods


Method
back( )

forward( )

history

browser

history

browser
go( n)

page
-

31 Module 5: Browser Object Model

BAYON HOSTING

screen object
object

properties

computer display

screen resolution

Screen object

color depth

properties

Table: Screen Object Properties


Property
availHeight

screen

availWidth

screen

colorDepth

screen

height

screen

width

screen

location object
object

URL

load

window

URL
location

properties

Table: Location Object Properties


Property
hash

URL

.http://www.abc.com/home.html#faq

host

server

hostname

host name

server (abc.com)
URL

host

http://www.abc.com/images/img1.jpg

/images/img1.jpg
port

port

web

http://www.abc.com:8080/index.html
protocol

8080

//
?

search

http://www.abc.com/index.html?page=1,section=2
location

faq

(www.abc.com)

href
pathname

hash

methods

?page=1,section=2

32 Module 5: Browser Object Model

BAYON HOSTING

Table: Location Object Methods


Methods

reload( force) load page

cache

force

replace( url)

force

false

server

true
url

history

assign(url)

page

href property

url

navigator object
object

Web browser.
BOM

browser

navigator object

standard

properties

methods

browser

Table: Navigator Object Properties


Browser

property/method
appCodeName
appName

string

code name

string

browser

browser

appMinorVersion string
appVersion
string

browser OS

browserLanguage string
cookieEnabled
boolean

browser

cookies

cpuClass

string

javaEnabled()

boolean

language

string

mimeTypes

array

onLine

boolean

oscpu

string

OS CPU

platform

string

computer platform

plugins

array

preference()

method

product

string

productSub

string

systemLanguage

string

taintEnabled()

boolean

userAgent

string

userLanguage

string

class

IE Moz

CPU

java

browser
mimetypes

browser
browser

internet

plugins

browser
preferences

browser

product

product
OS

data-tainting

user-agent
OS

33 Module 5: Browser Object Model

userProfile

BAYON HOSTING

object

user profile

vendor

browser

vendorSub

string

document object
object

Document Object

properties

Page
cookie

methods

Link,

access

collection

form, image

Table: Document Object Properties


Property
alinkColor

Description
link

anchors[ ]

array

Anchor object

applets[ ]

array

Applet object

bgColor
cookie
embeds[ ]

background
A string-valued property with special behavior that allows the cookies
associated with this document to be queried and set.
array
Embeds object

fgColor
forms[ ]

array

Form object

images[ ]

array

image object

lastModified

page

linkColor
links[ ]

link
array

location
plugins[ ]

tag <img/>

link object
URL

array

tag <a/>

file

plugins object

title

tag <title>

URL

URL

vlinkColor

file
link

Table: Document Object Method


Methods

Description

write( value, ...)

string

document

writeln( value, ...)

string

document

new line

34 Module 6: Document Object Model

BAYON HOSTING

Module 6: Document Object Model


Document Object Model

object

page

node

document

method

element object

node

property

node

form

Properties and Methods in DOM


Table: Document Object Model
Property/Method

Type
Return Type

nodeName

String

Description
node
node

nodeValue

node

String

node
nodeType

Number

ownerDocument

Document

document

firstChild

Node

node

lastChild

Node

node

node type constant


parent

node

childNodes

childNodes
childNodes

NodeList

previousSibling

Node

child node
previous sibling

null

sibling
nextSibling

next sibling

Node

null

sibling
hasChildNodes()

Boolean

true

childNodes

node

attr objects
attributes
appendChild(node
)
removeChild(node
)
replaceChild(new
node, oldnode)
insertBefore(new
node,refnode)

NamedNodeMap

Node
Node

properties

elements

Element nodes

Node
node

childNodes
childNodes

Node

oldnode

Node

newnode

childNodes
refnode

newnode
childNodes

35 Module 6: Document Object Model

BAYON HOSTING

array

NodeList
child nodes
NamedNodeMap

no

index

elements

array

nodes

index
attributes

node type constant


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

elements

Node Type Description


Element_NODE
Attribute_NODE
Text_NODE
CDATA_SECTION_NODE
ENTITY_REFERENCE_NODE
ENTITY_NODE
PROCESSING_INSTRUCTION_NODE
COMMENT_NODE
DOCUMENT_NODE
DOCUMENT_TYPE_NODE
DOCUMENT_FRAGMENT_NODE
NOTATION_NODE

Accessing Element Object


element object
documentElement, childNodes, firstChild, lastChild, nextSibling, previousSibling,

HTML

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"
/>
<title>DOM Lesson</title>
</head>
<body>
My First Content
<div>
Hello
<i>
World
</i>
</div>
My First Paragraph
<p>

36 Module 6: Document Object Model

BAYON HOSTING

Welcome
</p>
</body>
</html>
node

By Hierarchy

HTML

<html>
<head>
<title> DOM </title>
</head>
<body>
</body>
</html>
Internet Explorer

DOM

37 Module 6: Document Object Model

BAYON HOSTING

Firefox
#text node

tag

white space

Firefox

html element object:


var
var
var
var

oHTML=document.childNodes[0];
oHTML=document.documentElement;
oHTML=document.firstChild;
oHTML=document.lastChild;
head element

1:
2:
3:

var oBody=oHTML.firstChild;
var oBody=oHTML.childNodes[0];
var oBody=oHTML.childNodes.item(0);

1:
2:
3:
4:

body element
oBody=document.body;
oBody=oHTML.lastChild;
oBody=oHTML.childNodes[0];
oBody=oHTML.childNodes.item(1);

var
var
var
var

Access Element By Elements Id


element object

id attribute id attribute

Syntax:
var oElement=document.getElementById(elementID)

HTML
<html>

element

38 Module 6: Document Object Model

BAYON HOSTING

<head>
<title> DOM </title>
</head>
<body>
<h1 id=headerText>Web Content </h1>
<p id=content>Welcome To My Site </p>
</body>
</html>
p element object

id

element

var oPContent=document.getElementById(content);
h1 element object
var oH1HeaderText=document.getElementById(headerText);

Access Element By Elements Name


element

radio, checkbox

Syntax:
var oElement=document.getElementsByName(elementName)
oElement

array

element

Radio Implementation
<form>
<input type="radio" name="radAge" value="14" checked="checked"
/>14<br />
<input type="radio" name="radAge" value="15" />15<br />
<input type="radio" name="radAge" value="16" />16<br />
<input type="radio" name="radAge" value="17" />17<br />
<input type="button" onclick="showValue()" value="ShowAge" />
</form>
<script>
function showValue(){
var oAge=document.getElementsByName("radAge");
for(i=0;i<oAge.length;i++){
if(oAge.item(i).checked==true){
alert(oAge.item(i).value);
}
}
}
</script>

Checkbox Implementation

39 Module 6: Document Object Model

BAYON HOSTING

<form>
<input type="checkbox" value="1" name="chkNumber" />1<br />
<input type="checkbox" value="2" name="chkNumber" />2<br />
<input type="checkbox" value="3" name="chkNumber" />3<br />
<input type="button" value="Get Number" onclick="getNumber()"
/>
</form>
<script type="text/javascript">
var aNumber=new Array();
var oChkNumber=document.getElementsByName("chkNumber");
function getNumber(){
for(i=0;i<oChkNumber.length;i++){
if(oChkNumber.item(i).checked==true) {
aNumber.push(oChkNumber.item(i).value);
}
}
alert(aNumber);
}
</script>

Access Element By Elements TagName


method

array

element

tag name

Syntax
array oElementObject.getElementByTagName(tagName);

element object
Id

content

array

tag

tag

aPContents

...
<div id="content">
<h2> First Article </h2>
<p>First Text</p>
<h2> Second Article </h2>
<p>Third Text</p>
<h2> Third Article </h2>
<p>Third Text</p>
</div>
...
var oContent = document.getElementById("content");
var aPContents=oContent.getElementsByTagName("p");

array
p

array

element object

tag

40 Module 6: Document Object Model

BAYON HOSTING

alert(aPContents.length);// display 3
element object

index

p tag
var oFirstP=aPContents[0];

Using document.all
document.all
#text node

javascript

property

array

property
HTML

support

node
Internet Explorer

HTML

var oAll=document.all;
for(i=0;i<oAll.length;i++){
document.writeln(oAll.item(i).nodeName);
}

#comment
HTML
HEAD
TITLE
META
BODY
DIV
I
P
PRE
SCRIPT

Creating andm Manipulate nodes


Creating node
node

document object

41 Module 6: Document Object Model

BAYON HOSTING

Syntax

HTML

<html>
<head>
<title>Create a Complete Node</title>
</head>
<body>
</body>
</html>
<h1>Welcome</h1>

body

var oH1=document.createElement(h1);

var oTextNode=document.createTextNode(Welcome);

oH1.appendChild(oTextNode);

document.body.appendChild(oH1);

Using removeChild(), replaceChild(), insertBefore()

42 Module 6: Document Object Model

BAYON HOSTING

Syntax
oElementObject.removeChild(oChildElementObject)
oElementObject.replaceChild(oNewChild,oOldChild)
oElementObject.insertBefor(oNewChild,oReferenceChild)

HTML Code

...
<body>
<ul id=list>
<li>Item 0</li>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</body>
...

variable

array

li

ul object

ul

var oList = document.getElementById(list);


var oListItems = oList.getElementsByTagName(li);
oList

reference

ul

oListItems

ul

oList.removeChild(oListItems[2]);
+
var oNewItem=document.createElement(li);
var oTextNode=document.createTextNode(New Item);
oNewItem.appendChild(oTextNode);

oList.replaceNode(oNewItem,oListItems[2]);
reference element
var oNewItem=document.createElement(li);
var oTextNode=document.createTextNode(New Item);
oNewItem.appendChild(oTextNode);
oList.insertBefore(oNewItem,oListItems[2]);

Using createDocumentFragement()
Node
node

node
refresh

documentFragement

screen
refresh

43 Module 6: Document Object Model

Syntax:
var oFragement= document.createDocumentFragement();

var oFragment=document.createDocumentFragment();
for(i=0;i<15;i++){
var oNewNode=document.createElement("h1");
var oTextNode=document.createTextNode("Head " + i);
oNewNode.appendChild(oTextNode);
oFragment.appendChild(oNewNode);
}
document.body.appendChild(oFragment);

BAYON HOSTING

44 Module 7: Error Handling

BAYON HOSTING

Module 7: Error Handling


Kind of Error
syntax errors

error
Syntax errors

runtime errors
interpret

unexpected character

code

compile interpret

example : alert(Welcome;
script function

script

function

external javascript

Runtime errors exception


compile Interpret
function

,
object

method
reference

object

Property

example : window.showMyName();
javascript function

Handling Errors

JavaScript

onerror event
try...catch statement

window object

runtime error exception

onerror event handler


event error

event

window object

page

<head>
<script type=text/javascript>
window.onerror=function(){
alert("got error");

BOM

45 Module 7: Error Handling

BAYON HOSTING

return true;
}
incorrect;
</script>

<body onload=incosistentMethod()>
</body>
browser

return true

error

argument

Error message

URL

Line number

browser
file

<head>
<script type=text/javascript>
window.onerror=function(sMessage, sUrl, sLine){
alert("An error occured:\n + sMessage + \nURL: +
sUrl + \nLine: + sLine);
return true;
}
incorrect;
</script>
<body onload=incosistentMethod()>
</body>

try...catch statement
statement

runtime

Syntax:
try{
statements;
} catch(exception){
statements_when_error_occur;
} [finally]{
statements_always_run.
}
try..caught statement
try

46 Module 7: Error Handling

BAYON HOSTING

catch
catch
finally

try
exception

variable

error object

property

Error Object

string

name

message

string

try{
}catch(oException){
}

47 Module 8: Form Validation

BAYON HOSTING

Module 8: Form Validation


server
element

form

<form/>, <input/>,

web form

<textarea/>, <select/> Browser

element

textbox, combo

box, listbox

Form Basics
form

elements

control object

1. <input/>

type attribute

text, radio, checkbox, file, password, button, submit,


reset, hidden,

image
combo box list box

2. <select/>

textbox

3. <textarea/>
tt i ut

cols, rows

Referencing to Form
reference

form

document.getElementById()
var oForm = document.getElementById(frmRegistration);

form

form collection

document

name attribute
var oForm = document.form1;
var oForm = document.forms[0];
var oForm = document.forms[form1];

Referencing to Form Field


reference

element

form

document.getElementById()
var oTextName = document.getElementById(txtName);
element collection
form object
reference
element

name attribute

48 Module 8: Form Validation

BAYON HOSTING

var oTextName = oForm.elements[0];


var oTextName = oForm.elements[txtName];

element

name tt i ut

property

form

object
var oTextName = oForm.txtName

var oTextName = oForm[txtName];

Form Vaidation
Submitting Forms
submit form

<html>

button

<input type=submit value=Submit />

Submit
<form method=post action=javascript:alert(Submitted)>
method submit()

form object

submit

oForm.submit();

Submitting Once
form

submit

<input type=button value=Submit


onclick=this.disabled=true; this.form.submit()/>

Select Element
List Boxes and Combo Boxes
List Box

Combo Box

<option/> tag
Combo Box:
<select name="selAge" id="selAge">

<select/> tags

49 Module 8: Form Validation

BAYON HOSTING

<option value="1">18-21</option>
<option value="2">22-25</option>
<option value="3">26-29</option>
<option value="4">30-35</option>
<option value="5">Over 35</option>
</select>
List Box:
<select name="selAge" id="selAge" size=3>
<option value="1">18-21</option>
<option value="2">22-25</option>
<option value="3">26-29</option>
<option value="4">30-35</option>
<option value="5">Over 35</option>
</select>

JavaScript

oListBox = document.getElementById(selAge);
oListBox = document.forms[form1].selAge;
oListBox = document.forms[0].selAge;

Accessing Options Collection


Select Element Object

Property

options

collections

option elements
var oListBox = document.getElementById(lstText);
alert(oListBox.options[1].value);

Getting Text from Option


Option element

property

property text

text

oListBox.options[1].text;

Accessing Selected Option


property
select

option

selectedIndex
select

index

option

-1

alert(oListBox.options[oListBox.selectedIndex].text);

Accessing Multiple Selected Option


attribute
select

option

Index

options

var arrSelectedIndex = [];


for ( var i=0; i<oListBox.options.length; i++){
if( oListBox.options[i].selected){
arrSelectedIndex.push(oListBox.options[i].value;
}
}

50 Module 10: Events

BAYON HOSTING

Module 10: Events


Event Handlers/Listeners
Event

user browser

Events

click, load

mouseover

Function

event

listener Function

event click

event handler

event handler event


onclick event handler
JavaScript

HTML.

<div id=oButton onclick=eventHandler()>Click Me!</div>


var oButton=document.getElementById(oButton);
oButton.onclick=function(){
alert(Clicked!);
}

attachEvent(), detachEvent()
method

internet Explorer

event handler

event

attachEvent()

detachEvent()

Syntax:
[Object].attachEvent(oneventname, fnHandler)
[Object].detachEvent(oneventname, fnHandler)
Example
var oButton=document.getElementById("oButton1");
var fnClicked=function(){
alert("OK!");
oButton.detachEvent(onclick,fnClicked);
}
oButton.attachEvent("onclick",fnClicked);

event handler

event

51 Module 10: Events

BAYON HOSTING

event handler

event

attactEvent()

addEventListener(), removeEventListener()
DOM Compliant Browser
Internet Explorer

Opera, Mozilla Firefox, Netscape

attachEvent()

detachEvent()

Syntax:
[Object].addEventListener(eventname,fnHandler,bCapture)
[Object].removeEventListener(eventname,fnHandler,bCapture)
bCapture

browser

bubble event

bubble event

true

capture event
Listen

version

Example
var oButton=document.getElementById("oButton1");
var fnClicked=function(){
alert("OK!");
oButton.detachEvent(click,fnClicked);
}
oButton.attachEvent("click",fnClicked,false);

***

event onload

function

function onload(){
statements;
}

body

Firefox
onload

52 Module 11: File System Object

BAYON HOSTING

Module 11: File System Object


ActiveX Object

File System

Folder, Text File, Copy Folder, Delete Folder, Delete File


File, Folder,

Drive

Working with Text File


File System Object

variable

instance
Syntax:

var oFSO = new ActiveXObject(Scripting.FileSystemObject);

Create Text file


Text File

method

variable

fso

createTextFile()

file object

method

file object

method

Syntax
file object

method

var oTextFile = oFSO.createTextFile(Path,true,true);

Write Data Into Text File


method

File Object

write() writeLine()

oTextFile.write(Hello My First File.);


oTextFile.close();

Open Text File and Read Out


method openTextFile()
(read only)

mode
readLine()
string

readAll()

53 Module 11: File System Object

BAYON HOSTING

var oFSO = new ActiveXObject(Scripting.FileSystemObject);


var oFile = oFSO.openTextFile(Path,1);
alert(oFile.readAll);

Appending Text File


method openTextFile()
write

writeline

mode

54 Excercises

BAYON HOSTING

Excercises
Exercise I

External JavaScript

variable

document.write()

InputBox,

InputBox

OK

OK

InputBox

HTML

(Operand1)

(Operand2)

55 Excercises

BAYON HOSTING

External JavaScript
HTML Code
Variable

link

HTML Page

document.write() method

eval() method

String

HTML Code

Number

document.write()

Exercise 2
InputBox

Math, Physic, Khmer

Number

50

: Fail.

50

100

: Passed.

90

100

:A

80

90

:B

70

80

:C

60

70

:D

50

60

:E

50

:F

Your Result
______________
Math : 60.5
Physic : 80.3
Khmer : 30.8
Average : 57.2
Result : Passed
Grade : E

56 Excercises

BAYON HOSTING

Exercise 3

InputBox

Operand1, Operand2

Operator

Operand1, Operand2,
Number

Operator

Operator

String

+,-,*,/,%

Operand1

Operand2

Operator

Calculation
________________
Operand1: 6
Operand2: 8
Operator: *
Result: 6 * 8 = 48
Operator

Calculation
________________
Operand1: 6
Operand2: 8
Operator: efd
Result: 6 efd 8 = Invalid Operator

Exercise 4
Combo Box

1-31

1-12

1960-2009

Exercise 5
user
inputbox

user

do while

Exercise 6
Input Box

rows

columns

rows
Table

columns

57 Excercises

BAYON HOSTING

Cell

Exercise 7
Input Box

lines

rows

HTML

line = 5
1.@

2.@@@@@

3.@

4.

@@

@@@@

@@

@@@

@@@

@@@

@@@

@@@@@

@@@@

@@

@@

@@@

@@@@@

58 Excercises

BAYON HOSTING

line=10

Exercise 8
TextBox

TextBox

TextBox

user
password

button

Log in

button

Clear

user

Button log in
message

Pl

username

ty

min123

message

compl t

ll info m tion to lo in

mini t to

password

username and password not correct, Please

in!
message

Textbox

user

button clear

W lcom to A mini t to
textbox

59 Excercises

BAYON HOSTING

Exercise 10
function

textbox

+,-,*,/,=

operand1, operand2,

result

function

function

+,-,*,/

argument

operator

function

Result

Exercise 11
Interface

input button, input text

fieldset, legend, table, textarea,


CSS
array

Student List

(text area witdth=130px height=150px)

Add First

Add Last

Remove First

Remove Last

Clear

Asscending

Descending

Backup

List
List
List
List

array

array

60 Excercises

BAYON HOSTING

Restore

array

Backup

array

61 Appendix A: Key Words and Reserved Word

BAYON HOSTING

Appendix A: Key Words and Reserved


Word
Keywords
break

else

new

var

case

finally

return

void

catch

for

switch

while

continue

function

this

with

default

if

throw

delete

in

try

do

instanceof

typeof

Reserved Words
abstract

enum

int

short

boolean

export

interface

static

byte

extends

long

super

char

final

native

synchronized

class

float

package

throws

const

goto

private

transient

debugger

implements

protected

volatile

double

import

public

62 Appendix B: ASCII Code

BAYON HOSTING

Appendix B: ASCII Code


ASCII CODE
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
19
20
21
22
23
24
25
26
27
28
29

30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
49
50
51
52
53
54
55
56
57
58
59

!
"
#
$
%
&
'
(
)
*
+
,
.
/
0
1
2
3
4
5
6
7
8
9
:
;
1
2
3
4
5
6
7
8
9
:
;

60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
79
80
81
82
83
84
85
86
87
88
89

<
=
>
?
@
A
B
C
D
E
F
G
H
I
J
K
L
M
N
O
P
Q
R
S
T
U
V
W
X
Y
O
P
Q
R
S
T
U
V
W
X
Y

90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
109
110
111
112
113
114
115
116
117
118
119

Z
[
\
]
^
_
`
a
b
c
d
e
f
g
h
i
j
k
l
m
n
o
p
q
r
s
t
u
v
w
m
n
o
p
q
r
s
t
u
v
w

120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
139
140
141
142
143
144
145
146
147
148
149

x
y
z
{
|
}
~

150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
169
170
171
172
173
174
175
176
177
178
179

180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
199
200
201
202
203
204
205
206
207
208
209

210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
229
230
231
232
233
234
235
236
237
238
239

240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255

63 Appendix B: ASCII Code

BAYON HOSTING

Special ASCII Code

8 : Backspace

9 : Tab

13 : Enter

16 : shift

17 : ctrl

18 : Alt

19 : Pause Break

20 : Caps Lock

32 : Space

33 : PageUp

34 : PageDown

35 : End Key

36 : Home Key

37 : Left Arrow Key

38 : Up Arrow Key

39 : Right Arrow Key

40 : Down Arrow Key

45 : Insert Key

46 : Delete Key

144 : Num Lock

64 Appendix C: JavaScript Version

BAYON HOSTING

Appendix C: JavaScript Version


JavaScript Versions
Browser Version

JavaScript Version

Netscape 2.x

1.0

Netscape 3.x

1.1

Netscape 4.0 4.0.5

1.2

Netscape 4.0.6 4.7x

1.3

Netscape 6.x, Mozilla 0.9

1.5

Firefox 1.5

1.6

Firefox 2.0

1.7

Firefox 3.0

1.8

Internet Explorer 3.x

JScript 1.0

Internet Explorer 4.x

JScript 3.0

Internet Explorer 5.x

JScript 5.0

Internet Explorer 5.5

JScript 5.5

Internet Explorer 6.x

JScript 5.6

Internet Explorer 7.x

JScript 5.6 (5.7 under Vista)

65 Reference

BAYON HOSTING

Reference
1. Professional JavaScript for Web Developers (Wrox) By Nicholas C. Zakas
2. JavaScript Pocket Reference 2nd Edition (OReilly) By David Flanagan
3. JavaScript 2.0: The Complete Reference, 2nd Edition(McGraw-Hill/Osborne) By Thomas
Powell and Schneider

You might also like