You are on page 1of 53

www.SoftGozar.

Com

) JAVASCRIPT (
:

Professional JavaScript for Web Developers


By : Nicholas C.Zakas

javascript


)(BOM
)(DOM



...

ahmadbadpey@gmail.com

www.SoftGozar.Com


. ) (client
) . (server ) (Client Side
) (server side .

client .
. HTML , CSS , JAVASCRIPT .
) static( .

. ) (Database . ASP PHP JSP
. ) dynamic(
.
JavaScript ) (client-side .
.
Document Object Model : DOM
DOM API ) ( HTML XML .
DOM ) (node .
DOM .
DOM , .
Browser Object Model : BOM
API HTML IE Netscape
BOM.

BOM .
BOM
Content .
BOM :
. Popup
.
) , . (...
.
) (resolution .
Cookie .
BOM .
Window Navigator .
JavaScript :
Case-Sensitive :
. Test test .
: java , C .
var . " " .
)( .
);( : );( .
);( .
);( .
.
: C
C++ // : /* */
//this is a single-line comment
/* this is a multiline
comment */

) (Variables
var . :
;'test ='ali

Var

test ' 'ali .


test String .
.
; 'test 1='ali' , test2='salam

Var

Var .
;test_1='ali' , age=25

Var

) (Java .
; test

Var

.
.

; "Var test ="hi


;)alert(test
// hi
;Test=55
;)alert(test
// 55

:
:
, ) _ ( Underline $.
.1
Underline , $ .
.2
:
; test
; $test
; $1
; _$test2

Var
var
var
var

) Java Script (
:
;"var sTest="hello
;"sTest2=sTest + "world
alert (sTest2); // hello world

sTest2 .
,
.
.

:
) (keywords .
.
. :
var
void
while
with

new
return
switch
this
throw
try
typeof

else
finally
for
function
if
in
instanceof

Break
Case
Catch
Continue
Default
Delete
Do

Identifier expected .
:
.
. :
short
static
super
synchronized
throws
transient
volatile

int
interface
long
native
package
private
protected
public

enum
export
extends
final
float
goto
implements
import

Abstract
Boolean
Byte
Char
Class
Const
Debugger
Double

:
:
undefined , null , boolean , number , string
typeof : .
.
: UndeFined undefined.

: Boolean Boolean.

: Number Number.

: String String.

: Object null .

: Undefind
. Undefined :
Undefined .
"// outputs "Undefined

; )oTemp

; Var oTemp
alert (typeof

.
typeof . Undefined ,
) (oTemp2 .
"// outputs "Undefined
"// outputs "Undefined

; Var oTemp
; )alert (typeof oTemp
; )alert (typeof oTemp2

oTemp2 typeof :
//make sure this variable isnt defined
;//var oTemp2
//try outputting
alert(oTemp2 == undefined); //causes error

Undefined Return .
{ )( Function Testfunc
// leave the function black
}
alert( TestFunc() == undefined ); //outputs true

: Null
null , null .
Java Script Undefined null :
alert(null == undefined); //outputs true

.
Undefined . null
.
: Boolean
Boolean
true false . , false 0
0 false . :
;var bFound = true
;var bLost = false

: Number
. 8 , Integer 16 .
Integer 55 :
;var iNum = 55

:
;var fNum = 5.0

: String
. . .
String ) ' ( ) " ( . ) ' ( )
" ( .
;"var sColor1 = "blue
;'var sColor2 = 'blue

:
.
:
Numbers , Boolean String
, .
Length :
//outputs 4

; "var sColor = "blue


