Vous êtes sur la page 1sur 38

uction

Ja%aScript Intro(uction - Pre%ious .e!t Chapter /

To ents ents es ors risons

Ja%aScript is the most popular scriptin+ lan+ua+e on the internet0 an( wor$s in all ma)or browsers0 such as Internet E!plorer0 "irefo!0 Chrome0 Opera0 an( Safari. What 1ou Shoul( ,lrea(& 2now efore &ou continue &ou shoul( ha%e a basic un(erstan(in+ of the followin+3

o!es ns p oop oops

HTM# 4 5HTM#

If &ou want to stu(& these sub)ects first0 fin( the tutorials on our Home pa+e. What is Ja%aScript6

atch

Ja%aScript was (esi+ne( to a(( interacti%it& to HTM# pa+es Ja%aScript is a scriptin+ lan+ua+e , scriptin+ lan+ua+e is a li+htwei+ht pro+rammin+ lan+ua+e Ja%aScript is usuall& embe((e( (irectl& into HTM# pa+es Ja%aScript is an interprete( lan+ua+e 7means that scripts e!ecute without preliminar& compilation8 E%er&one can use Ja%aScript without purchasin+ a license

Te!t nes

s Intro

n ,re Ja%a an( Ja%aScript the same6 .O9 Ja%a an( Ja%aScript are two completel& (ifferent lan+ua+es in both concept an( (esi+n9 Ja%a 7(e%elope( b& Sun Micros&stems8 is a powerful an( much more comple! pro+rammin+ lan+ua+e : in the same cate+or& as C an( C;;. What can a Ja%aScript (o6

ced

r s on on Maps

Ob)ect r&

les

JavaScript gives HTML designers a programming tool - HTM# authors are normall& not pro+rammers0 but Ja%aScript is a scriptin+ lan+ua+e with a %er& simple s&nta!9 ,lmost an&one can put small <snippets< of co(e into their HTM# pa+es

es E!amples r E!amples !amples

JavaScript can put d"namic text into an HTML page - , Ja%aScript statement li$e this3 (ocument.write7<>h?@< ; name ; <>4h?@<8 can write a %ariable te!t into an HTM# pa+e JavaScript can react to events - , Ja%aScript can be set to e!ecute when somethin+ happens0 li$e when a pa+e has finishe( loa(in+ or when a user clic$s on an HTM# element JavaScript can read and #rite HTML elements - , Ja%aScript can rea( an( chan+e the content of an HTM# element JavaScript can be used to validate data - , Ja%aScript can be use( to %ali(ate form (ata before it is submitte( to a ser%er. This sa%es the ser%er from e!tra processin+ JavaScript can be used to detect t$e visitor%s bro#ser : , Ja%aScript can be use( to (etect the %isitorAs browser0 an( : (epen(in+ on the browser : loa( another pa+e specificall& (esi+ne( for that browser JavaScript can be used to create coo&ies : , Ja%aScript can be use( to store an( retrie%e information on the %isitorAs computer

ate

nces

Ob)ects M Ob)ects

Ja%aScript How To - Pre%ious .e!t Chapter /

The HTM# >script@ ta+ is use( to insert a Ja%aScript into an HTM# pa+e. Put a Ja%aScript into an HTM# pa+e The e!ample below shows how to use Ja%aScript to write te!t on a web pa+e3 E!ample >html@ >bo(&@ >script t&peB<te!t4)a%ascript<@ (ocument.write7<Hello Worl(9<8C >4script@ >4bo(&@ >4html@

Tr" it "oursel! ' The e!ample below shows how to a(( HTM# ta+s to the Ja%aScript3

E!ample >html@ >bo(&@ >script t&peB<te!t4)a%ascript<@ (ocument.write7<>h?@Hello Worl(9>4h?@<8C >4script@ >4bo(&@ >4html@

Tr" it "oursel! '

E!ample E!plaine( To insert a Ja%aScript into an HTM# pa+e0 we use the >script@ ta+. Insi(e the >script@ ta+ we use the t&pe attribute to (efine the scriptin+ lan+ua+e. So0 the >script t&peB<te!t4)a%ascript<@ an( >4script@ tells where the Ja%aScript starts an( en(s3 >html@ >bo(&@ >script t&peB<te!t4)a%ascript<@ ... >4script@ >4bo(&@ >4html@ The document(#rite comman( is a stan(ar( Ja%aScript comman( for writin+ output to a pa+e. & enterin+ the (ocument.write comman( between the >script@ an( >4script@ ta+s0 the browser will reco+niDe it as a Ja%aScript comman( an( e!ecute the co(e line. In this case the browser will write Hello Worl(9 to the pa+e3 >html@ >bo(&@ >script t&peB<te!t4)a%ascript<@ (ocument.write7<Hello Worl(9<8C >4script@ >4bo(&@ >4html@

)ote* If we ha( not entere( the >script@ ta+0 the browser woul( ha%e treate( the (ocument.write7<Hello Worl(9<8 comman( as pure te!t0 an( )ust write the entire line on the pa+e. Tr& it &ourself How to Han(le Simple rowsers rowsers that (o not support Ja%aScript0 will (ispla& Ja%aScript as pa+e content. To pre%ent them from (oin+ this0 an( as a part of the Ja%aScript stan(ar(0 the HTM# comment ta+ shoul( be use( to <hi(e< the Ja%aScript. Just a(( an HTM# comment ta+ >9:: before the first Ja%aScript statement0 an( a ::@ 7en( of comment8 after the last Ja%aScript statement0 li$e this3 >html@ >bo(&@ >script t&peB<te!t4)a%ascript<@ >9:: (ocument.write7<Hello Worl(9<8C 44::@ >4script@ >4bo(&@ >4html@ The two forwar( slashes at the en( of comment line 7448 is the Ja%aScript comment s&mbol. This pre%ents Ja%aScript from e!ecutin+ the ::@ ta+. Ja%aScript Where To - Pre%ious .e!t Chapter /

Ja%aScripts can be put in the bo(& an( in the hea( sections of an HTM# pa+e. Where to Put the Ja%aScript Ja%aScripts in a pa+e will be e!ecute( imme(iatel& while the pa+e loa(s into the browser. This is not alwa&s what we want. Sometimes we want to e!ecute a script when a pa+e loa(s0 or at a later e%ent0 such as when a user clic$s a button. When this is the case we put the script insi(e a function0 &ou will learn about functions in a later chapter. Scripts in >hea(@ Scripts to be e!ecute( when the& are calle(0 or when an e%ent is tri++ere(0 are place( in functions.

Put &our functions in the hea( section0 this wa& the& are all in one place0 an( the& (o not interfere with pa+e content. E!ample >html@ >hea(@ >script t&peB<te!t4)a%ascript<@ function messa+e78 E alert7<This alert bo! was calle( with the onloa( e%ent<8C F >4script@ >4hea(@ >bo(& onloa(B<messa+e78<@ >4bo(&@ >4html@

Tr" it "oursel! ' Scripts in >bo(&@ If &ou (onAt want &our script to be place( insi(e a function0 or if &our script shoul( write pa+e content0 it shoul( be place( in the bo(& section. E!ample >html@ >hea(@ >4hea(@ >bo(&@ >script t&peB<te!t4)a%ascript<@ (ocument.write7<This messa+e is written b& Ja%aScript<8C >4script@ >4bo(&@ >4html@

Tr" it "oursel! ' Scripts in >hea(@ an( >bo(&@

1ou can place an unlimite( number of scripts in &our (ocument0 so &ou can ha%e scripts in both the bo(& an( the hea( section. E!ample >html@ >hea(@ >script t&peB<te!t4)a%ascript<@ function messa+e78 E alert7<This alert bo! was calle( with the onloa( e%ent<8C F >4script@ >4hea(@ >bo(& onloa(B<messa+e78<@ >script t&peB<te!t4)a%ascript<@ (ocument.write7<This messa+e is written b& Ja%aScript<8C >4script@ >4bo(&@ >4html@

Tr" it "oursel! '

Gsin+ an E!ternal Ja%aScript If &ou want to run the same Ja%aScript on se%eral pa+es0 without ha%in+ to write the same script on e%er& pa+e0 &ou can write a Ja%aScript in an e!ternal file. Sa%e the e!ternal Ja%aScript file with a .)s file e!tension. )ote* The e!ternal script cannot contain the >script@>4script@ ta+s9 To use the e!ternal script0 point to the .)s file in the <src< attribute of the >script@ ta+3 E!ample >html@ >hea(@ >script t&peB<te!t4)a%ascript< srcB<!!!.)s<@>4script@

>4hea(@ >bo(&@ >4bo(&@ >4html@ Ja%aScript Statements - Pre%ious .e!t Chapter /

Ja%aScript is a seHuence of statements to be e!ecute( b& the browser. Ja%aScript is Case Sensiti%e Gnli$e HTM#0 Ja%aScript is case sensiti%e : therefore watch &our capitaliDation closel& when &ou write Ja%aScript statements0 create or call %ariables0 ob)ects an( functions. Ja%aScript Statements , Ja%aScript statement is a comman( to a browser. The purpose of the comman( is to tell the browser what to (o. This Ja%aScript statement tells the browser to write <Hello =oll&< to the web pa+e3 (ocument.write7<Hello =oll&<8C It is normal to a(( a semicolon at the en( of each e!ecutable statement. Most people thin$ this is a +oo( pro+rammin+ practice0 an( most often &ou will see this in Ja%aScript e!amples on the web. The semicolon is optional 7accor(in+ to the Ja%aScript stan(ar(80 an( the browser is suppose( to interpret the en( of the line as the en( of the statement. ecause of this &ou will often see e!amples without the semicolon at the en(. )ote* Gsin+ semicolons ma$es it possible to write multiple statements on one line. Ja%aScript Co(e Ja%aScript co(e 7or )ust Ja%aScript8 is a seHuence of Ja%aScript statements. Each statement is e!ecute( b& the browser in the seHuence the& are written. This e!ample will write a hea(in+ an( two para+raphs to a web pa+e3 E!ample

>script t&peB<te!t4)a%ascript<@ (ocument.write7<>h?@This is a hea(in+>4h?@<8C (ocument.write7<>p@This is a para+raph.>4p@<8C (ocument.write7<>p@This is another para+raph.>4p@<8C >4script@

Tr" it "oursel! '

Ja%aScript loc$s Ja%aScript statements can be +roupe( to+ether in bloc$s. loc$s start with a left curl& brac$et E0 an( en(s with a ri+ht curl& brac$et F. The purpose of a bloc$ is to ma$e the seHuence of statements e!ecute to+ether. This e!ample will write a hea(in+ an( two para+raphs to a web pa+e3 E!ample >script t&peB<te!t4)a%ascript<@ E (ocument.write7<>h?@This is a hea(in+>4h?@<8C (ocument.write7<>p@This is a para+raph.>4p@<8C (ocument.write7<>p@This is another para+raph.>4p@<8C F >4script@ Ja%aScript Comments - Pre%ious .e!t Chapter /

Ja%aScript comments can be use( to ma$e the co(e more rea(able. Ja%aScript Comments Comments can be a((e( to e!plain the Ja%aScript0 or to ma$e the co(e more rea(able. Sin+le line comments start with 44. The followin+ e!ample uses sin+le line comments to e!plain the co(e3

E!ample >script t&peB<te!t4)a%ascript<@ 44 Write a hea(in+ (ocument.write7<>h?@This is a hea(in+>4h?@<8C 44 Write two para+raphs3 (ocument.write7<>p@This is a para+raph.>4p@<8C (ocument.write7<>p@This is another para+raph.>4p@<8C >4script@

Tr" it "oursel! '

Ja%aScript Multi:#ine Comments Multi line comments start with 4I an( en( with I4. The followin+ e!ample uses a multi line comment to e!plain the co(e3 E!ample >script t&peB<te!t4)a%ascript<@ 4I The co(e below will write one hea(in+ an( two para+raphs I4 (ocument.write7<>h?@This is a hea(in+>4h?@<8C (ocument.write7<>p@This is a para+raph.>4p@<8C (ocument.write7<>p@This is another para+raph.>4p@<8C >4script@

Tr" it "oursel! '

Gsin+ Comments to Pre%ent E!ecution In the followin+ e!ample the comment is use( to pre%ent the e!ecution of a sin+le co(e line 7can be suitable for (ebu++in+83

E!ample >script t&peB<te!t4)a%ascript<@ 44(ocument.write7<>h?@This is a hea(in+>4h?@<8C (ocument.write7<>p@This is a para+raph.>4p@<8C (ocument.write7<>p@This is another para+raph.>4p@<8C >4script@

Tr" it "oursel! ' In the followin+ e!ample the comment is use( to pre%ent the e!ecution of a co(e bloc$ 7can be suitable for (ebu++in+83 E!ample >script t&peB<te!t4)a%ascript<@ 4I (ocument.write7<>h?@This is a hea(in+>4h?@<8C (ocument.write7<>p@This is a para+raph.>4p@<8C (ocument.write7<>p@This is another para+raph.>4p@<8C I4 >4script@

Tr" it "oursel! '

Gsin+ Comments at the En( of a #ine In the followin+ e!ample the comment is place( at the en( of a co(e line3 E!ample >script t&peB<te!t4)a%ascript<@ (ocument.write7<Hello<8C 44 Write <Hello< (ocument.write7< =oll&9<8C 44 Write < =oll&9< >4script@ Ja%aScript Variables - Pre%ious .e!t Chapter /

Variables are <containers< for storin+ information. =o 1ou *emember ,l+ebra "rom School6 =o &ou remember al+ebra from school6 !BJ0 &BK0 DB!;& =o &ou remember that a letter 7li$e !8 coul( be use( to hol( a %alue 7li$e J80 an( that &ou coul( use the information abo%e to calculate the %alue of D to be ??6 These letters are calle( variables0 an( %ariables can be use( to hol( %alues 7!BJ8 or e!pressions 7DB!;&8. Ja%aScript Variables ,s with al+ebra0 Ja%aScript %ariables are use( to hol( %alues or e!pressions. , %ariable can ha%e a short name0 li$e !0 or a more (escripti%e name0 li$e carname. *ules for Ja%aScript %ariable names3

Variable names are case sensiti%e 7& an( 1 are two (ifferent %ariables8 Variable names must be+in with a letter or the un(erscore character

)ote* ecause Ja%aScript is case:sensiti%e0 %ariable names are case:sensiti%e. E!ample , %ariableAs %alue can chan+e (urin+ the e!ecution of a script. 1ou can refer to a %ariable b& its name to (ispla& or chan+e its %alue. This e!ample will show &ou how =eclarin+ 7Creatin+8 Ja%aScript Variables Creatin+ %ariables in Ja%aScript is most often referre( to as <(eclarin+< %ariables. 1ou can (eclare Ja%aScript %ariables with the var $e&wor(3 %ar !C %ar carnameC ,fter the (eclaration shown abo%e0 the %ariables are empt& 7the& ha%e no %alues &et8. Howe%er0 &ou can also assi+n %alues to the %ariables when &ou (eclare them3

%ar !BJC %ar carnameB<Vol%o<C ,fter the e!ecution of the statements abo%e0 the %ariable x will hol( the %alue +0 an( carname will hol( the %alue ,olvo. )ote* When &ou assi+n a te!t %alue to a %ariable0 use Huotes aroun( the %alue. ,ssi+nin+ Values to Gn(eclare( Ja%aScript Variables If &ou assi+n %alues to %ariables that ha%e not &et been (eclare(0 the %ariables will automaticall& be (eclare(. These statements3 !BJC carnameB<Vol%o<C ha%e the same effect as3 %ar !BJC %ar carnameB<Vol%o<C

*e(eclarin+ Ja%aScript Variables If &ou re(eclare a Ja%aScript %ariable0 it will not lose its ori+inal %alue. %ar !BJC %ar !C ,fter the e!ecution of the statements abo%e0 the %ariable ! will still ha%e the %alue of J. The %alue of ! is not reset 7or cleare(8 when &ou re(eclare it. Ja%aScript ,rithmetic ,s with al+ebra0 &ou can (o arithmetic operations with Ja%aScript %ariables3 &B!:JC DB&;JC 1ou will learn more about the operators that can be use( in the ne!t chapter of this tutorial. Ja%aScript Operators

- Pre%ious B is use( to assi+n %alues. ; is use( to a(( %alues.

.e!t Chapter /

The assi+nment operator - is use( to assi+n %alues to Ja%aScript %ariables. The arithmetic operator ; is use( to a(( %alues to+ether. &BJC DBLC !B&;DC The %alue of !0 after the e!ecution of the statements abo%e is M. Ja%aScript ,rithmetic Operators ,rithmetic operators are use( to perform arithmetic between %ariables an(4or %alues. 'i%en that "-+0 the table below e!plains the arithmetic operators3 Operator ; : I 4 P ;; :: .escription ,((ition Subtraction Multiplication =i%ision Mo(ulus 7(i%ision remain(er8 Increment =ecrement Example !B&;L !B&:L !B&IL !B&4L !B&PL !B;;& !B::& esult !BM !BN !B?O !BL.J !B? !BK !BQ

Ja%aScript ,ssi+nment Operators ,ssi+nment operators are use( to assi+n %alues to Ja%aScript %ariables. 'i%en that x-/0 an( "-+0 the table below e!plains the assi+nment operators3

Operator B ;B :B IB 4B PB

Example !B& !;B& !:B& !IB& !4B& !PB&

Same As

esult !BJ

!B!;& !B!:& !B!I& !B!4& !B!P&

!B?J !BJ !BJO !BL !BO

The ; Operator Gse( on Strin+s The ; operator can also be use( to a(( strin+ %ariables or te!t %alues to+ether. To a(( two or more strin+ %ariables to+ether0 use the ; operator. t!t?B<What a %er&<C t!tLB<nice (a&<C t!tNBt!t?;t!tLC ,fter the e!ecution of the statements abo%e0 the %ariable t!tN contains <What a %er&nice (a&<. To a(( a space between the two strin+s0 insert a space into one of the strin+s3 t!t?B<What a %er& <C t!tLB<nice (a&<C t!tNBt!t?;t!tLC or insert a space into the e!pression3 t!t?B<What a %er&<C t!tLB<nice (a&<C t!tNBt!t?;< <;t!tLC ,fter the e!ecution of the statements abo%e0 the %ariable t!tN contains3 <What a %er& nice (a&< ,((in+ Strin+s an( .umbers

The rule is3 I! "ou add a number and a string1 t$e result #ill be a string2 E!ample !BJ;JC (ocument.write7!8C !B<J<;<J<C (ocument.write7!8C !BJ;<J<C (ocument.write7!8C !B<J<;JC (ocument.write7!8C Ja%aScript Comparison an( #o+ical Operators - Pre%ious .e!t Chapter /

Comparison an( #o+ical operators are use( to test for true or false. Comparison Operators Comparison operators are use( in lo+ical statements to (etermine eHualit& or (ifference between %ariables or %alues. 'i%en that x-+0 the table below e!plains the comparison operators3 Operator BB BBB .escription is eHual to is e!actl& eHual to 7%alue an( t&pe8 Example !BBR is false !BBBJ is true !BBB<J< is false !9BR is true !@R is false !>R is true !@BR is false

9B @ > @B

is not eHual is +reater than is less than is +reater than or eHual to

>B

is less than or eHual to

!>BR is true

How Can it be Gse( Comparison operators can be use( in con(itional statements to compare %alues an( ta$e action (epen(in+ on the result3 if 7a+e>?R8 (ocument.write7<Too &oun+<8C 1ou will learn more about the use of con(itional statements in the ne!t chapter of this tutorial. #o+ical Operators #o+ical operators are use( to (etermine the lo+ic between %ariables or %alues. 'i%en that x-3 and "-40 the table below e!plains the lo+ical operators3 Operator SS TT 9 .escription an( or not Example 7! > ?O SS & @ ?8 is true 7!BBJ TT &BBJ8 is false 97!BB&8 is true

Con(itional Operator Ja%aScript also contains a con(itional operator that assi+ns a %alue to a %ariable base( on some con(ition. S&nta! %ariablenameB7con(ition86%alue?3%alueL E!ample +reetin+B7%isitorBB<P*ES<86<=ear Presi(ent <3<=ear <C If the %ariable visitor has the %alue of <P*ES<0 then the %ariable greeting will be assi+ne( the %alue <=ear Presi(ent < else it will be assi+ne( <=ear<.

Ja%aScript If...Else Statements - Pre%ious .e!t Chapter /

Con(itional statements are use( to perform (ifferent actions base( on (ifferent con(itions. Con(itional Statements Ver& often when &ou write co(e0 &ou want to perform (ifferent actions for (ifferent (ecisions. 1ou can use con(itional statements in &our co(e to (o this. In Ja%aScript we ha%e the followin+ con(itional statements3

i! statement : use this statement to e!ecute some co(e onl& if a specifie( con(ition is true i!(((else statement : use this statement to e!ecute some co(e if the con(ition is true an( another co(e if the con(ition is false i!(((else i!((((else statement : use this statement to select one of man& bloc$s of co(e to be e!ecute( s#itc$ statement : use this statement to select one of man& bloc$s of co(e to be e!ecute(

If Statement Gse the if statement to e!ecute some co(e onl& if a specifie( con(ition is true. S&nta! if 7condition8 E code to be executed if condition is true F .ote that if is written in lowercase letters. Gsin+ uppercase letters 7I"8 will +enerate a Ja%aScript error9 E!ample >script t&peB<te!t4)a%ascript<@ 44Write a <'oo( mornin+< +reetin+ if 44the time is less than ?O

%ar (Bnew =ate78C %ar timeB(.+etHours78C if 7time>?O8 E (ocument.write7<>b@'oo( mornin+>4b@<8C F >4script@

Tr" it "oursel! ' .otice that there is no ..else.. in this s&nta!. 1ou tell the browser to e!ecute some co(e onl" i! t$e speci!ied condition is true. If...else Statement Gse the if....else statement to e!ecute some co(e if a con(ition is true an( another co(e if the con(ition is not true. S&nta! if 7condition8 E code to be executed if condition is true F else E code to be executed if condition is not true F

E!ample >script t&peB<te!t4)a%ascript<@ 44If the time is less than ?O0 &ou will +et a <'oo( mornin+< +reetin+. 44Otherwise &ou will +et a <'oo( (a&< +reetin+. %ar ( B new =ate78C %ar time B (.+etHours78C if 7time > ?O8

E (ocument.write7<'oo( mornin+9<8C F else E (ocument.write7<'oo( (a&9<8C F >4script@

Tr" it "oursel! '

If...else if...else Statement Gse the if....else if...else statement to select one of se%eral bloc$s of co(e to be e!ecute(. S&nta! if 7condition18 E code to be executed if condition1 is true F else if 7condition28 E code to be executed if condition2 is true F else E code to be executed if condition1 and condition2 are not true F

E!ample >script t&peB<te!t4)a%ascript<@ %ar ( B new =ate78 %ar time B (.+etHours78 if 7time>?O8 E (ocument.write7<>b@'oo( mornin+>4b@<8C

F else if 7time@?O SS time>?K8 E (ocument.write7<>b@'oo( (a&>4b@<8C F else E (ocument.write7<>b@Hello Worl(9>4b@<8C F >4script@

Tr" it "oursel! ' Ja%aScript Switch Statement - Pre%ious .e!t Chapter /

Con(itional statements are use( to perform (ifferent actions base( on (ifferent con(itions. The Ja%aScript Switch Statement Gse the switch statement to select one of man& bloc$s of co(e to be e!ecute(. S&nta! switch7n8 E case ?3 execute code block 1 brea$C case L3 execute code block 2 brea$C (efault3 code to be executed if n is different from case 1 and 2 F This is how it wor$s3 "irst we ha%e a sin+le e!pression n 7most often a %ariable80 that is e%aluate( once. The %alue of the e!pression is then compare( with the %alues for each case in the structure. If there is a match0 the bloc$ of co(e associate( with that case is e!ecute(. Gse brea& to pre%ent the co(e from runnin+ into the ne!t case automaticall&.

E!ample >script t&peB<te!t4)a%ascript<@ 441ou will recei%e a (ifferent +reetin+ base( 44on what (a& it is. .ote that Sun(a&BO0 44Mon(a&B?0 Tues(a&BL0 etc. %ar (Bnew =ate78C the=a&B(.+et=a&78C switch 7the=a&8 E case J3 (ocument.write7<"inall& "ri(a&<8C brea$C case K3 (ocument.write7<Super Satur(a&<8C brea$C case O3 (ocument.write7<Sleep& Sun(a&<8C brea$C (efault3 (ocument.write7<IAm loo$in+ forwar( to this wee$en(9<8C F >4script@ Ja%aScript Popup o!es - Pre%ious .e!t Chapter /

Ja%aScript has three $in( of popup bo!es3 ,lert bo!0 Confirm bo!0 an( Prompt bo!. ,lert o! ,n alert bo! is often use( if &ou want to ma$e sure information comes throu+h to the user. When an alert bo! pops up0 the user will ha%e to clic$ <O2< to procee(. S"ntax alert7<somete!t<8C

E!ample >html@ >hea(@ >script t&peB<te!t4)a%ascript<@ function showUalert78 E alert7<I am an alert bo!9<8C F >4script@ >4hea(@ >bo(&@ >input t&peB<button< onclic$B<showUalert78< %alueB<Show alert bo!< 4@ >4bo(&@ >4html@

Tr" it "oursel! '

Confirm o! , confirm bo! is often use( if &ou want the user to %erif& or accept somethin+. When a confirm bo! pops up0 the user will ha%e to clic$ either <O2< or <Cancel< to procee(. If the user clic$s <O2<0 the bo! returns true. If the user clic$s <Cancel<0 the bo! returns false. S"ntax confirm7<somete!t<8C

E!ample >html@ >hea(@ >script t&peB<te!t4)a%ascript<@ function showUconfirm78 E

%ar rBconfirm7<Press a button<8C if 7rBBtrue8 E alert7<1ou presse( O29<8C F else E alert7<1ou presse( Cancel9<8C F F >4script@ >4hea(@ >bo(&@ >input t&peB<button< onclic$B<showUconfirm78< %alueB<Show confirm bo!< 4@ >4bo(&@ >4html@ Ja%aScript "unctions - Pre%ious .e!t Chapter /

, function will be e!ecute( b& an e%ent or b& a call to the function. Ja%aScript "unctions To $eep the browser from e!ecutin+ a script when the pa+e loa(s0 &ou can put &our script into a function. , function contains co(e that will be e!ecute( b& an e%ent or b& a call to the function. 1ou ma& call a function from an&where within a pa+e 7or e%en from other pa+es if the function is embe((e( in an e!ternal .)s file8. "unctions can be (efine( both in the >hea(@ an( in the >bo(&@ section of a (ocument. Howe%er0 to assure that a function is rea(4loa(e( b& the browser before it is calle(0 it coul( be wise to put functions in the >hea(@ section. How to =efine a "unction S&nta!

function functionname7var1,var2,...,varX8 E some code F The parameters %ar?0 %arL0 etc. are %ariables or %alues passe( into the function. The E an( the F (efines the start an( en( of the function. )ote* , function with no parameters must inclu(e the parentheses 78 after the function name. )ote* =o not for+et about the importance of capitals in Ja%aScript9 The wor( function must be written in lowercase letters0 otherwise a Ja%aScript error occurs9 ,lso note that &ou must call a function with the e!act same capitals as in the function name. Ja%aScript "unction E!ample E!ample >html@ >hea(@ >script t&peB<te!t4)a%ascript<@ function (ispla&messa+e78 E alert7<Hello Worl(9<8C F >4script@ >4hea(@ >bo(&@ >form@ >input t&peB<button< %alueB<Clic$ me9< onclic$B<(ispla&messa+e78< 4@ >4form@ >4bo(&@ >4html@

Tr" it "oursel! ' If the line3 alert7<Hello worl(99<8 in the e!ample abo%e ha( not been put within a function0 it woul( ha%e been e!ecute( as soon as the pa+e was loa(e(. .ow0 the script is not e!ecute( before a user hits the input button. The function (ispla&messa+e78 will be e!ecute( if the input button is clic$e(. 1ou will learn more about Ja%aScript e%ents in the JS E%ents chapter.

The return Statement The return statement is use( to specif& the %alue that is returne( from the function. So0 functions that are +oin+ to return a %alue must use the return statement. The e!ample below returns the pro(uct of two numbers 7a an( b83 E!ample >html@ >hea(@ >script t&peB<te!t4)a%ascript<@ function pro(uct7a0b8 E return aIbC F >4script@ >4hea(@ >bo(&@ >script t&peB<te!t4)a%ascript<@ (ocument.write7pro(uct7Q0N88C >4script@ >4bo(&@ >4html@

Tr" it "oursel! ' Ja%aScript "or #oop - Pre%ious .e!t Chapter /

#oops e!ecute a bloc$ of co(e a specifie( number of times0 or while a specifie( con(ition is true. Ja%aScript #oops Often when &ou write co(e0 &ou want the same bloc$ of co(e to run o%er an( o%er a+ain in a row. Instea( of a((in+ se%eral almost eHual lines in a script we can use loops to perform a tas$ li$e this. In Ja%aScript0 there are two (ifferent $in( of loops3

!or : loops throu+h a bloc$ of co(e a specifie( number of times #$ile : loops throu+h a bloc$ of co(e while a specifie( con(ition is true

The for #oop The for loop is use( when &ou $now in a(%ance how man& times the script shoul( run. S"ntax for 7%arBstart%alueC%ar>Ben(%alueC%arB%ar;increment8 E code to be executed F Example The e!ample below (efines a loop that starts with iBO. The loop will continue to run as lon+ as i is less than0 or eHual to J. i will increase b& ? each time the loop runs. )ote* The increment parameter coul( also be ne+ati%e0 an( the >B coul( be an& comparin+ statement. E!ample >html@ >bo(&@ >script t&peB<te!t4)a%ascript<@ %ar iBOC for 7iBOCi>BJCi;;8 E (ocument.write7<The number is < ; i8C (ocument.write7<>br 4@<8C F >4script@ >4bo(&@ >4html@

Tr" it "oursel! '

The while loop

The while loop will be e!plaine( in the ne!t chapter. Ja%aScript While #oop - Pre%ious .e!t Chapter /

#oops e!ecute a bloc$ of co(e a specifie( number of times0 or while a specifie( con(ition is true. The while #oop The while loop loops throu+h a bloc$ of co(e while a specifie( con(ition is true. S&nta! while 7%ar>Ben(%alue8 E code to be executed F )ote* The >B coul( be an& comparin+ operator. E!ample The e!ample below (efines a loop that starts with iBO. The loop will continue to run as lon+ as i is less than0 or eHual to J. i will increase b& ? each time the loop runs3 E!ample >html@ >bo(&@ >script t&peB<te!t4)a%ascript<@ %ar iBOC while 7i>BJ8 E (ocument.write7<The number is < ; i8C (ocument.write7<>br 4@<8C i;;C F >4script@ >4bo(&@ >4html@

Tr" it "oursel! '

The (o...while #oop The (o...while loop is a %ariant of the while loop. This loop will e!ecute the bloc$ of co(e O.CE0 an( then it will repeat the loop as lon+ as the specifie( con(ition is true. S&nta! (o E code to be executed F while 7%ar>Ben(%alue8C E!ample The e!ample below uses a (o...while loop. The (o...while loop will alwa&s be e!ecute( at least once0 e%en if the con(ition is false0 because the statements are e!ecute( before the con(ition is teste(3 E!ample >html@ >bo(&@ >script t&peB<te!t4)a%ascript<@ %ar iBOC (o E (ocument.write7<The number is < ; i8C (ocument.write7<>br 4@<8C i;;C F while 7i>BJ8C >4script@ >4bo(&@ >4html@

Tr" it "oursel! ' The brea$ Statement The brea$ statement will brea$ the loop an( continue e!ecutin+ the co(e that follows after the loop 7if an&8.

E!ample >html@ >bo(&@ >script t&peB<te!t4)a%ascript<@ %ar iBOC for 7iBOCi>B?OCi;;8 E if 7iBBN8 E brea$C F (ocument.write7<The number is < ; i8C (ocument.write7<>br 4@<8C F >4script@ >4bo(&@ >4html@

Tr" it "oursel! '

The continue Statement The continue statement will brea$ the current loop an( continue with the ne!t %alue. E!ample >html@ >bo(&@ >script t&peB<te!t4)a%ascript<@ %ar iBO for 7iBOCi>B?OCi;;8 E if 7iBBN8 E continueC F (ocument.write7<The number is < ; i8C (ocument.write7<>br 4@<8C F

>4script@ >4bo(&@ >4html@ Ja%aScript "or...In Statement - Pre%ious Ja%aScript "or...In Statement The for...in statement loops throu+h the elements of an arra& or throu+h the properties of an ob)ect. S&nta! for 7variable in object8 E code to be executed F )ote* The co(e in the bo(& of the for...in loop is e!ecute( once for each element4propert&. )ote* The %ariable ar+ument can be a name( %ariable0 an arra& element0 or a propert& of an ob)ect. E!ample Gse the for...in statement to loop throu+h an arra&3 E!ample >html@ >bo(&@ >script t&peB<te!t4)a%ascript<@ %ar !C %ar m&cars B new ,rra&78C m&carsVOW B <Saab<C m&carsV?W B <Vol%o<C m&carsVLW B < MW<C for 7! in m&cars8 E (ocument.write7m&carsV!W ; <>br 4@<8C .e!t Chapter /

F >4script@ >4bo(&@ >4html@ Ja%aScript E%ents - Pre%ious .e!t Chapter /

E%ents are actions that can be (etecte( b& Ja%aScript. E%ents & usin+ Ja%aScript0 we ha%e the abilit& to create (&namic web pa+es. E%ents are actions that can be (etecte( b& Ja%aScript. E%er& element on a web pa+e has certain e%ents which can tri++er a Ja%aScript. "or e!ample0 we can use the onClic$ e%ent of a button element to in(icate that a function will run when a user clic$s on the button. We (efine the e%ents in the HTM# ta+s. E!amples of e%ents3

, mouse clic$ , web pa+e or an ima+e loa(in+ Mousin+ o%er a hot spot on the web pa+e Selectin+ an input fiel( in an HTM# form Submittin+ an HTM# form , $e&stro$e

)ote* E%ents are normall& use( in combination with functions0 an( the function will not be e!ecute( before the e%ent occurs9 "or a complete reference of the e%ents reco+niDe( b& Ja%aScript0 +o to our complete Ja%aScript reference. on#oa( an( onGnloa( The on#oa( an( onGnloa( e%ents are tri++ere( when the user enters or lea%es the pa+e.

The on#oa( e%ent is often use( to chec$ the %isitorAs browser t&pe an( browser %ersion0 an( loa( the proper %ersion of the web pa+e base( on the information. oth the on#oa( an( onGnloa( e%ents are also often use( to (eal with coo$ies that shoul( be set when a user enters or lea%es a pa+e. "or e!ample0 &ou coul( ha%e a popup as$in+ for the userAs name upon his first arri%al to &our pa+e. The name is then store( in a coo$ie. .e!t time the %isitor arri%es at &our pa+e0 &ou coul( ha%e another popup sa&in+ somethin+ li$e3 <Welcome John =oe9<. on"ocus0 on lur an( onChan+e The on"ocus0 on lur an( onChan+e e%ents are often use( in combination with %ali(ation of form fiel(s. elow is an e!ample of how to use the onChan+e e%ent. The chec$Email78 function will be calle( whene%er the user chan+es the content of the fiel(3 >input t&peB<te!t< siDeB<NO< i(B<email< onchan+eB<chec$Email78<@

onSubmit The onSubmit e%ent is use( to %ali(ate ,## form fiel(s before submittin+ it. elow is an e!ample of how to use the onSubmit e%ent. The chec$"orm78 function will be calle( when the user clic$s the submit button in the form. If the fiel( %alues are not accepte(0 the submit shoul( be cancelle(. The function chec$"orm78 returns either true or false. If it returns true the form will be submitte(0 otherwise the submit will be cancelle(3 >form metho(B<post< actionB<!!!.htm< onsubmitB<return chec$"orm78<@

onMouseO%er an( onMouseOut onMouseO%er an( onMouseOut are often use( to create <animate(< buttons. elow is an e!ample of an onMouseO%er e%ent. ,n alert bo! appears when an onMouseO%er e%ent is (etecte(3 >a hrefB<http344www.wNschools.com< onmouseo%erB<alert7A,n onMouseO%er e%entA8Creturn false<@>im+ srcB<wNs.+if< altB<WNSchools< 4@>4a@ Ja%aScript Tr&...Catch Statement

- Pre%ious

.e!t Chapter /

The tr&...catch statement allows &ou to test a bloc$ of co(e for errors. Ja%aScript : Catchin+ Errors When browsin+ Web pa+es on the internet0 we all ha%e seen a Ja%aScript alert bo! tellin+ us there is a runtime error an( as$in+ <=o &ou wish to (ebu+6<. Error messa+e li$e this ma& be useful for (e%elopers but not for users. When users see errors0 the& often lea%e the Web pa+e. This chapter will teach &ou how to catch an( han(le Ja%aScript error messa+es0 so &ou (onAt lose &our au(ience. The tr&...catch Statement The tr&...catch statement allows &ou to test a bloc$ of co(e for errors. The tr& bloc$ contains the co(e to be run0 an( the catch bloc$ contains the co(e to be e!ecute( if an error occurs. S&nta! tr& E 44*un some co(e here F catch7err8 E 44Han(le errors here F .ote that tr&...catch is written in lowercase letters. Gsin+ uppercase letters will +enerate a Ja%aScript error9 E!amples The e!ample below is suppose( to alert <Welcome +uest9< when the button is clic$e(. Howe%er0 thereAs a t&po in the messa+e78 function. alert78 is misspelle( as a(((lert78. , Ja%aScript error occurs. The catch bloc$ catches the error an( e!ecutes a custom co(e to han(le it. The co(e (ispla&s a custom error messa+e informin+ the user what happene(3 E!ample >html@ >hea(@ >script t&peB<te!t4)a%ascript<@

%ar t!tB<<C function messa+e78 E tr& E a(((lert7<Welcome +uest9<8C F catch7err8 E t!tB<There was an error on this pa+e.XnXn<C t!t;B<Error (escription3 < ; err.(escription ; <XnXn<C t!t;B<Clic$ O2 to continue.XnXn<C alert7t!t8C F F >4script@ >4hea(@ >bo(&@ >input t&peB<button< %alueB<View messa+e< onclic$B<messa+e78< 4@ >4bo(&@ >4html@

Tr" it "oursel! ' The ne!t e!ample uses a confirm bo! to (ispla& a custom messa+e tellin+ users the& can clic$ O2 to continue %iewin+ the pa+e or clic$ Cancel to +o to the homepa+e. If the confirm metho( returns false0 the user clic$e( Cancel0 an( the co(e re(irects the user. If the confirm metho( returns true0 the co(e (oes nothin+3 E!ample >html@ >hea(@ >script t&peB<te!t4)a%ascript<@ %ar t!tB<<C function messa+e78 E tr& E a(((lert7<Welcome +uest9<8C

F catch7err8 E t!tB<There was an error on this pa+e.XnXn<C t!t;B<Clic$ O2 to continue %iewin+ this pa+e0Xn<C t!t;B<or Cancel to return to the home pa+e.XnXn<C if79confirm7t!t88 E (ocument.location.hrefB<http344www.wNschools.com4<C F F F >4script@ >4hea(@ >bo(&@ >input t&peB<button< %alueB<View messa+e< onclic$B<messa+e78< 4@ >4bo(&@ >4html@ Ja%aScript Throw Statement - Pre%ious .e!t Chapter /

The throw statement allows &ou to create an e!ception. The Throw Statement The throw statement allows &ou to create an e!ception. If &ou use this statement to+ether with the tr&...catch statement0 &ou can control pro+ram flow an( +enerate accurate error messa+es. S&nta! throw7e!ception8 The e!ception can be a strin+0 inte+er0 oolean or an ob)ect. .ote that throw is written in lowercase letters. Gsin+ uppercase letters will +enerate a Ja%aScript error9 E!ample

The e!ample below (etermines the %alue of a %ariable calle( !. If the %alue of ! is hi+her than ?O0 lower than O0 or not a number0 we are +oin+ to throw an error. The error is then cau+ht b& the catch ar+ument an( the proper error messa+e is (ispla&e(3 E!ample >html@ >bo(&@ >script t&peB<te!t4)a%ascript<@ %ar !Bprompt7<Enter a number between O an( ?O3<0<<8C tr& E if7!@?O8 E throw <Err?<C F else if7!>O8 E throw <ErrL<C F else if7is.a.7!88 E throw <ErrN<C F F catch7er8 E if7erBB<Err?<8 E alert7<Error9 The %alue is too hi+h<8C F if7erBB<ErrL<8 E alert7<Error9 The %alue is too low<8C F if7erBB<ErrN<8 E alert7<Error9 The %alue is not a number<8C F F >4script@ >4bo(&@ >4html@

Tr" it "oursel! ' Ja%aScript Special Characters - Pre%ious .e!t Chapter /

In Ja%aScript &ou can a(( special characters to a te!t strin+ b& usin+ the bac$slash si+n. Insert Special Characters The bac$slash 7X8 is use( to insert apostrophes0 new lines0 Huotes0 an( other special characters into a te!t strin+. #oo$ at the followin+ Ja%aScript co(e3 %ar t!tB<We are the so:calle( <Vi$in+s< from the north.<C (ocument.write7t!t8C In Ja%aScript0 a strin+ is starte( an( stoppe( with either sin+le or (ouble Huotes. This means that the strin+ abo%e will be choppe( to3 We are the so:calle( To sol%e this problem0 &ou must place a bac$slash 7X8 before each (ouble Huote in <Vi$in+<. This turns each (ouble Huote into a strin+ literal3 %ar t!tB<We are the so:calle( X<Vi$in+sX< from the north.<C (ocument.write7t!t8C Ja%aScript will now output the proper te!t strin+3 We are the so:calle( <Vi$in+s< from the north. Here is another e!ample3 (ocument.write 7<1ou XS I are sin+in+9<8C The e!ample abo%e will pro(uce the followin+ output3 1ou S I are sin+in+9 The table below lists other special characters that can be a((e( to a te!t strin+ with the bac$slash si+n3 5ode XA Outputs sin+le Huote

X< XS XX Xn Xr Xt Xb Xf

(ouble Huote ampersan( bac$slash new line carria+e return tab bac$space form fee(

- Pre%ious

.e!t Chapter /

Vous aimerez peut-être aussi