; )alert (sColor.length

Number , Bool String )( tostring .


Boolean true false :
;var bFound = false
alert(bFound.toString()); //outputs false

number :
;var iNum1 = 10
;var fNum2 = 10.0
alert(iNum1.toString()); //outputs 10
alert(fNum2.toString()); //outputs 10

:
:
)( praseInt
)( parseFloat
: I F .
NaN .
)( parseInt NaN .
. " "123red
123 .
var iNum1 = parseInt(1234blue); //returns 1234
;)"var iNum3 = parseInt("22.5
//returns 22
;)"var iNum4 = parseInt("blue
//returns NaN

)( parseFloat )( parseInt .
.

invalid .
:
1234.0
22.5
22.34
NaN

//returns
//returns
//returns
//returns

;)parseFloat(1234blue
;)parseFloat(22.5
;)parseFloat(22.34.5
;)parseFloat(blue

=
=
=
=

fNum1
fNum3
fNum4
fNum6

var
var
var
var

)(Type Casting
type casting :
)( Boolean
)( Number
)( String
)( Boolean True ,
False undefined null :
//false empty string
//true non-empty string
//true non-zero number
//false - null
//false - zero
//true object

;)(Boolean
;)Boolean(hi
;)Boolean(100
;)Boolean(null
;)Boolean(0
;))(Boolean(new Object

=
=
=
=
=
=

b1
b2
b3
b4
b5
b6

var
var
var
var
var
var

)( Number )( ParseInt )( ParseFloat .


)( ParseInt )(ParseFloat .
4.5.6 4.5 . )( Number NaN
)( Number .
)( Number )( ParseInt )( ParseFloat
. )( Number :
0
1
NaN
0
5.5
56
NaN
NaN
100

)Number(false
)Number(true
)Number(undefined
)Number(null
)Number(5.5
)Number(56
)Number(5.6.7
))(Number(new Object
)Number(100

)( String :
null

var s1 = String(null); //

:

HTML . script .
head . language
src type
MIME TYPE text/javascript .
language javascript javascript 1.3 ) .
javascript ( .
script src
script . :
><html
><head
><title>Title of Page</title
><script language=JavaScript
;var i = 0
></script
><script language=JavaScript src=../scripts/external.js></script
></head
><body
><!-- body goes here --
></body
></html

. ) inline
( . script javascript .
: javascript
. .
script .
:
><html
><head
><title>Title of Page</title
><script language=JavaScript
{ )(function sayHi
;)alert(Hi
}
></script
></head
><body
><!-- body goes here --
></body
></html

)( sayhi external.js
) ( :

www.SoftGozar.Com

><html
><head
><title>Title of Page</title
><script language=JavaScript src=external.js></script
></head
><body
><!-- body goes here --
></body
></html

inline : External
inline external
inline
:
: source
.
: External
) (cache cache
.
:
.
script :
head
body .
body .
script body
. :
><html
><head
><title>Title of Page</title
><script language=JavaScript
{ )(function sayHi
;)alert(Hi
}
></script
></head
><body
><script language=JavaScript
;)(sayHi
></script
><p>This is the first text the user will see.</p
></body
></html

)( sayHi . alert
This is the first text the user will see .
) (Event Handler . :

><html
><head
><title>Title of Page</title
><script language=JavaScript
{ )(function sayHi
;)alert(Hi
}
></script
></head
><body
><input type=button value=Call Function onclick=sayHi() /
></body
></html

input )( sayHi .
onclick .

. script
:

><html
><head
><title>Title of Page</title
></head
><body
><script language=JavaScript
;)(sayHi
></script
><p>This is the first text the user will see.</p
><script language=JavaScript
{ )(function sayHi
;)alert(Hi
}
></script
></body
></html

.
)( sayHi script .
:
.
. > <script

.

HTML .
.
> <script
.
HTML <!-- > --
.
:
<script language=JavaScript><!-- hide from older browsers
{ )(function sayHi
;)alert(Hi
}
>//--
></script

slash .
> --

. // .

> <noscript .
> <noscript .
) ( .
:
><html
><head
><title>Title of Page</title
><script language=JavaScript
{ )(function sayHi
;)alert(Hi
}
></script
></head
><body
><script language=JavaScript
;)(sayHi
></script
><noscript
<p>Your browser doesnt support JavaScript. If it did support
>JavaScript, you would see this message: Hi!</p
></noscript
<p>This is the first text the user will see if JavaScript is enabled. If
>JavaScript is disabled this is the second text the user will see.</p
></body
></html


Array

) ( java array )
( . :
;)(var aValues = new Array

:
;)var aValues = new Array(20

:
;)(var aColors = new Array
;aColors[0] = red
;aColors[1] = green
;aColors[2] = blue

.
:
;)var aColors = new Array(red, green, blue

:
alert(aColors[1]); //outputs green

length .
.
25
3 24 null 26 :
;)var aColors = new Array(red, green, blue
alert(aColors.length); //outputs 3
;aColors[25] = purple
aColors(arr.length); //outputs 26

)] [( , :
;]var aColors = [red, green, blue
alert(aColors.length); //outputs 3
;aColors[25] = purple
alert(aColors.length); //outputs 26

:
;]var aColors = [red, green, blue
alert(aColors.toString()); //outputs red,green,blue
alert(aColors.valueOf()); //outputs red,green,blue
alert(aColors.toLocaleString()); //outputs red,green,blue

)( join ) (separator .
. :
;]var aColors = [red, green, blue
alert(aColors.join(,)); //outputs red,green,blue
alert(aColors.join(-spring-)); //outputs red-spring-green-spring-blue
alert(aColors.join(][)); //outputs red][green][blue

string
!!!
string )( split
.
, :
;var sColors = red,green,blue
;)var aColors = sColors.split(,


. :
;var sColors = green
;)(var aColors = sColors.split
alert(aColors.toString()); //outputs g,r,e,e,n

)( concat .
. :
;]var aColors = [red, green, blue
;)var aColors2 = arr.concat(yellow, purple
alert(aColors2.toString()); //outputs red,green,blue,yellow,purple
alert(aColors.toString()); //outputs red,green,blue

)( slice .
.
. :
;]var aColors = [red, green, blue, yellow, purple
;)var aColors2 = arr.slice(1
;)var aColors3 = arr.slice(1, 4
alert(aColors2.toString()); //outputs green,blue,yellow,purple
alert(aColors3.toString()); //outputs green,blue,yellow

) arr.slice(n,m n m-1 .

stack
queue .
stack )( push )( pop
.
)( push )( pop
. )( pop . :
;var stack = new Array
;)stack.push(red
;)stack.push(green
;)stack.push(yellow
alert(stack.toString()); //outputs red,green,yellow
;)(var vItem = stack.pop
alert(vItem); //outputs yellow
alert(stack.toString()); //outputs red,green

. )( shift
. )( unshift
:
;]var aColors = [red, green, yellow
;)(var vItem = aColors.shift
alert(aColors.toString()); //outputs green,yellow
alert(vItem); //outputs red
;)aColors.unshift(black
alert(aColors.toString()); //outputs black,green,yellow

) (ordering . )( reverse
. :
;]var aColors = [red, green, blue
;)(aColors.reverse
alert(aColors.toString()); //outputs blue,green,red

)( sort .
. :
;]var aColors = [red, green, blue, yellow
;)(aColors.sort
alert(aColors.toString()); //outputs blue,green,red,yellow

:
]var aColors = [3, 32, 2, 5
;)(aColors.sort
alert(aColors.toString()); //outputs 2,3,32,5

)( splice .
.
:
: .
: . ) arr.splice(0, 2
arr .
: :
.
. ) arr.splice(2, 0, red, green red
green .
:
: .
) arr.splice(2, 1, red, green red green
) (2 .

)( : string
) ( . Hello World
:
;)var oStringObject = new String(hello world

string length .
:
:

)( : charAt . :
;)var oStringObject = new String(hello world
alert(oStringObject.length); //outputs 11

)( charCodeAt :
;)var oStringObject = new String(hello world
alert(oStringObject.charCodeAt(1)); //outputs 101

101 e .

)( concat . :
;) var oStringObject = new String(hello
;)var sResult = oStringObject.concat(world
alert(sResult); //outputs hello world
alert(oStringObject); //outputs hello

)( concat + .
:

)( indexOf )( lastIndexOf
.
-1 .
)( indexOf ) (0
. :
;)var oStringObject = new String(hello world
alert(oStringObject.indexOf(o)); //outputs 4
alert(oStringObject.lastIndexOf(o)); //outputs 7

O .
:

)( localeCompare ) .
)( strcmp C++ (.
:
.1 -1 .
.2 0 .
.3 1 .
:
;)var oStringObject = new String(yellow
alert(oStringObject.localeCompare(brick)); //outputs 1
alert(oStringObject.localeCompare(yellow)); //outputs 0
alert(oStringObject.localeCompare (zoo)); //outputs -1

slice() : )(. substring


) .
(.
length .
:

var oStringObject = new String(hello world);


alert(oStringObject.slice(3)); //outputs lo world
alert(oStringObject.substring(3)); //outputs lo world
alert(oStringObject.slice(3, 7)); //outputs lo w
alert(oStringObject.substring(3,7)); //outputs lo w


.
. slice()
(. ) . sustring()

:
var oStringObject= new String(hello world);
alert(oStringObject.slice(-3)); //outputs rld
alert(oStringObject.substring(-3)); //outputs hello world
alert(oStringObject.slice(3, -4)); //outputs lo w
alert(oStringObject.substring(3,-4)); //outputs hel

: 8 -3
oStringObject.slice(8);

: . .
oStringObject.substring(0);

: . 8
oStringObject.slice(3,8);

:
oStringObject.substring(3,0);

toLowerCase () toUpperCase()
toLowerCase() toUpperCase()
:
var oStringObject= new String(Hello World);
alert(oStringObject.toLocaleUpperCase()); //outputs HELLO WORLD
alert(oStringObject.toUpperCase()); //outputs HELLO WORLD
alert(oStringObject.toLocaleLowerCase()); //outputs hello world
alert(oStringObject.toLowerCase()); //outputs hello world

) ( :
.
.
: Math
.
.
)( min )(: max
.
:
;)54, 32, 16
54
;)54, 32, 16
3

var iMax = Math.max(3,


alert(iMax); //outputs
var iMin = Math.min(3,
alert(iMin); //outputs

min max .
abs() .
. )( ceil )( floor
)( round .
)( : round
.
)( : ceil .
)( : floor .
:
alert(Math.ceil(25.5)); //outputs 26
alert(Math.round(25.5)); //outputs 26
alert(Math.floor(25.5)); //outputs 25

:
)( : Log .
)( : Pow :
;)var iNum = Math.pow(2, 10

)( : sqrt :
;)var iNum = Math.sqrt(4
alert(iNum); //outputs 2

Math :
)acos(x) , asin(x) , atan(x) , atan2(x, y) , cos(x) , sin(x) , tan(x

Math )( random . 0 1
) 0 (1 .
:
number = Math.floor(Math.random() * total_number_of_choices +
)first_possible_value

1 10 :
;)var iNum = Math.floor(Math.random() * 10 + 1

:
{ )function selectFrom(iFirstValue, iLastValue
;var iChoices = iLastValue iFirstValue + 1
;)return Math.floor(Math.random() * iChoices + iFirstValue
}
//select from between 2 and 10
;)var iNum = selectFrom(2, 10

. :
;]var aColors = [red, green, blue, yellow, black, purple, brown
;])var sColor = aColors[selectFrom(0, aColors.length-1

1 .
:
)( encodeURI )( encodeURIComponent encode ) URI(
. space .
encode .
)( encodeURI ) ( http://itcom.pnuab.ac.ir/illegal value.htm
illegal value.htm .
) / ( : ...
encode encode . :
;var sUri = http://www.wrox.com/illegal value.htm#start
;))alert(encodeURI(sUri
;))alert(encodeURIComponent(sUri

:
http://www.wrox.com/illegal%20value.htm#start
http%3A%2F%2Fwww.wrox.com%2Fillegal%20value.htm%23start

decode :
)( decodeURI
)( decodeURIComponent
:
;var sUri = http%3A%2F%2Fwww.wrox.com%2Fillegal%20value.htm%23start
;))alert(decodeURI(sUri
;))alert(decodeURIComponent(sUri

:
http%3A%2F%2Fwww.wrox.com%2Fillegal value.htm%23start
http://www.wrox.com/illegal value.htm#start

)( eval .
. :
;))eval(alert(hi

:
;)alert(hi

.

:
;var msg = hello world
;))eval(alert(msg

)( eval )( eval . :
;)} ;)eval(function sayHi() { alert(hi
;)(sayHi


.
HTML Javascript
.
. object Date
.
:
;)(var d = new Date

)( Date 12:00:00 01/01/1970


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

:
1269938333117

.
:

)(getDate
)(getMonth
)(getFullYear
)(getHours
)(getMinutes
)(getSeconds
)(getDate
)(getTime
)(valueOf
)(toString

1 31 .
0 11
4
0 23
0 59 .
0 59
0 6 .
) 6 (sunday
1/1/1970
1/1/1970

... .

Date )( getTimezoneOffset
. ) .
: ( .
) : BOM (Browser Object Model
BOM BOM .
, :

BOM : .

: window
Window .
.
:
Window :
: moveBy(dx,dy) (
x y .
x,y.
: moveTo(x,y) (
x,y . .
: resizeBy(w,h) (
w h size .
.
: resizeTo(w,h) (
w h . .
:
)window.moveBy(10, 20
// 10px 20px .
)window.resizeTo(150, 300
150px 300px .
)window.resizeBy(150, 0
150px .
)window.moveTo(0, 0
.


)( open :

.1

.2

.3
Booelan
.4
.
, .
.

:
) = ( ) ( , .
:
: Left

: Top

: Width

: Height

) : Resizable , (Yes,No

) scroll : Scrollable , (Yes,NO

) : Toolbar , (Yes,NO .

) : Status , (Yes,No

) : Location , (Yes,No .

.
Open Window Window .
)( close .
.
: System Dialog
Window .
: alert() Ok
:
> "<scritp type="text/javascript
;)'alert('Hello world
></script

: confirm() . Cancel .
> "<scritp type="text/javascript
; )' ? confirm('Are you sure
></script

Ok True Cancel False .

: prompt() . , Ok , Cancel text field


.
:
.1 .
.2 Text field

> "<scritp type="text/javascript


;)'Prompt('what is your name','ali
></script

Ok Text field Cancel


Null .

: statusbar
. status
defaultStatus .
Status Statusbar
defaultstatus Statusbar .
:
'<a href="books.htm" onmouseover="window.status='Information on Wrox books.
>">Books</a

Timeouts : Intervals
.
: setTimeouts . Intervals
o
. :
.
.1
.
.2
.
:
> "<scritp type="text/javascript
;)setTimeout("alert('Hello world!')", 1000
></script
---------------------------------------------------------> "<scritp type="text/javascript
;)setTimeout(function() { alert("Hello world!"); }, 1000
></script
---------------------------------------------------------> "<scritp type="text/javascript
{ )(function sayHelloWorld
;)"!alert("Hello world
}
;)setTimout(sayHelloWorld, 1000
></script

)( setTimeout )( ClearTimeout :
> "<scritp type="text/javascript
;)var iTimeoutId = setTimeout("alert('Hello world!')", 1000
;)clearTimeout(iTimeoutId
></script

: setIntervals o .
, ClearInterval :
;)setInterval(alert(Hello world!) , 1000
----------------------------------------------------;)setInterval(function() { alert(Hello world!); }, 1000
----------------------------------------------------{ )(function sayHelloWorld
;)!alert(Hello world
}
;)setInterval(sayHelloWorld, 1000

: history
, History
, . History Window :
)( Go : .
. :
;)window.history.go(-1

:
;)window.history.go(+1

)( back )( forward .
//go back one
;)(history.back
//go forward one
;)(history.forward

lenght history :
;)"alert("There are currently " + history.length + " pages in history.

: Document
BOM DOM . .
URL .
;"document.URL = "http://www.tavoosebehesht.ir/

.
:

anchors

embeds

embed

forms

images

links

index .
:
;]Document.images[0
Or
; ]'Document.images['image-name

, :
document.images[0].src

)( Write )( Writeln .
: location
location . location.href
URL :
;"document.href= "http://www.tavoosebehesht.ir/

)( assign .
)( reload . Cache
Server . false Catch true Server
.
: Navigator
BOM.
.
:

appcodeName

appName

appMinotVersion

appVersion

browserLanguage

cookieEnabled

cpuClass

cpu

javaEnabled

Language

mimeType

mimetype

Platform

platform .

: screen
. :

availHeight

availWidth

colorDepth

height

width

. fullscreen
:
;)Window.MoveTo(0,0
;)Window.resizeTo(screen.availWidth,screen.availHegiht

) DOM BASIC (
DOM HTML .
HTML :
><html
><head
><title>DOMinating JavaScript</title
></head
><body
><h1>DOMinating JavaScript</h1
<p>If you need some help with your JavaScript, you might like to read articles
from <a href=http://www.danwebb.net/ rel="external">DanWebb</a>,
><a href="http://www.quirksmode.org/" rel="external">PPK</a
and
<a href="http://adactio.com/" rel="external">Jeremy Keith</a>.
></p
></body
></html

www.SoftGozar.Com

) node( .
DOM document .
:

) (node .
:
: Document ) (. document
) Node ( .
: Element . > <tag></tag
> <tag / . . ) element Node
( .
: Text . .
) text Node . (.
:

: Attr . ) attribute Node


( . DOM .
href rel
:

: Comment ) . comment (.
document .
.
:
/

nodeName

String

. .

nodeValue

String

. .

nodeType

Number

ownerDocument

Document

document

firstChild

Node

lastChild

Node

childNodes

NodeList

)(

previousSibling

Node

)( .
null .

nextSibling

Node

)( .
null .

)(hasChildNodes

Boolean

childNodes
)( True

)appendChild(node

Node

node childNodes .

)removeChild(node

Node

node childNodes .

)replaceChild (newnode, oldnode

Node

oldnode childNodes newnode


.

)insertBefore (newnode, refnode

Node

newnode childNodes refnode


.

: DOM

:
:
<html>
<head>
<title>DOM Example</title>
</head>
<body>
<p>Hello World!</p>
<p>Isnt this exciting?</p>
<p>Youre learning to use the DOM!</p>
</body>
</html>

document documentElement HTML


: .
var oHtml = document.documentElement ;

: body head
var oHead = oHtml.firstChild;
var oBody = oHtml.lastChild;

:
var oHead = oHtml.childNodes[0];
var oBody = oHtml.childNodes[1];

:
alert(oHtml.childNodes.length); //outputs 2

: item()
var oHead = oHtml.childNodes.item(0);
var oBody = oHtml.childNodes.item(1);

. body document.body DOM


var oBody = document.body;

: oHtml oBody oHead


alert(oHead.parentNode == oHtml);
alert(oBody.parentNode == oHtml);
alert(oBody.previousSibling == oHead);
alert(oHead.nextSibling == oBody);
alert(oHead.ownerDocument == document);

//outputs
//outputs
//outputs
//outputs
//outputs

true
true
true
true
true

:
DOM :
) : getAttribute(name name .
) : setAttribute(name,new Value name new Value .
) : removeAttribute(name name .
. ID
:
;)var sId = oP.getAttribute(id

Id :
;)oP.setAttribute(id, newId

:
.
DOM node .
)(: getElementsByTagName
.
;)var oImgs = document.getElementsByTagName(img

img oImgs .
:
;)var oPs = document.getElementsByTagname(p
;)var oImgsInP = oPs[0].getElementsByTagName(img

:
;)*(var oAllElements = document.getElementsByTagName

)(: getElementsByName
DOM name .
:

<html>
<head>
<title>DOM Example</title>
</head>
<body>
<form method=post action=dosomething.php>
<fieldset>
<legend>What color do you like?</legend>
<input type=radio name=radColor value=red /> Red<br />
<input type=radio name=radColor value=green /> Green<br />
<input type=radio name=radColor value=blue /> Blue<br />
</fieldset>
<input type=submit value=Submit />
</form>
</body>
</html>

. radiobutton .
. radiobutton . radiobutton
var oRadios = document.getElementsByName(radColor);

: radiobutton
alert(oRadios[0].getAttribute(value)); //outputs red

: getElementById()
id . id
. id
: .
<html>
<head>
<title>DOM Example</title>
</head>
<body>
<p>Hello World!</p>
<div id=div1>This is my first layer</div>
</body>
</html>

div1 div getElementsByTagName()


:
var oDivs = document.getElementsByTagName(div);
var oDiv1 = null;
for (var i=0; i < oDivs.length; i++){
if (oDivs[i].getAttribute(id) == div1) {
oDiv1 = oDivs[i];
break;
}
}

: getElementById()
var oDiv1 = document.getElementById(div1);

:
DOM .
:
:
) : createAttribute(name name
) : createComment(text
) : createElement(tagname .
) : createTextNode(text text
)(createElement(), createTextNode(), appendChild
:
><html
><head
><title>createElement() Example</title
></head
><body
></body
></html

:
><p>Hello World !</p

p .
;)var oP = document.createElement(p

:
;)!var oText = document.createTextNode(Hello World

append p . )( appendchild .
.
;)oP.appendChild(oText

body append . :
;)oP.appendChild(oText

)(removeChild(), replaceChild(), insertBefore


. )( removeChild
. . :
;]var oP = document.body.getElementsByTagName(p)[0
;)document.body.removeChild(oP

)( replaceChild . :

;)var oNewP = document.createElement(p


;) !var oText = document.createTextNode(Hello Universe
;)oNewP.appendChild(oText
;]var oOldP = document.body.getElementsByTagName(p)[0
;)oOldP.parentNode.replaceChild(oNewP, oOldP

)( insertBefore .
.
)(createDocumentFragment
update .
.
.
) (documentFragment .
. .
.
:
;]var arrText = [first, second, third, fourth, fifth, sixth
;)(var oFragment = document.createDocumentFragment
{ )for (var i=0; i < arrText.length; i++
;)var oP = document.createElement(p
;)]var oText = document.createTextNode(arrText[i
;)oP.appendChild(oText
;)oFragment.appendChild(oP
}
;)document.body.appendChild(oFragment

DOM : HTML
DOM DOM HTML .

.
. :
><img src=mypicture.jpg border=0 /

src border )( getAttribute )( setAttribute :


;))alert(oImg.getAttribute(src
;))alert(oImg.getAttribute(border
;)oImg.setAttribute(src, mypicture2.jpg
;)oImg.setAttribute(border, 1

get set :
;)alert(oImg.src
;)alert(oImg.border
;oImg.src = mypicture2.jpg
;oImg.border = 1

class :

className .

.
:
:
<table border=1 width=100%>
<tbody>
<tr>
<td>Cell 1,1</td>
<td>Cell 2,1</td>
</tr>
<tr>
<td>Cell 1,2</td>
<td>Cell 2,2</td>
</tr>
</tbody>
</table>

DOM
:
//create the table
var oTable = document.createElement(table);
oTable.setAttribute(border, 1);
oTable.setAttribute(width, 100%);
//create the tbody
var oTBody = document.createElement(tbody);
oTable.appendChild(oTBody);
//create the first row
var oTR1 = document.createElement(tr);
oTBody.appendChild(oTR1);
var oTD11 = document.createElement(td);
oTD11.appendChild(document.createTextNode(Cell 1,1));
oTR1.appendChild(oTD11);
var oTD21 = document.createElement(td);
oTD21.appendChild(document.createTextNode(Cell 2,1));
oTR1.appendChild(oTD21);
//create the second row
var oTR2 = document.createElement(tr);
oTBody.appendChild(oTR2);
var oTD12 = document.createElement(td);
oTD12.appendChild(document.createTextNode(Cell 1,2));
oTR2.appendChild(oTD12);
var oTD22 = document.createElement(td);
oTD22.appendChild(document.createTextNode(Cell 2,2));
oTR2.appendChild(oTD22);
//add the table to the document body
document.body.appendChild(oTable);

DOM table, tody, tr


.
:
: caption caption ) . (.
: tBodies )( tbody
: tFoot tfoot
: tHead thead
: Rows
)( : createThead thead
)( : createTfoot tfoot
)( : createCaption caption
)( : deleteThead thead
)( : deleteTfoot tfoot
)( : deleteCaption Caption
) : deleteRow(position position
) : insertRow(position position
: tbody
: Rows tbody
) : deleteRow(position position
) : insertRow(position position
: tr
: Cells
) : deleteCell(position position
) : insertCell(position position .

:
//create the table
;)var oTable = document.createElement(table
;)oTable.setAttribute(border, 1
;)oTable.setAttribute(width, 100%
//create the tbody
;)var oTBody = document.createElement(tbody
;)oTable.appendChild(oTBody
//create the first row
;)oTBody.insertRow(0
;)oTBody.rows[0].insertCell(0
oTBody.rows[0].cells[0].appendChild(document.createTextNode(Cell
;))1,1
;)oTBody.rows[0].insertCell(1
oTBody.rows[0].cells[1].appendChild(document.createTextNode(Cell
;))2,1
//create the second row
;)oTBody.insertRow(1
;)oTBody.rows[1].insertCell(0
oTBody.rows[1].cells[0].appendChild(document.createTextNode(Cell
;))1,2
;)oTBody.rows[1].insertCell(1
oTBody.rows[1].cells[1].appendChild(document.createTextNode(Cell
;))2,2
//add the table to the document body
;)document.body.appendChild(oTable

:
.
form textarea select input ..
... .
:
form :
: Method GET POST
.
: Action ) server side (
. ) (URL .
: Enctype Encoding application/x-url-
encoded . file
multipart/form-data .
: Accept MIME type .
: Accept-charset .

:
.
) (reference :
form . .
)( getElementById Id .
][ forms document DOM .
. :
var oForm = document.forms[0] ; // get the first form
var oOtherForm = document.forms["formZ"] ; // get the form whose name is
""formZ

:
... ][ elements
.
.
var oFirstField = oForm.elements[0] ; // get the first form field
var oTextbox1 = oForm.elements["textbox1"] ; // get the field with the name
""textbox1

oForm .
textbox1 oForm .
) (
:
"//get the field with the name "textbox1

;var oTextbox1 = oForm.textbox1

) textbox1 (Id oForm .


space )][( :
"var oTextbox1 = oForm.textbox1; //get the field with the name "textbox1

: form
) (Hidden :
: disabled
.
: form .

)( : focus ) focus( .

)( : blur ) focus( .
: blur ) focus( .
: focus ) focus( .
:
;]var oField1 = oForm.elements[0
;]var oField2 = oForm.elements[1
//set the first field to be disabled
;oField1.disabled = true
//set the focus to the second field
;)(oField2.focus
?//is the form property equal to oForm
"alert(oField1.form == oForm); //outputs "true

: hidden form .

) Submit( :
HTML submit submit .
:
><input type="submit" value="Submit" /
><input type="image" src="submit.gif" /

.
Enter .
:
>")<form method="post" action="javascript:alert(Submitted

)( submit .
DOM form .
) ( :
;)"oForm = document.getElementById("form1
;]"oForm = document.forms["form1
;]oForm = document.forms[0

:
;)(oForm.submit

form !!!

submit .
) Request( .

: ) (disabled .
submit :
><input type="submit" value="Submit" /

:
;<input type=button value=Submit onclick=this.disabled=true
>this.form.submit() /

.
this form .
)( submit )( reset ) reset
( :
><input type=button value=Reset onclick=document.forms[0].reset() /

textbox :
text box html .
:
><input type="text"/

:
><textarea>Content</textarea

textbox type input text . size


textbox . value textbox
. maxlength textbox .
><input type="text" size="25" maxlength="50" value="initial value" /

textarea . rows cols


textarea .
><textarea rows="25" cols="5">initial value</textarea

input .
: textbox
value
.
) txt1 (Id :
;)"var oTextbox1 = document.getElementById("txt1

value
.
;)'alert ('oTextbox1.length

textbox .
) oTextbox1 ( :
;'oTextbox1.value='first textbox

textbox :
)( select .
) (focus . )( select
)( focus ) . (.
textbox :
;)(oTextbox1.focus
;)(oTextbox1.select

textbox :
blur focus change select
.
: Change textbox .
: Select textbox
)( select .
change blur blur
change textarea .
textbox blur
change blur .
textbox :
textbox
)( this.select onFocus .
:
><input type="text" onfocus="this.select();" /
><textarea onfocus="this.select()"></textarea

Tab :
textfield )(
.
maxlength input :
><input type="text" maxlength="4" /

)( focus .
test :
{)function test(oTextbox
;var oForm = oTextbox.form
//make sure the textbox is not the last field in the form
if (oForm.elements[oForm.elements.length-1] != oTextbox
{ ))"&& oTextbox.value.length == oTextbox.getAttribute("maxlength
{ )for (var i=0; i < oForm.elements.length; i++
{ )if (oForm.elements[i] == oTextbox
{ )for(var j=i+1; j < oForm.elements.length; j++
{ )"if (oForm.elements[j].type != "hidden
;)(oForm.elements[j].focus
;return
}
}
;return
}
}
}
;}

textbox . onKeyUp
:
><input type='text' maxlength='4' onKeyUp='test(this)' /

: textarea
textfield maxlength textarea
. javascript .
)( isNotMax . :
{)Function isNotMax(oTextbox
; )'Return oTextbox.value.length != oTextarea.getAttribute('maxlength
}

. textbox maxlength
True False .
maxlength textarea getAttribute
.
onKeyPress .
. :
<textarea rows='10' cols='25' maxlength='150' onKeyPress='return
>isNotMax(this)'></textarea

onKeyPress .
.
MAX True
.

listbox combobox :
Listbox combobox HTML select
combobox .
>"<select name="selAge" id="selAge
><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

value .
listbox size
select . listbox 5
:
>"<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

:
;)"oListbox = document.getElementById("selAge

DOM select option option .


)( option value . :
;)"oListbox = document.getElementById("selAge

option index option .


"alert(oListbox.options[1].index); //outputs "1

option length option select


.
) option(
) option( :
select selectedIndex Index .
-1 .
' multiple='multiple select
.
selectedIndex list .

www.SoftGozar.Com

index :
.
listbox selected
index option . selected
) true ( ) Fasle ( .
{ )function getSelectedIndexes (oListbox
;var arrIndexes = new Array
{ )for (var i=0; i < oListbox.options.length; i++
{ )if (oListbox.options[i].selected
;)arrIndexes.push(i
}
}
;return arrIndexes
;}

.
option :
list .
:
list .
DOM option select
{ )Function test (oListbox, sName, sValue
;)"var oOption = document.createElement("option
;))oOption.appendChild(document.createTextNode(sName
{ )if (arguments.length == 3
;)oOption.setAttribute("value", sValue
}
;)oListbox.appendChild(oOption
}

value option value option


. value arqument.length .
option :
option .
options null
.
oListbox.remove(0); //remove the first option

)( remove ) (index :
{ )Function test (oListbox, iIndex
;)oListbox.remove(iIndex
}

option listbox )( remove


.
{ )Function test (oListbox
{ )for (var i=oListbox.options.length-1; i >= 0; i--
;)ListUtil.remove(oListbox, i
}
}

.
index option .
index index .

HTML
.

.
. ...
. click
mouseover load ... . ) event Handler
( . click onclick .
: . HTML

) ( . :

;)'Var oDiv = document.getElementById('div1


{)( oDiv.onclick= function
;)'!!! alert('I Was Clicked
}

.
. :
><div onclick='alert("I Was Clicked !!!")'></div

. onclick OnClick : ONCLICK


.

:
:
mouse .
keyboard keyboard .
HTML .
DOM .
: Mouse :
: Onclick mouse ) . ( .
Enter .
: Ondblclick mouse .
: Onmousedown mouse .
: onMouseOut
.
: onmouseover .
: onmouseup mouse .
: Onmousemove .
.
:
click mousedown mouseup click .
dblclick :
mousedown .
mouseup .
click .
mousedown .
mouseup .
click .
dblclick .
mouseout mousemove
mouseover .

: keyboard
keyboard .
:
: onkeydown .
.
: Onkeypress .
.
: Onkeyup .
: keyboard
:
keydown
-
Keypress
-
Keyup
-
shift :
Keydown
-
Keyup
-
keypress keydown
.
keydown .
:
:
: Load img object
. onload > <body .
loading complete
:
><body onload='alert("loading complete !!!")'></body

: Unload . (close) X
.
: Abort object
.
: Error
object .
: Select )
textarea (input .

www.SoftGozar.Com

: Change ) (focus
select .
: Submit form submit .
: Reset form reset .
: Focus .
: Blur .

: event
event
.
event .
:

mouse

:
Internet Explorer window .
event :
{ )( oDiv.onclick = function
;var oEvent = window.event
}

window .
event .
DOM event . :
{ )( oDiv.onclick = function
;]var oEvent = arguments[0
}

:
{ )oDiv.onclick = function (oEvent
}

: event
:
: Shiftkey shift true false .
: altkey alt true false .
: ctrlkey ctrl true false .
: Button mouse .
:

www.SoftGozar.Com

:
: .
: .
: .
: .
: .
: .
: .
clienX : clientY .
screenX : screenY .
pageX : pageY x,y .
: type click mouseover...
: keyCode .
: Target ) ( .
) Cookie( :

.
.
cookie document :
;"document.cookie="name=value ; expires=Date ; path = path ; domain=domain

:
;Var x = document.cookie


) name=value ; ( cookie .
.

name=value

expires=date

path=path
domain=domain

.
.

)( toGMTString Date .
.

.

.

name=ali
=expires
13/06/2003 00:00:00

path=/tutorials/
domain = mysite.com

www.SoftGozar.Com

username ali 15/02/2010 :


;" document.cookie = " username = ali ; expires = 15/02/2010 00:00:00

myCookie this is my cookie :


;)document.cookie = myCookie= + escape(This is my Cookie

: escape
. % . space
%20 . )( encodeURIComponent .

:
.
:
) function delete_cookie ( cookie_name
{
var cookie_date = new Date ( ); // current date & time
;) cookie_date.setTime ( cookie_date.getTime() - 1
;)(document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString
}

. username :
; )"delete_cookie ("username

:
)( .
cookie document :
;var x = document.cookie

)( name=value ;
. x :
""username=ali; password=abc123

: username ali password . abc123


x x split
string .
:

:
var
Var
Var
Var

www.SoftGozar.Com

allCookie
cookieParts
fistCookie
secondCookie

=
=
=
=

document.cookie;
allCookie.split(";");
cookieParts[0];
cookieParts[1];

Var nameOfFirstCookie = firstCookie.split("=")[0];


Var valueOfFirstCookie = firstCookie.split("=")[1];
Var nameOfSecondCookie = firstCookie.split("=")[0];
Var valueOfSecondCookie = firstCookie.split("=")[1];

www.SoftGozar.Com

You might also like