Você está na página 1de 118

JavaScript Introduction

Previous Next Chapter


JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as nternet !xplorer, "ire#ox, Chrome, $pera, and Sa#ari%

&hat 'ou Should (lread) *now


+e#ore )ou continue )ou should have a basic understanding o# the #ollowing,

-./0 and CSS

# )ou want to stud) these subjects #irst, #ind the tutorials on our -ome page%

&hat is JavaScript1

JavaScript was designed to add interactivit) to -./0 pages JavaScript is a scripting language ( scripting language is a lightweight programming language JavaScript is usuall) embedded directl) into -./0 pages JavaScript is an interpreted language 2means that scripts execute without preliminar) compilation3 !ver)one can use JavaScript without purchasing a license

(re Java and JavaScript the same1


N$4 Java and JavaScript are two completel) di##erent languages in both concept and design4 Java 2developed b) Sun /icros)stems3 is a power#ul and much more complex programming language 5 in the same categor) as C and C66%

&hat Can JavaScript do1



JavaScript gives HTML designers a programming tool - -./0 authors are normall) not programmers, but JavaScript is a scripting language with a ver) simple s)ntax4 (lmost an)one can put small 7snippets7 o# code into their -./0 pages JavaScript can react to events - ( JavaScript can be set to execute when something happens, like when a page has #inished loading or when a user clicks on an -./0 element JavaScript can read and write HTML elements - ( JavaScript can read and change the content o# an -./0 element JavaScript can be used to validate data - ( JavaScript can be used to validate #orm data be#ore it is submitted to a server% .his saves the server #rom extra processing JavaScript can be used to detect the visitor's browser 5 ( JavaScript can be used to detect the visitor8s browser, and 5 depending on the browser 5 load another page speci#icall) designed #or that browser JavaScript can be used to create cookies 5 ( JavaScript can be used to store and retrieve in#ormation on the visitor8s computer

JavaScript 9 !C/(Script
JavaScript is an implementation o# the !C/(Script language standard% !C/(5:;: is the o##icial JavaScript standard% JavaScript was invented b) +rendan !ich at Netscape 2with Navigator :%<3, and has appeared in all browsers since =>>;% .he o##icial standardi?ation was adopted b) the !C/( organi?ation 2an industr) standardi?ation association3 in =>>@% .he !C/( standard 2called !C/(Script5:;:3 was approved as an international S$ 2 S$A !C =;:;:3 standard in =>>B% .he development is still in progress%

Previous

Next Chapter

JavaScript How To
Previous
.he -./0 CscriptD tag is used to insert a JavaScript into an -./0 page%

Next Chapter

&riting to .he -./0 Eocument


.he example below writes a CpD element with current date in#ormation to the -./0 document,

!xample
<html> <body> <h1>My First Web Page</h1> <script type="text/javascript"> docume t!"rite#"<p>" $ %ate#& $ "</p>"&' </script> </body> </html>
Try it yoursel !

"ote# .r) to avoid using document%write23 in real li#e JavaScript code% .he entire -./0 page will be overwritten i# document%write23 is used inside a #unction, or a#ter the page is loaded% -owever, document%write23 is an eas) wa) to demonstrate JavaScript output in a tutorial%

Changing -./0 !lements


.he example below writes the current date into an existing CpD element,

!xample
<html> <body> <h1>My First Web Page</h1> <p id="demo"></p> <script type="text/javascript"> docume t!get(leme t)y*d#"demo"&!i </script> </body> </html>
Try it yoursel !

er+,M-=%ate#&'

"ote# .o manipulate -./0 elements JavaScript uses the E$/ method get$lement%yId&'% .his method accesses the element with the speci#ied id%

!xamples !xplained
.o insert a JavaScript into an -./0 page, use the CscriptD tag% nside the CscriptD tag use the t)pe attribute to de#ine the scripting language% .he CscriptD and CAscriptD tells where the JavaScript starts and ends,

<html> <body> <h1>My First Web Page</h1> <p id="demo">,his is a paragraph!</p> <script type="text/javascript"> !!! some .ava/cript code !!! </script> </body> </html>

.he lines between the CscriptD and CAscriptD contain the JavaScript and are executed b) the browser% n this case the browser will replace the content o# the -./0 element with id97demo7, with the current date,

<html> <body> <h1>My First Web Page</h1> <p id="demo">,his is a paragraph!</p> <script type="text/javascript"> docume t!get(leme t)y*d#"demo"&!i </script> </body> </html>
&ithout the CscriptD tag2s3, the browser will treat 7document%get!lement+) d27demo73%inner-./09Eate23F7 as pure text and just write it to the page,.r) it )oursel#

er+,M-=%ate#&'

Some +rowsers do Not Support JavaScript


+rowsers that do not support JavaScript, will displa) JavaScript as page content% .o prevent them #rom doing this, and as a part o# the JavaScript standard, the -./0 comment tag should be used to 7hide7 the JavaScript% Just add an -./0 comment tag C455 be#ore the #irst JavaScript statement, and a 55D 2end o# comment3 a#ter the last JavaScript statement, like this,

<html> <body> <script type="text/javascript"> <011 docume t!get(leme t)y*d#"demo"&!i //11> </script> </body> </html>

er+,M-=%ate#&'

.he two #orward slashes at the end o# comment line 2AA3 is the JavaScript comment s)mbol% .his prevents JavaScript #rom executing the 55D tag%

Previous

Next Chapter

JavaScript (here To
Previous Next Chapter
JavaScripts can be put in the Cbod)D and in the CheadD sections o# an -./0 page%

JavaScript in Cbod)D
.he example below writes the current date into an existing CpD element when the page loads,

!xample
<html> <body> <h1>My First Web Page</h1> <p id="demo"></p> <script type="text/javascript"> docume t!get(leme t)y*d#"demo"&!i </script> </body> </html>
Try it yoursel !

er+,M-=%ate#&'

Note that the JavaScript is placed at the bottom o# the page to make sure it is not executed be#ore the CpD element is created%

JavaScript "unctions and !vents


JavaScripts in an -./0 page will be executed when the page loads% .his is not alwa)s what we want% Sometimes we want to execute a JavaScript when an event occurs, such as when a user clicks a button% &hen this is the case we can put the script inside a unction% !vents are normall) used in combination with #unctions 2like calling a #unction when an event occurs3% 'ou will learn more about JavaScript #unctions and events in later chapters%

JavaScript in CheadD
.he example below calls a #unction when a button is clicked,

!xample
<html> <head> <script type="text/javascript"> 2u ctio display%ate#& 3 docume t!get(leme t)y*d#"demo"&!i 4 </script> </head> <body> <h1>My First Web Page</h1> <p id="demo"></p> <butto </body> </html>
Try it yoursel !

er+,M-=%ate#&'

type="butto " o clic5="display%ate#&">%isplay %ate</butto >

Scripts in CheadD and Cbod)D


'ou can place an unlimited number o# scripts in )our document, and )ou can have scripts in both the bod) and the head section at the same time% t is a common practice to put all #unctions in the head section, or at the bottom o# the page% .his wa) the) are all in one place and do not inter#ere with page content%

Gsing an !xternal JavaScript


JavaScript can also be placed in external #iles% !xternal JavaScript #iles o#ten contain code to be used on several di##erent web pages% !xternal JavaScript #iles have the #ile extension %js% "ote# !xternal script cannot contain the CscriptDCAscriptD tags4 .o use an external script, point to the %js #ile in the 7src7 attribute o# the CscriptD tag,

!xample

<html> <head> <script type="text/javascript" src="xxx!js"></script> </head> <body> </body> </html>


Try it yoursel !

"ote# Hemember to place the script exactl) where )ou normall) would write the script4

Previous

Next Chapter

JavaScript Statements
Previous
JavaScript is a seIuence o# statements to be executed b) the browser%

Next Chapter

JavaScript is Case Sensitive


Gnlike -./0, JavaScript is case sensitive 5 there#ore watch )our capitali?ation closel) when )ou write JavaScript statements, create or call variables, objects and #unctions%

JavaScript Statements
( JavaScript statement is a command to a browser% .he purpose o# the command is to tell the browser what to do% .his JavaScript statement tells the browser to write 7-ello Eoll)7 to the web page,

docume t!"rite#"+ello %olly"&'


t is normal to add a semicolon at the end o# each executable statement% /ost people think this is a good programming practice, and most o#ten )ou will see this in JavaScript examples on the web% .he semicolon is optional 2according to the JavaScript standard3, and the browser is supposed to interpret the end o# the line as the end o# the statement% +ecause o# this )ou will o#ten see examples without the semicolon at the end%

"ote# Gsing semicolons makes it possible to write multiple statements on one line%

JavaScript Code
JavaScript code 2or just JavaScript3 is a seIuence o# JavaScript statements% !ach statement is executed b) the browser in the seIuence the) are written% .his example will write a heading and two paragraphs to a web page,

!xample
<script type="text/javascript"> docume t!"rite#"<h1>,his is a headi g</h1>"&' docume t!"rite#"<p>,his is a paragraph!</p>"&' docume t!"rite#"<p>,his is a other paragraph!</p>"&' </script>
Try it yoursel !

JavaScript +locks
JavaScript statements can be grouped together in blocks% +locks start with a le#t curl) bracket J, and end with a right curl) bracket K% .he purpose o# a block is to make the seIuence o# statements execute together% .his example will write a heading and two paragraphs to a web page,

!xample
<script type="text/javascript"> 3 docume t!"rite#"<h1>,his is a headi g</h1>"&' docume t!"rite#"<p>,his is a paragraph!</p>"&' docume t!"rite#"<p>,his is a other paragraph!</p>"&' 4 </script>
Try it yoursel !

.he example above is not ver) use#ul% t just demonstrates the use o# a block% Normall) a block is used to group statements together in a #unction or in a condition 2where a group o# statements should be executed i# a condition is met3% 'ou will learn more about #unctions and conditions in later chapters%

Previous

Next Chapter

JavaScript )omments
Previous
JavaScript comments can be used to make the code more readable%

Next Chapter

JavaScript Comments
Comments can be added to explain the JavaScript, or to make the code more readable% Single line comments start with AA% .he #ollowing example uses single line comments to explain the code,

!xample
<script type="text/javascript"> // Write a headi g docume t!"rite#"<h1>,his is a headi g</h1>"&' // Write t"o paragraphs6 docume t!"rite#"<p>,his is a paragraph!</p>"&' docume t!"rite#"<p>,his is a other paragraph!</p>"&' </script>
Try it yoursel !

JavaScript /ulti50ine Comments


/ulti line comments start with AL and end with LA% .he #ollowing example uses a multi line comment to explain the code,

!xample
<script type="text/javascript"> /7 ,he code belo" "ill "rite o e headi g a d t"o paragraphs 7/ docume t!"rite#"<h1>,his is a headi g</h1>"&'

docume t!"rite#"<p>,his is a paragraph!</p>"&' docume t!"rite#"<p>,his is a other paragraph!</p>"&' </script>


Try it yoursel !

Gsing Comments to Prevent !xecution


n the #ollowing example the comment is used to prevent the execution o# a single code line 2can be suitable #or debugging3,

!xample
<script type="text/javascript"> //docume t!"rite#"<h1>,his is a headi g</h1>"&' docume t!"rite#"<p>,his is a paragraph!</p>"&' docume t!"rite#"<p>,his is a other paragraph!</p>"&' </script>
Try it yoursel !

n the #ollowing example the comment is used to prevent the execution o# a code block 2can be suitable #or debugging3,

!xample
<script type="text/javascript"> /7 docume t!"rite#"<h1>,his is a headi g</h1>"&' docume t!"rite#"<p>,his is a paragraph!</p>"&' docume t!"rite#"<p>,his is a other paragraph!</p>"&' 7/ </script>
Try it yoursel !

Gsing Comments at the !nd o# a 0ine


n the #ollowing example the comment is placed at the end o# a code line,

!xample
<script type="text/javascript"> docume t!"rite#"+ello"&' // Write "+ello" docume t!"rite#" %olly0"&' // Write " %olly0" </script>

Try it yoursel !

Previous

Next Chapter

JavaScript *ariables
Previous
Mariables are 7containers7 #or storing in#ormation%

Next Chapter

Eo 'ou Hemember (lgebra "rom School1


Eo )ou remember algebra #rom school1 x9N, )9;, ?9x6) Eo )ou remember that a letter 2like x3 could be used to hold a value 2like N3, and that )ou could use the in#ormation above to calculate the value o# ? to be ==1 .hese letters are called variables, and variables can be used to hold values 2x9N3 or expressions 2?9x6)3%

JavaScript Mariables
(s with algebra, JavaScript variables are used to hold values or expressions% ( variable can have a short name, like x, or a more descriptive name, like carname% Hules #or JavaScript variable names,

Mariable names are case sensitive 2) and ' are two di##erent variables3 Mariable names must begin with a letter or the underscore character

"ote# +ecause JavaScript is case5sensitive, variable names are case5sensitive%

!xample
( variable8s value can change during the execution o# a script% 'ou can re#er to a variable b) its name to displa) or change its value% .his example will show )ou how

Eeclaring 2Creating3 JavaScript Mariables


Creating variables in JavaScript is most o#ten re#erred to as 7declaring7 variables%

'ou declare JavaScript variables with the var ke)word,

var x' var car ame'


(#ter the declaration shown above, the variables are empt) 2the) have no values )et3% -owever, )ou can also assign values to the variables when )ou declare them,

var x=8' var car ame="9olvo"'


(#ter the execution o# the statements above, the variable + will hold the value ,, and carname will hold the value *olvo% "ote# &hen )ou assign a text value to a variable, use Iuotes around the value% "ote# # )ou redeclare a JavaScript variable, it will not lose its value%

0ocal JavaScript Mariables


( variable declared within a JavaScript #unction becomes L-).L and can onl) be accessed within that #unction% 2the variable has local scope3% 'ou can have local variables with the same name in di##erent #unctions, because local variables are onl) recogni?ed b) the #unction in which the) are declared% 0ocal variables are destro)ed when )ou exit the #unction% 'ou will learn more about #unctions in a later chapter o# this tutorial%

Olobal JavaScript Mariables


Mariables declared outside a #unction become /L-%.L, and all scripts and #unctions on the web page can access it% Olobal variables are destro)ed when )ou close the page% # )ou declare a variable, without using 7var7, the variable alwa)s becomes /L-%.L%

(ssigning Malues to Gndeclared JavaScript Mariables


# )ou assign values to variables that have not )et been declared, the variables will automaticall) be declared as global variables% .hese statements,

x=8' car ame="9olvo"'


will declare the variables x and carname as global variables 2i# the) don8t alread) exist3%

JavaScript (rithmetic
(s with algebra, )ou can do arithmetic operations with JavaScript variables,

y=x18' :=y$8'
'ou will learn more about the operators that can be used in the next chapter o# this tutorial%

Previous

Next Chapter

JavaScript -perators
Previous
9 is used to assign values% 6 is used to add values%

Next Chapter

.he assignment operator 0 is used to assign values to JavaScript variables% .he arithmetic operator 6 is used to add values together%

y=8' :=;' x=y$:'


.he value o# x, a#ter the execution o# the statements above, is @%

JavaScript (rithmetic $perators


(rithmetic operators are used to per#orm arithmetic between variables andAor values% Oiven that y0,, the table below explains the arithmetic operators, -perator 6 1escription (ddition $+ample x9)6: 2esult x9@ )9N

5 L A Q 66 55

Subtraction /ultiplication Eivision /odulus 2division remainder3 ncrement Eecrement

x9)5: x9)L: x9)A: x9)Q: x966) x9)66 x955) x9)55

x9P x9=< x9:%N x9= x9; x9N x9R x9N

)9N )9N )9N )9N )9; )9; )9R )9R

JavaScript (ssignment $perators


(ssignment operators are used to assign values to JavaScript variables% Oiven that +034 and y0,, the table below explains the assignment operators, -perator 9 69 59 L9 A9 Q9 $+ample x9) x69) x59) xL9) xA9) xQ9) x9x6) x9x5) x9xL) x9xA) x9xQ) Same .s 2esult x9N x9=N x9N x9N< x9: x9<

.he 6 $perator Gsed on Strings


.he 6 operator can also be used to add string variables or text values together% .o add two or more string variables together, use the 6 operator%

txt1="What a very"' txt;=" ice day"' txt<=txt1$txt;'


(#ter the execution o# the statements above, the variable txtP contains 7&hat a ver)nice da)7% .o add a space between the two strings, insert a space into one o# the strings,

txt1="What a very "' txt;=" ice day"' txt<=txt1$txt;'


or insert a space into the expression,

txt1="What a very"' txt;=" ice day"' txt<=txt1$" "$txt;'


(#ter the execution o# the statements above, the variable txtP contains, 7&hat a ver) nice da)7

(dding Strings and Numbers


.he rule is, I you add a number and a string5 the result will be a string6

!xample
x=8$8' docume t!"rite#x&' x="8"$"8"' docume t!"rite#x&' x=8$"8"' docume t!"rite#x&' x="8"$8' docume t!"rite#x&'
Try it yoursel !

Previous

Next Chapter

JavaScript )omparison and Logical -perators


Previous
Comparison and 0ogical operators are used to test #or true or #alse%

Next Chapter

Comparison $perators
Comparison operators are used in logical statements to determine eIualit) or di##erence between variables or values% Oiven that +0,, the table below explains the comparison operators, -perator 1escription $+ample

99 999 49 D C D9 C9

is eIual to is exactl) eIual to 2value and t)pe3 is not eIual is greater than is less than is greater than or eIual to is less than or eIual to

x99B is #alse x99N is true x999N is true x9997N7 is #alse x49B is true xDB is #alse xCB is true xD9B is #alse xC9B is true

-ow Can it be Gsed


Comparison operators can be used in conditional statements to compare values and take action depending on the result,

i2 #age<1=& docume t!"rite#",oo you g"&'


'ou will learn more about the use o# conditional statements in the next chapter o# this tutorial%

0ogical $perators
0ogical operators are used to determine the logic between variables or values% Oiven that +07 and y08, the table below explains the logical operators, -perator SS TT 4 1escription and or not $+ample 2x C =< SS ) D =3 is true 2x99N TT )99N3 is #alse 42x99)3 is true

Conditional $perator
JavaScript also contains a conditional operator that assigns a value to a variable based on some condition%

S)ntax
variable ame=#co ditio &>value16value;

!xample
greeti g=#visitor=="P?(/"&>"%ear Preside t "6"%ear "'
# the variable visitor has the value o# 7PH!S7, then the variable greeting will be assigned the value 7Eear President 7 else it will be assigned 7Eear7%

Previous

Next Chapter

JavaScript I 999$lse Statements


Previous Next Chapter
Conditional statements are used to per#orm di##erent actions based on di##erent conditions%

Conditional Statements
Mer) o#ten when )ou write code, )ou want to per#orm di##erent actions #or di##erent decisions% 'ou can use conditional statements in )our code to do this% n JavaScript we have the #ollowing conditional statements,

i statement 5 use this statement to execute some code onl) i# a speci#ied condition is true i 999else statement 5 use this statement to execute some code i# the condition is true and another code i# the condition is #alse i 999else i 9999else statement 5 use this statement to select one o# man) blocks o# code to be executed switch statement 5 use this statement to select one o# man) blocks o# code to be executed

# Statement
Gse the i# statement to execute some code onl) i# a speci#ied condition is true%

S)ntax
i2 #condition& 3 code to be executed if condition is true 4
Note that i# is written in lowercase letters% Gsing uppercase letters 2 "3 will generate a JavaScript error4

!xample
<script type="text/javascript"> //Write a "@ood mor i g" greeti g i2 //the time is less tha 1A var d= e" %ate#&' var time=d!get+ours#&' i2 #time<1A&

3 docume t!"rite#"<b>@ood mor i g</b>"&' 4 </script>


Try it yoursel !

Notice that there is no %%else%% in this s)ntax% 'ou tell the browser to execute some code only i the speci ied condition is true%

#%%%else Statement
Gse the i#%%%%else statement to execute some code i# a condition is true and another code i# the condition is not true%

S)ntax
i2 #condition& 3 code to be executed if condition is true 4 else 3 code to be executed if condition is not true 4

!xample
<script type="text/javascript"> //*2 the time is less tha 1AB you "ill get a "@ood mor i g" greeti g! //Cther"ise you "ill get a "@ood day" greeti g! var d = e" %ate#&' var time = d!get+ours#&' i2 #time < 1A& 3 docume t!"rite#"@ood mor i g0"&' 4 else 3 docume t!"rite#"@ood day0"&' 4 </script>
Try it yoursel !

#%%%else i#%%%else Statement


Gse the i#%%%%else i#%%%else statement to select one o# several blocks o# code to be executed%

S)ntax
i2 #condition1& 3 code to be executed if condition1 is true 4 else i2 #condition2& 3 code to be executed if condition2 is true 4 else 3 code to be executed if neither condition1 nor condition2 is true 4

!xample
<script type="text/javascript"> var d = e" %ate#& var time = d!get+ours#& i2 #time<1A& 3 docume t!"rite#"<b>@ood mor i g</b>"&' 4 else i2 #time>1A DD time<1E& 3 docume t!"rite#"<b>@ood day</b>"&' 4 else 3 docume t!"rite#"<b>+ello World0</b>"&' 4 </script>
Try it yoursel !

/ore !xamples
Handom link .his example demonstrates a link, when )ou click on the link it will take )ou to &PSchools%com $H to He#snesEata%no% .here is a N<Q chance #or each o# them%

Previous

Next Chapter

JavaScript Switch Statement


Previous Next Chapter
Conditional statements are used to per#orm di##erent actions based on di##erent conditions%

.he JavaScript Switch Statement


Gse the switch statement to select one o# man) blocks o# code to be executed%

S)ntax
s"itch# & 3 case 16 execute code block 1 brea5' case ;6 execute code block 2 brea5' de2ault6 code to be executed if n is different from case 1 and 2 4
.his is how it works, "irst we have a single expression n 2most o#ten a variable3, that is evaluated once% .he value o# the expression is then compared with the values #or each case in the structure% # there is a match, the block o# code associated with that case is executed% Gse break to prevent the code #rom running into the next case automaticall)%

!xample
<script type="text/javascript"> //Fou "ill receive a di22ere t greeti g based //o "hat day it is! Gote that /u day=AB //Mo day=1B ,uesday=;B etc! var d= e" %ate#&' var the%ay=d!get%ay#&' s"itch #the%ay& 3 case 86 docume t!"rite#"Fi ally Friday"&' brea5' case E6 docume t!"rite#"/uper /aturday"&' brea5' case A6 docume t!"rite#"/leepy /u day"&' brea5' de2ault6 docume t!"rite#"*Hm loo5i g 2or"ard to this "ee5e d0"&' 4 </script>
Try it yoursel !

Previous

Next Chapter

JavaScript :opup %o+es


Previous Next Chapter
JavaScript has three kind o# popup boxes, (lert box, Con#irm box, and Prompt box%

(lert +ox
(n alert box is o#ten used i# )ou want to make sure in#ormation comes through to the user% &hen an alert box pops up, the user will have to click 7$*7 to proceed%

Synta+
alert#"sometext"&'

!xample
<html> <head> <script type="text/javascript"> 2u ctio sho"Ialert#& 3 alert#"* am a alert box0"&' 4 </script> </head> <body> <i put type="butto " o clic5="sho"Ialert#&" value="/ho" alert box" /> </body> </html>
Try it yoursel !

Con#irm +ox
( con#irm box is o#ten used i# )ou want the user to veri#) or accept something% &hen a con#irm box pops up, the user will have to click either 7$*7 or 7Cancel7 to proceed% # the user clicks 7$*7, the box returns true% # the user clicks 7Cancel7, the box returns #alse%

Synta+
co 2irm#"sometext"&'

!xample

<html> <head> <script type="text/javascript"> 2u ctio sho"Ico 2irm#& 3 var r=co 2irm#"Press a butto "&' i2 #r==true& 3 alert#"Fou pressed CJ0"&' 4 else 3 alert#"Fou pressed Ka cel0"&' 4 4 </script> </head> <body> <i put type="butto " o clic5="sho"Ico 2irm#&" value="/ho" co 2irm box" /> </body> </html>
Try it yoursel !

Prompt +ox
( prompt box is o#ten used i# )ou want the user to input a value be#ore entering a page% &hen a prompt box pops up, the user will have to click either 7$*7 or 7Cancel7 to proceed a#ter entering an input value% # the user clicks 7$*7 the box returns the input value% # the user clicks 7Cancel7 the box returns null%

Synta+
prompt#"sometext"B"defaultvalue"&'

!xample
<html> <head> <script type="text/javascript"> 2u ctio sho"Iprompt#& 3 var ame=prompt#"Please e ter your ame"B"+arry Potter"&' i2 # ame0= ull DD ame0=""& 3 docume t!"rite#"+ello " $ ame $ "0 +o" are you today>"&' 4

4 </script> </head> <body> <i put type="butto " o clic5="sho"Iprompt#&" value="/ho" prompt box" /> </body> </html>
Try it yoursel !

/ore !xamples
(lert box with line breaks

Previous

Next Chapter

JavaScript ;unctions
Previous
( #unction will be executed b) an event or b) a call to the #unction%

Next Chapter

JavaScript "unctions
.o keep the browser #rom executing a script when the page loads, )ou can put )our script into a #unction% ( #unction contains code that will be executed b) an event or b) a call to the #unction% 'ou ma) call a #unction #rom an)where within a page 2or even #rom other pages i# the #unction is embedded in an external %js #ile3% "unctions can be de#ined both in the CheadD and in the Cbod)D section o# a document% -owever, to assure that a #unction is readAloaded b) the browser be#ore it is called, it could be wise to put #unctions in the CheadD section%

-ow to Ee#ine a "unction


S)ntax
2u ctio 3 functionname#var1,var2,...,varX&

some code 4
.he parameters var=, var:, etc% are variables or values passed into the #unction% .he J and the K de#ines the start and end o# the #unction% "ote# ( #unction with no parameters must include the parentheses 23 a#ter the #unction name% "ote# Eo not #orget about the importance o# capitals in JavaScript4 .he word function must be written in lowercase letters, otherwise a JavaScript error occurs4 (lso note that )ou must call a #unction with the exact same capitals as in the #unction name%

JavaScript "unction !xample


!xample
<html> <head> <script type="text/javascript"> 2u ctio displaymessage#& 3 alert#"+ello World0"&' 4 </script> </head> <body> <2orm> <i put type="butto " value="Klic5 me0" o clic5="displaymessage#&" /> </2orm> </body> </html>
Try it yoursel !

# the line, alert27-ello world4473 in the example above had not been put within a #unction, it would have been executed as soon as the page was loaded% Now, the script is not executed be#ore a user hits the input button% .he #unction displa)message23 will be executed i# the input button is clicked% 'ou will learn more about JavaScript events in the JS !vents chapter%

.he return Statement


.he return statement is used to speci#) the value that is returned #rom the #unction% So, #unctions that are going to return a value must use the return statement% .he example below returns the product o# two numbers 2a and b3,

!xample
<html> <head> <script type="text/javascript"> 2u ctio product#aBb& 3 retur a7b' 4 </script> </head> <body> <script type="text/javascript"> docume t!"rite#product#LB<&&' </script> </body> </html>
Try it yoursel !

.he 0i#etime o# JavaScript Mariables


# )ou declare a variable, using 7var7, within a #unction, the variable can onl) be accessed within that #unction% &hen )ou exit the #unction, the variable is destro)ed% .hese variables are called local variables% 'ou can have local variables with the same name in di##erent #unctions, because each is recogni?ed onl) b) the #unction in which it is declared% # )ou declare a variable outside a #unction, all the #unctions on )our page can access it% .he li#etime o# these variables starts when the) are declared, and ends when the page is closed%

/ore !xamples
"unction with a parameter -ow to pass a variable to a #unction, and use the variable in the #unction% "unction that returns a value -ow to let a #unction return a value%

Previous

Next Chapter

JavaScript ;or Loop


Previous Next Chapter
0oops execute a block o# code a speci#ied number o# times, or while a speci#ied condition is true%

JavaScript 0oops
$#ten when )ou write code, )ou want the same block o# code to run over and over again in a row% nstead o# adding several almost eIual lines in a script we can use loops to per#orm a task like this% n JavaScript, there are two di##erent kind o# loops,

or 5 loops through a block o# code a speci#ied number o# times while 5 loops through a block o# code while a speci#ied condition is true

.he #or 0oop


.he #or loop is used when )ou know in advance how man) times the script should run%

Synta+
2or #variable=startvalue'variable<=endvalue'variable=variable$increment& 3 code to be executed 4

$+ample
.he example below de#ines a loop that starts with i9<% .he loop will continue to run as long as i is less than, or eIual to N% i will increase b) = each time the loop runs% "ote# .he increment parameter could also be negative, and the C9 could be an) comparing statement%

!xample
<html> <body> <script type="text/javascript"> var i=A' 2or #i=A'i<=8'i$$& 3 docume t!"rite#",he umber is " $ i&' docume t!"rite#"<br />"&' 4 </script> </body> </html>
Try it yoursel !

.he while loop


.he while loop will be explained in the next chapter%

/ore !xamples
0ooping through -./0 headings 0oop through the six di##erent -./0 headings%

Previous

Next Chapter

JavaScript (hile Loop


Previous Next Chapter
0oops execute a block o# code a speci#ied number o# times, or while a speci#ied condition is true%

.he while 0oop


.he while loop loops through a block o# code while a speci#ied condition is true%

S)ntax
"hile #variable<=endvalue& 3 code to be executed 4
"ote# .he C9 could be an) comparing operator%

!xample
.he example below de#ines a loop that starts with i9<% .he loop will continue to run as long as i is less than, or eIual to N% i will increase b) = each time the loop runs,

!xample
<html> <body> <script type="text/javascript"> var i=A' "hile #i<=8&

3 docume t!"rite#",he umber is " $ i&' docume t!"rite#"<br />"&' i$$' 4 </script> </body> </html>
Try it yoursel !

.he do%%%while 0oop


.he do%%%while loop is a variant o# the while loop% .his loop will execute the block o# code $NC!, and then it will repeat the loop as long as the speci#ied condition is true%

S)ntax
do 3 code to be executed 4 "hile #variable<=endvalue&'

!xample
.he example below uses a do%%%while loop% .he do%%%while loop will alwa)s be executed at least once, even i# the condition is #alse, because the statements are executed be#ore the condition is tested,

!xample
<html> <body> <script type="text/javascript"> var i=A' do 3 docume t!"rite#",he umber is " $ i&' docume t!"rite#"<br />"&' i$$' 4 "hile #i<=8&' </script> </body> </html>
Try it yoursel !

Previous

Next Chapter

JavaScript %reak and )ontinue Statements


Previous Next Chapter

.he break Statement


.he break statement will break the loop and continue executing the code that #ollows a#ter the loop 2i# an)3%

!xample
<html> <body> <script type="text/javascript"> var i=A' 2or #i=A'i<=1A'i$$& 3 i2 #i==<& 3 brea5' 4 docume t!"rite#",he umber is " $ i&' docume t!"rite#"<br />"&' 4 </script> </body> </html>
Try it yoursel !

.he continue Statement


.he continue statement will break the current loop and continue with the next value%

!xample
<html> <body> <script type="text/javascript"> var i=A 2or #i=A'i<=1A'i$$& 3 i2 #i==<& 3 co ti ue' 4 docume t!"rite#",he umber is " $ i&' docume t!"rite#"<br />"&'

4 </script> </body> </html>


Try it yoursel !

Previous

Next Chapter

JavaScript ;or999In Statement


Previous Next Chapter

JavaScript "or%%% n Statement


.he #or%%%in statement loops through the properties o# an object%

S)ntax
2or #variable i object& 3 code to be executed 4
"ote# .he code in the bod) o# the #or%%%in loop is executed once #or each propert)%

!xample
0ooping through the properties o# an object,

!xample
var perso =32 ame6".oh "Bl ame6"%oe"Bage6;84' 2or #x i perso & 3 docume t!"rite#perso MxN $ " "&' 4
Try it yoursel !

Previous

Next Chapter

JavaScript $vents
Previous
!vents are actions that can be detected b) JavaScript%

Next Chapter

(cting to an !vent
.he example below displa)s the date when a button is clicked,

!xample
<html> <head> <script type="text/javascript"> 2u ctio display%ate#& 3 docume t!get(leme t)y*d#"demo"&!i 4 </script> </head> <body> <h1>My First Web Page</h1> <p id="demo"></p> <butto </body> </html>
Try it yoursel !

er+,M-=%ate#&'

type="butto " o clic5="display%ate#&">%isplay %ate</butto >

!vents
+) using JavaScript, we have the abilit) to create d)namic web pages% !vents are actions that can be detected b) JavaScript% !ver) element on a web page has certain events which can trigger a JavaScript% "or example, we can use the onClick event o# a button element to indicate that a #unction will run when a user clicks on the button% &e de#ine the events in the -./0 tags% !xamples o# events,

( mouse click ( web page or an image loading

/ousing over a hot spot on the web page Selecting an input #ield in an -./0 #orm Submitting an -./0 #orm ( ke)stroke

"ote# !vents are normall) used in combination with #unctions, and the #unction will not be executed be#ore the event occurs4 "or a complete re#erence o# the events recogni?ed b) JavaScript, go to our complete !vent re#erence%

on0oad and onGnload


.he on0oad and onGnload events are triggered when the user enters or leaves the page% .he on0oad event is o#ten used to check the visitor8s browser t)pe and browser version, and load the proper version o# the web page based on the in#ormation% +oth the on0oad and onGnload events are also o#ten used to deal with cookies that should be set when a user enters or leaves a page% "or example, )ou could have a popup asking #or the user8s name upon his #irst arrival to )our page% .he name is then stored in a cookie% Next time the visitor arrives at )our page, )ou could have another popup sa)ing something like, 7&elcome John Eoe47%

on"ocus, on+lur and onChange


.he on"ocus, on+lur and onChange events are o#ten used in combination with validation o# #orm #ields% +elow is an example o# how to use the onChange event% .he check!mail23 #unction will be called whenever the user changes the content o# the #ield,

<i put type="text" si:e="<A" id="email" o cha ge="chec5(mail#&">

onSubmit
.he onSubmit event is used to validate (00 #orm #ields be#ore submitting it% +elow is an example o# how to use the onSubmit event% .he check"orm23 #unction will be called when the user clicks the submit button in the #orm% # the #ield values are not accepted, the submit should be cancelled% .he #unction check"orm23 returns either true or #alse% # it returns true the #orm will be submitted, otherwise the submit will be cancelled,

<2orm method="post" actio ="xxx!htm" o submit="retur

chec5Form#&">

on/ouse$ver
.he onmouseover event can be used to trigger a #unction when the user mouses over an -./0 element,

!xample

/ouse over the sun and the planets and see the di##erent descriptions%
Try it yoursel !

Previous

Next Chapter

JavaScript Try999)atch Statement


Previous
.he tr)%%%catch statement allows )ou to test a block o# code #or errors%

Next Chapter

JavaScript 5 Catching !rrors


&hen browsing &eb pages on the internet, we all have seen a JavaScript alert box telling us there is a runtime error and asking 7Eo )ou wish to debug17% !rror message like this ma) be use#ul #or developers but not #or users% &hen users see errors, the) o#ten leave the &eb page% .his chapter will teach )ou how to catch and handle JavaScript error messages, so )ou don8t lose )our audience%

.he tr)%%%catch Statement


.he tr)%%%catch statement allows )ou to test a block o# code #or errors% .he tr) block contains the code to be run, and the catch block contains the code to be executed i# an error occurs%

S)ntax
try 3 //?u some code here 4 catch#err& 3 //+a dle errors here 4

Note that tr)%%%catch is written in lowercase letters% Gsing uppercase letters will generate a JavaScript error4

!xamples
.he example below is supposed to alert 7&elcome guest47 when the button is clicked% -owever, there8s a t)po in the message23 #unction% alert23 is misspelled as adddlert23% ( JavaScript error occurs% .he catch block catches the error and executes a custom code to handle it% .he code displa)s a custom error message in#orming the user what happened,

!xample
<html> <head> <script type="text/javascript"> var txt=""' 2u ctio message#& 3 try 3 adddlert#"Welcome guest0"&' 4 catch#err& 3 txt=",here "as a error o this page!O O "' txt$="(rror descriptio 6 " $ err!descriptio txt$="Klic5 CJ to co ti ue!O O "' alert#txt&' 4 4 </script> </head>

$ "O O "'

<body> <i put type="butto " value="9ie" message" o clic5="message#&" /> </body> </html>
Try it yoursel !

.he next example uses a con#irm box to displa) a custom message telling users the) can click $* to continue viewing the page or click Cancel to go to the homepage% # the con#irm method returns #alse, the user clicked Cancel, and the code redirects the user% # the con#irm method returns true, the code does nothing,

!xample
<html> <head> <script type="text/javascript"> var txt=""' 2u ctio message#& 3

try 3 adddlert#"Welcome guest0"&' 4 catch#err& 3 txt=",here "as a error o this page!O O "' txt$="Klic5 CJ to co ti ue vie"i g this pageBO "' txt$="or Ka cel to retur to the home page!O O "' i2#0co 2irm#txt&& 3 docume t!locatio !hre2="http6//"""!"<schools!com/"' 4 4 4 </script> </head> <body> <i put type="butto " value="9ie" message" o clic5="message#&" /> </body> </html>
Try it yoursel !

.he throw Statement


.he throw statement can be used together with the tr)%%%catch statement, to create an exception #or the error% 0earn about the throw statement in the next chapter%

Previous

Next Chapter

JavaScript Throw Statement


Previous
.he throw statement allows )ou to create an exception%

Next Chapter

.he .hrow Statement


.he throw statement allows )ou to create an exception% # )ou use this statement together with the tr)%%%catch statement, )ou can control program #low and generate accurate error messages%

S)ntax
thro" exception
.he exception can be a string, integer, +oolean or an object% Note that throw is written in lowercase letters% Gsing uppercase letters will generate a JavaScript error4

!xample
.he example below determines the value o# a variable called x% # the value o# x is higher than =<, lower than <, or not a number, we are going to throw an error% .he error is then caught b) the catch argument and the proper error message is displa)ed,

!xample
<html> <body> <script type="text/javascript"> var x=prompt#"( ter a umber bet"ee A a d 1A6"B""&' try 3 i2#x>1A& 3 thro" "(rr1"' 4 else i2#x<A& 3 thro" "(rr;"' 4 else i2#isGaG#x&& 3 thro" "(rr<"' 4 4 catch#er& 3 i2#er=="(rr1"& 3 alert#"(rror0 ,he value is too high"&' 4 i2#er=="(rr;"& 3 alert#"(rror0 ,he value is too lo""&' 4 i2#er=="(rr<"& 3 alert#"(rror0 ,he value is ot a umber"&' 4 4 </script> </body> </html>

Try it yoursel !

Previous

Next Chapter

JavaScript Special )haracters


Previous Next Chapter
n JavaScript )ou can add special characters to a text string b) using the backslash sign%

nsert Special Characters


.he backslash 2U3 is used to insert apostrophes, new lines, Iuotes, and other special characters into a text string% 0ook at the #ollowing JavaScript code,

var txt="We are the so1called "9i5i gs" 2rom the docume t!"rite#txt&'

orth!"'

n JavaScript, a string is started and stopped with either single or double Iuotes% .his means that the string above will be chopped to, &e are the so5called .o solve this problem, )ou must place a backslash 2U3 be#ore each double Iuote in 7Miking7% .his turns each double Iuote into a string literal,

var txt="We are the so1called O"9i5i gsO" 2rom the docume t!"rite#txt&'

orth!"'

JavaScript will now output the proper text string, &e are the so5called 7Mikings7 #rom the north% .he table below lists other special characters that can be added to a text string with the backslash sign, )ode U8 U7 UU Un Ur Ut Ub U# -utputs single Iuote double Iuote backslash new line carriage return tab backspace #orm #eed

Previous

Next Chapter

JavaScript /uidelines
Previous
Some other important things to know when scripting with JavaScript%

Next Chapter

JavaScript is Case Sensitive


( #unction named 7m)#unction7 is not the same as 7m)"unction7 and a variable named 7m)Mar7 is not the same as 7m)var7% JavaScript is case sensitive 5 there#ore watch )our capitali?ation closel) when )ou create or call variables, objects and #unctions%

&hite Space
JavaScript ignores extra spaces% 'ou can add white space to )our script to make it more readable% .he #ollowing lines are eIuivalent,

var var

ame="+ege"' ame = "+ege"'

+reak up a Code 0ine


'ou can break up a code line within a te+t string with a backslash% .he example below will be displa)ed properl),

docume t!"rite#"+ello O World0"&'


-owever, )ou cannot break up a code line like this,

docume t!"rite O #"+ello World0"&'

Previous

Next Chapter

JavaScript -b<ects ntroduction


Previous
JavaScript is an $bject $riented Programming 2$$P3 language% (n $$P language allows )ou to de#ine )our own objects and make )our own variable t)pes%

Next Chapter

$bject $riented Programming


JavaScript is an $bject $riented Programming 2$$P3 language% (n $$P language allows )ou to de#ine )our own objects and make )our own variable t)pes% -owever, creating )our own objects will be explained later, in the (dvanced JavaScript section% &e will start b) looking at the built5in JavaScript objects, and how the) are used% .he next pages will explain each built5in JavaScript object in detail% Note that an object is just a special kind o# data% (n object has properties and methods%

Properties
Properties are the values associated with an object% n the #ollowing example we are using the length propert) o# the String object to return the number o# characters in a string,

<script type="text/javascript"> var txt="+ello World0"' docume t!"rite#txt!le gth&' </script>


.he output o# the code above will be,

1;

/ethods
/ethods are the actions that can be per#ormed on objects% n the #ollowing example we are using the toGpperCase23 method o# the String object to displa) a text in uppercase letters,

<script type="text/javascript"> var str="+ello "orld0"' docume t!"rite#str!toPpperKase#&&'

</script>
.he output o# the code above will be,

+(--C WC?-%0

Previous

Next Chapter

JavaScript String $bject


Previous
.he String object is used to manipulate a stored piece o# text%

Next Chapter

.r) it 'oursel# 5 !xamples


Heturn the length o# a string -ow to return the length o# a string% St)le strings -ow to st)le strings% .he to0owerCase23 and toGpperCase23 methods -ow to convert a string to lowercase or uppercase letters% .he match23 method -ow to search #or a speci#ied value within a string% Heplace characters in a string 5 replace23 -ow to replace a speci#ied value with another value in a string% .he index$#23 method -ow to return the position o# the #irst #ound occurrence o# a speci#ied value in a string%

Complete String $bject He#erence


"or a complete re#erence o# all the properties and methods that can be used with the String object, go to our complete String object re#erence% .he re#erence contains a brie# description and examples o# use #or each propert) and method4

String object
.he String object is used to manipulate a stored piece o# text%

$+amples o use# .he #ollowing example uses the length propert) o# the String object to #ind the length o# a string,

var txt="+ello "orld0"' docume t!"rite#txt!le gth&'


.he code above will result in the #ollowing output,

1;
.he #ollowing example uses the toGpperCase23 method o# the String object to convert a string to uppercase letters,

var txt="+ello "orld0"' docume t!"rite#txt!toPpperKase#&&'


.he code above will result in the #ollowing output,

+(--C WC?-%0

Previous

Next Chapter

JavaScript 1ate $bject


Previous
.he Eate object is used to work with dates and times%

Next Chapter

.r) it 'oursel# 5 !xamples


Heturn toda)8s date and time -ow to use the Eate23 method to get toda)8s date% get"ull'ear23 Gse get"ull'ear23 to get the )ear% get.ime23 get.ime23 returns the number o# milliseconds since <=%<=%=>@<% set"ull'ear23 -ow to use set"ull'ear23 to set a speci#ic date%

toG.CString23 -ow to use toG.CString23 to convert toda)8s date 2according to G.C3 to a string% getEa)23 Gse getEa)23 and an arra) to write a weekda), and not just a number% Eispla) a clock -ow to displa) a clock on )our web page%

Complete Eate $bject He#erence


"or a complete re#erence o# all the properties and methods that can be used with the Eate object, go to our complete Eate object re#erence% .he re#erence contains a brie# description and examples o# use #or each propert) and method4

Create a Eate $bject


.he Eate object is used to work with dates and times% Eate objects are created with the Eate23 constructor% .here are #our wa)s o# instantiating a date,

e" e" e" e"

%ate#& // curre t date a d time %ate#milliseco ds& //milliseco ds si ce 1QRA/A1/A1 %ate#date/tri g& %ate#yearB mo thB dayB hoursB mi utesB seco dsB milliseco ds&

/ost parameters above are optional% Not speci#)ing, causes < to be passed in% $nce a Eate object is created, a number o# methods allow )ou to operate on it% /ost methods allow )ou to get and set the )ear, month, da), hour, minute, second, and milliseconds o# the object, using either local time or G.C 2universal, or O/.3 time% (ll dates are calculated in milliseconds #rom <= Januar), =>@< <<,<<,<< Gniversal .ime 2G.C3 with a da) containing B;,R<<,<<< milliseconds% Some examples o# instantiating a date,

var var var var

today d1 = d; = d< =

= e" e" e"

e" %ate#& %ate#"Cctober 1<B 1QR8 1161<6AA"& %ate#RQB8B;L& %ate#RQB8B;LB11B<<BA&

Set Eates
&e can easil) manipulate the date b) using the methods available #or the Eate object%

n the example below we set a Eate object to a speci#ic date 2=Rth Januar) :<=<3,

var my%ate= e" %ate#&' my%ate!setFullFear#;A1ABAB1L&'


(nd in the #ollowing example we set a Eate object to be N da)s into the #uture,

var my%ate= e" %ate#&' my%ate!set%ate#my%ate!get%ate#&$8&'


"ote# # adding #ive da)s to a date shi#ts the month or )ear, the changes are handled automaticall) b) the Eate object itsel#4

Compare .wo Eates


.he Eate object is also used to compare two dates% .he #ollowing example compares toda)8s date with the =Rth Januar) :=<<,

var x= e" %ate#&' x!setFullFear#;1AABAB1L&' var today = e" %ate#&' i2 #x>today& 3 alert#",oday is be2ore 1Lth .a uary ;1AA"&' 4 else 3 alert#",oday is a2ter 1Lth .a uary ;1AA"&' 4

Previous

Next Chapter

JavaScript .rray $bject


Previous
.he (rra) object is used to store multiple values in a single variable%

Next Chapter

.r) it 'oursel# 5 !xamples

Create an arra) Create an arra), assign values to it, and write the values to the output% 2'ou can #ind more examples at the bottom o# this page3

Complete (rra) $bject He#erence


"or a complete re#erence o# all the properties and methods that can be used with the (rra) object, go to our complete (rra) object re#erence% .he re#erence contains a brie# description and examples o# use #or each propert) and method4

&hat is an (rra)1
(n arra) is a special variable, which can hold more than one value, at a time% # )ou have a list o# items 2a list o# car names, #or example3, storing the cars in single variables could look like this,

var car1="/aab"' var car;="9olvo"' var car<=")MW"'


-owever, what i# )ou want to loop through the cars and #ind a speci#ic one1 (nd what i# )ou had not P cars, but P<<1 .he best solution here is to use an arra)4 (n arra) can hold all )our variable values under a single name% (nd )ou can access the values b) re#erring to the arra) name% !ach element in the arra) has its own E so that it can be easil) accessed%

Create an (rra)
(n arra) can be de#ined in three wa)s% .he #ollowing code creates an (rra) object called m)Cars, =,

var myKars= e" Srray#&' // regular array #add a optio al i teger myKarsMAN="/aab"' // argume t to co trol arrayHs si:e& myKarsM1N="9olvo"' myKarsM;N=")MW"'
:,

var myKars= e" Srray#"/aab"B"9olvo"B")MW"&' // co de sed array


P,

var myKars=M"/aab"B"9olvo"B")MW"N' // literal array


"ote# # )ou speci#) numbers or trueA#alse values inside the arra) then the variable t)pe will be Number or +oolean, instead o# String%

(ccess an (rra)
'ou can re#er to a particular element in an arra) b) re#erring to the name o# the arra) and the index number% .he index number starts at <% .he #ollowing code line,

docume t!"rite#myKarsMAN&'
will result in the #ollowing output,

/aab

/odi#) Malues in an (rra)


.o modi#) a value in an existing arra), just add a new value to the arra) with a speci#ied index number,

myKarsMAN="Cpel"'
Now, the #ollowing code line,

docume t!"rite#myKarsMAN&'
will result in the #ollowing output,

Cpel

/ore !xamples
Join two arra)s 5 concat23 Join three arra)s 5 concat23 Join all elements o# an arra) into a string 5 join23

Hemove the last element o# an arra) 5 pop23 (dd new elements to the end o# an arra) 5 push23 Heverse the order o# the elements in an arra) 5 reverse23 Hemove the #irst element o# an arra) 5 shi#t23 Select elements #rom an arra) 5 slice23 Sort an arra) 2alphabeticall) and ascending3 5 sort23 Sort numbers 2numericall) and ascending3 5 sort23 Sort numbers 2numericall) and descending3 5 sort23 (dd an element to position : in an arra) 5 splice23 Convert an arra) to a string 5 toString23 (dd new elements to the beginning o# an arra) 5 unshi#t23

Previous

Next Chapter

JavaScript %oolean $bject


Previous Next Chapter
.he +oolean object is used to convert a non5+oolean value to a +oolean value 2true or #alse3%

.r) it 'oursel# 5 !xamples


Check +oolean value Check i# a +oolean object is true or #alse%

Complete +oolean $bject He#erence


"or a complete re#erence o# all the properties and methods that can be used with the +oolean object, go to our complete +oolean object re#erence%

.he re#erence contains a brie# description and examples o# use #or each propert) and method4

Create a +oolean $bject


.he +oolean object represents two values, 7true7 or 7#alse7% .he #ollowing code creates a +oolean object called m)+oolean,

var my)oolea = e" )oolea #&'


# the +oolean object has no initial value, or i# the passed value is one o# the #ollowing,

< 5< null 77 #alse unde#ined NaN

the object it is set to #alse% "or an) other value it is set to true 2even with the string 7#alse734

Previous

Next Chapter

JavaScript Math $bject


Previous
.he /ath object allows )ou to per#orm mathematical tasks%

Next Chapter

.r) it 'oursel# 5 !xamples


round23 -ow to use round23% random23 -ow to use random23 to return a random number between < and =% max23 -ow to use max23 to return the number with the highest value o# two speci#ied numbers% min23 -ow to use min23 to return the number with the lowest value o# two speci#ied numbers%

Complete /ath $bject He#erence


"or a complete re#erence o# all the properties and methods that can be used with the /ath object, go to our complete /ath object re#erence% .he re#erence contains a brie# description and examples o# use #or each propert) and method4

/ath $bject
.he /ath object allows )ou to per#orm mathematical tasks% .he /ath object includes several mathematical constants and methods% Synta+ or using properties=methods o Math#

var x=Math!P*' var y=Math!sTrt#1E&'


"ote# /ath is not a constructor% (ll properties and methods o# /ath can be called b) using /ath as an object without creating it%

/athematical Constants
JavaScript provides eight mathematical constants that can be accessed #rom the /ath object% .hese are, !, P , sIuare root o# :, sIuare root o# =A:, natural log o# :, natural log o# =<, base5: log o# !, and base5=< log o# !% 'ou ma) re#erence these constants #rom )our JavaScript like this,

Math!( Math!P* Math!/U?,; Math!/U?,1I; Math!-G; Math!-G1A Math!-C@;( Math!-C@1A(

/athematical /ethods
n addition to the mathematical constants that can be accessed #rom the /ath object there are also several methods available% .he #ollowing example uses the round23 method o# the /ath object to round a number to the nearest integer,

docume t!"rite#Math!rou d#L!R&&'

.he code above will result in the #ollowing output,

8
.he #ollowing example uses the random23 method o# the /ath object to return a random number between < and =,

docume t!"rite#Math!ra dom#&&'


.he code above can result in the #ollowing output,

A!Q88;RLL;1Q8L8;R8
.he #ollowing example uses the #loor23 and random23 methods o# the /ath object to return a random number between < and =<,

docume t!"rite#Math!2loor#Math!ra dom#&711&&'


.he code above can result in the #ollowing output,

Previous

Next Chapter

JavaScript 2eg$+p $bject


Previous
Heg!xp, is short #or regular expression%

Next Chapter

Complete Heg!xp $bject He#erence


"or a complete re#erence o# all the properties and methods that can be used with the Heg!xp object, go to our complete Heg!xp object re#erence% .he re#erence contains a brie# description and examples o# use #or each propert) and method4

&hat is Heg!xp1

( regular expression is an object that describes a pattern o# characters% &hen )ou search in a text, )ou can use a pattern to describe what )ou are searching #or% ( simple pattern can be one single character% ( more complicated pattern can consist o# more characters, and can be used #or parsing, #ormat checking, substitution and more% Hegular expressions are used to per#orm power#ul pattern5matching and 7search5and5replace7 #unctions on text%

S)ntax
var patt= e" ?eg(xp#patter Bmodi2iers&' or more simply6 var patt=/patter /modi2iers'
pattern speci#ies the pattern o# an expression modi#iers speci#) i# a search should be global, case5sensitive, etc%

Heg!xp /odi#iers
/odi#iers are used to per#orm case5insensitive and global searches% .he i modi#ier is used to per#orm case5insensitive matching% .he g modi#ier is used to per#orm a global match 2#ind all matches rather than stopping a#ter the #irst match3%

!xample =
Eo a case5insensitive search #or 7wPschools7 in a string,

var str="9isit W</chools"' var patt1=/"<schools/i'


.he marked text below shows where the expression gets a match,

9isit W</chools
Try it yoursel !

!xample :
Eo a global search #or 7is7,

var str="*s this all there is>"'

var patt1=/is/g'
.he marked text below shows where the expression gets a match,

*s this all there is>


Try it yoursel !

!xample P
Eo a global, case5insensitive search #or 7is7,

var str="*s this all there is>"' var patt1=/is/gi'


.he marked text below shows where the expression gets a match,

*s this all there is>


Try it yoursel !

test23
.he test23 method searches a string #or a speci#ied value, and returns true or #alse, depending on the result% .he #ollowing example searches a string #or the character 7e7,

!xample
var patt1= e" ?eg(xp#"e"&' docume t!"rite#patt1!test#",he best thi gs i li2e are 2ree"&&'

Since there is an 7e7 in the string, the output o# the code above will be,

true
Try it yoursel !

exec23
.he exec23 method searches a string #or a speci#ied value, and returns the text o# the #ound value% # no match is #ound, it returns null. .he #ollowing example searches a string #or the character 7e7,

!xample =
var patt1= e" ?eg(xp#"e"&' docume t!"rite#patt1!exec#",he best thi gs i li2e are 2ree"&&'

Since there is an 7e7 in the string, the output o# the code above will be,

e
Try it yoursel !

Previous

Next Chapter

JavaScript %rowser 1etection


Previous
.he Navigator object contains in#ormation about the visitor8s browser%

Next Chapter

+rowser Eetection
(lmost ever)thing in this tutorial works on all JavaScript5enabled browsers% -owever, there are some things that just don8t work on certain browsers 5 especiall) on older browsers% Sometimes it can be use#ul to detect the visitor8s browser, and then serve the appropriate in#ormation% .he Navigator object contains in#ormation about the visitor8s browser name, version, and more% "ote# .here is no public standard that applies to the navigator object, but all major browsers support it%

.he Navigator $bject


.he Navigator object contains all in#ormation about the visitor8s browser,

!xample
<div id="example"></div> <script type="text/javascript"> txt = txt$= txt$= txt$= txt$= "<p>)ro"ser KodeGame6 " $ avigator!appKodeGame $ "</p>"' "<p>)ro"ser Game6 " $ avigator!appGame $ "</p>"' "<p>)ro"ser 9ersio 6 " $ avigator!app9ersio $ "</p>"' "<p>Koo5ies ( abled6 " $ avigator!coo5ie( abled $ "</p>"' "<p>Plat2orm6 " $ avigator!plat2orm $ "</p>"'

txt$= "<p>Pser1age t header6 " $

avigator!userSge t $ "</p>"' er+,M-=txt'

docume t!get(leme t)y*d#"example"&!i </script>


Try it yoursel !

Previous

Next Chapter

JavaScript )ookies
Previous
( cookie is o#ten used to identi#) a user%

Next Chapter

&hat is a Cookie1
( cookie is a variable that is stored on the visitor8s computer% !ach time the same computer reIuests a page with a browser, it will send the cookie too% &ith JavaScript, )ou can both create and retrieve cookie values% !xamples o# cookies,

Name cookie 5 .he #irst time a visitor arrives to )our web page, he or she must #ill in herAhis name% .he name is then stored in a cookie% Next time the visitor arrives at )our page, he or she could get a welcome message like 7&elcome John Eoe47 .he name is retrieved #rom the stored cookie Password cookie 5 .he #irst time a visitor arrives to )our web page, he or she must #ill in a password% .he password is then stored in a cookie% Next time the visitor arrives at )our page, the password is retrieved #rom the cookie Eate cookie 5 .he #irst time a visitor arrives to )our web page, the current date is stored in a cookie% Next time the visitor arrives at )our page, he or she could get a message like 7'our last visit was on .uesda) (ugust ==, :<<N47 .he date is retrieved #rom the stored cookie

Create and Store a Cookie


n this example we will create a cookie that stores the name o# a visitor% .he #irst time a visitor arrives to the web page, he or she will be asked to #ill in herAhis name% .he name is then stored in a cookie% .he next time the visitor arrives at the same page, he or she will get welcome message% "irst, we create a #unction that stores the name o# the visitor in a cookie variable,

2u ctio setKoo5ie#cI ameBvalueBexdays& 3 var exdate= e" %ate#&'

exdate!set%ate#exdate!get%ate#& $ exdays&' var cIvalue=escape#value& $ ##exdays== ull& > "" 6 "' expires="$exdate!toP,K/tri g#&&' docume t!coo5ie=cI ame $ "=" $ cIvalue' 4
.he parameters o# the #unction above hold the name o# the cookie, the value o# the cookie, and the number o# da)s until the cookie expires% n the #unction above we #irst convert the number o# da)s to a valid date, then we add the number o# da)s until the cookie should expire% (#ter that we store the cookie name, cookie value and the expiration date in the document%cookie object% .hen, we create another #unction that returns a speci#ied cookie,

2u ctio getKoo5ie#cI ame& 3 var iBxByBS??coo5ies=docume t!coo5ie!split#"'"&' 2or #i=A'i<S??coo5ies!le gth'i$$& 3 x=S??coo5iesMiN!substr#ABS??coo5iesMiN!i dexC2#"="&&' y=S??coo5iesMiN!substr#S??coo5iesMiN!i dexC2#"="&$1&' x=x!replace#/VOs$WOs$X/gB""&' i2 #x==cI ame& 3 retur u escape#y&' 4 4 4
.he #unction above makes an arra) to retrieve cookie names and values, then it checks i# the speci#ied cookie exists, and returns the cookie value% 0ast, we create the #unction that displa)s a welcome message i# the cookie is set, and i# the cookie is not set it will displa) a prompt box, asking #or the name o# the user, and stores the username cookie #or P;N da)s, b) calling the setCookie #unction,

2u ctio chec5Koo5ie#& 3 var user ame=getKoo5ie#"user ame"&' i2 #user ame0= ull DD user ame0=""& 3 alert#"Welcome agai " $ user ame&' 4 else 3 user ame=prompt#"Please e ter your ame6"B""&' i2 #user ame0= ull DD user ame0=""& 3 setKoo5ie#"user ame"Buser ameB<E8&' 4 4 4

(ll together now,

!xample
<html> <head> <script type="text/javascript"> 2u ctio getKoo5ie#cI ame& 3 var iBxByBS??coo5ies=docume t!coo5ie!split#"'"&' 2or #i=A'i<S??coo5ies!le gth'i$$& 3 x=S??coo5iesMiN!substr#ABS??coo5iesMiN!i dexC2#"="&&' y=S??coo5iesMiN!substr#S??coo5iesMiN!i dexC2#"="&$1&' x=x!replace#/VOs$WOs$X/gB""&' i2 #x==cI ame& 3 retur u escape#y&' 4 4 4 2u ctio setKoo5ie#cI ameBvalueBexdays& 3 var exdate= e" %ate#&' exdate!set%ate#exdate!get%ate#& $ exdays&' var cIvalue=escape#value& $ ##exdays== ull& > "" 6 "' expires="$exdate!toP,K/tri g#&&' docume t!coo5ie=cI ame $ "=" $ cIvalue' 4 2u ctio chec5Koo5ie#& 3 var user ame=getKoo5ie#"user ame"&' i2 #user ame0= ull DD user ame0=""& 3 alert#"Welcome agai " $ user ame&' 4 else 3 user ame=prompt#"Please e ter your ame6"B""&' i2 #user ame0= ull DD user ame0=""& 3 setKoo5ie#"user ame"Buser ameB<E8&' 4 4 4 </script> </head> <body o load="chec5Koo5ie#&"> </body> </html>
Try it yoursel !

.he example above runs the checkCookie23 #unction when the page loads%

Previous

Next Chapter

JavaScript ;orm *alidation


Previous Next Chapter

JavaScript "orm Malidation


JavaScript can be used to validate data in -./0 #orms be#ore sending o## the content to a server% "orm data that t)picall) are checked b) a JavaScript could be,

has has has has

the the the the

user user user user

le#t reIuired #ields empt)1 entered a valid e5mail address1 entered a valid date1 entered text in a numeric #ield1

HeIuired "ields
.he #unction below checks i# a #ield has been le#t empt)% # the #ield is blank, an alert box alerts a message, the #unction returns #alse, and the #orm will not be submitted,

2u ctio validateForm#& 3 var x=docume t!2ormsM"myForm"NM"2 ame"N!value i2 #x== ull WW x==""& 3 alert#"First ame must be 2illed out"&' retur 2alse' 4 4
.he #unction above could be called when a #orm is submitted,

!xample
<2orm ame="myForm" actio ="demoI2orm!asp" o submit="retur method="post"> First ame6 <i put type="text" ame="2 ame"> <i put type="submit" value="/ubmit"> </2orm> validateForm#&"

Try it yoursel !

!5mail Malidation
.he #unction below checks i# the content has the general s)ntax o# an email% .his means that the input data must contain an V sign and at least one dot 2%3% (lso, the V must not be the #irst character o# the email address, and the last dot must be present a#ter the V sign, and minimum : characters be#ore the end,

2u ctio validateForm#& 3 var x=docume t!2ormsM"myForm"NM"email"N!value var atpos=x!i dexC2#"Y"&' var dotpos=x!last* dexC2#"!"&' i2 #atpos<1 WW dotpos<atpos$; WW dotpos$;>=x!le gth& 3 alert#"Got a valid e1mail address"&' retur 2alse' 4 4
.he #unction above could be called when a #orm is submitted,

!xample
<2orm ame="myForm" actio ="demoI2orm!asp" o submit="retur method="post"> (mail6 <i put type="text" ame="email"> <i put type="submit" value="/ubmit"> </2orm>
Try it yoursel !

validateForm#&'"

Previous

Next Chapter

JavaScript Timing $vents


Previous
1 2 3 4 5 6 7

Next Chapter
JavaScript can be executed in time5intervals% .his is called timing events%

8 9 10 11 12

JavaScript .iming !vents


&ith JavaScript, it is possible to execute some code a#ter a speci#ied time5interval% .his is called timing events% t8s ver) eas) to time events in JavaScript% .he two ke) methods that are used are,

set.imeout23 5 executes a code some time in the #uture clear.imeout23 5 cancels the set.imeout23

"ote# .he set.imeout23 and clear.imeout23 are both methods o# the -./0 E$/ &indow object%

.he set.imeout23 /ethod


Synta+
var t=set,imeout#"javascript statement"Bmilliseconds&'
.he set.imeout23 method returns a value% n the s)ntax de#ined above, the value is stored in a variable called t% # )ou want to cancel the set.imeout23 #unction, )ou can re#er to it using the variable name% .he #irst parameter o# set.imeout23 can be a string o# executable code, or a call to a #unction% .he second parameter indicates how man) milliseconds #rom now )ou want to execute the #irst parameter% "ote# .here are =<<< milliseconds in one second%

!xample
&hen the button is clicked in the example below, an alert box will be displa)ed a#ter P seconds%

!xample
<html> <head> <script type="text/javascript"> 2u ctio timeMsg#& 3 var t=set,imeout#"alertMsg#&"B<AAA&' 4 2u ctio alertMsg#& 3 alert#"+ello"&' 4 </script> </head>

<body> <2orm> <i put type="butto " value="%isplay alert box i o clic5="timeMsg#&" /> </2orm> </body> </html>
Try it yoursel !

< seco ds"

!xample 5 n#inite 0oop


.o get a timer to work in an in#inite loop, we must write a #unction that calls itsel#% n the example below, when a button is clicked, the input #ield will start to count 2#or ever3, starting at <% Notice that we also have a #unction that checks i# the timer is alread) running, to avoid creating additional timers, i# the button is pressed more than once,

!xample
<html> <head> <script type="text/javascript"> var c=A' var t' var timerIisIo =A' 2u ctio timedKou t#& 3 docume t!get(leme t)y*d#HtxtH&!value=c' c=c$1' t=set,imeout#"timedKou t#&"B1AAA&' 4 2u ctio do,imer#& 3 i2 #0timerIisIo & 3 timerIisIo =1' timedKou t#&' 4 4 </script> </head> <body> <2orm> <i put type="butto " value="/tart cou t0" o clic5="do,imer#&"> <i put type="text" id="txt" /> </2orm> </body>

</html>
Try it yoursel !

.he clear.imeout23 /ethod


Synta+
clear,imeout#setTimeout_variable&

!xample
.he example below is the same as the 7 n#inite 0oop7 example above% .he onl) di##erence is that we have now added a 7Stop Count47 button that stops the timer,

!xample
<html> <head> <script type="text/javascript"> var c=A' var t' var timerIisIo =A' 2u ctio timedKou t#& 3 docume t!get(leme t)y*d#HtxtH&!value=c' c=c$1' t=set,imeout#"timedKou t#&"B1AAA&' 4 2u ctio do,imer#& 3 i2 #0timerIisIo & 3 timerIisIo =1' timedKou t#&' 4 4 2u ctio stopKou t#& 3 clear,imeout#t&' timerIisIo =A' 4 </script> </head> <body> <2orm> <i put type="butto " value="/tart cou t0" o clic5="do,imer#&">

<i put type="text" id="txt"> <i put type="butto " value="/top cou t0" o clic5="stopKou t#&"> </2orm> </body> </html>
Try it yoursel !

/ore !xamples
(nother simple timing ( clock created with a timing event

Previous

Next Chapter

JavaScript )reate >our -wn -b<ects


Previous
$bjects are use#ul to organi?e in#ormation%

Next Chapter

.r) it 'oursel# 5 !xamples


Create a direct instance o# an object Create a template #or an object

JavaScript $bjects
!arlier in this tutorial we have seen that JavaScript has several built5in objects, like String, Eate, (rra), and more% n addition to these built5in objects, )ou can also create )our own% (n object is just a special kind o# data, with a collection o# properties and methods% 0et8s illustrate with an example, ( person is an object% Properties are the values associated with the object% .he persons8 properties include name, height, weight, age, skin tone, e)e color, etc% (ll persons have these properties, but the values o# those properties will di##er #rom person to person% $bjects also have methods% /ethods are the actions that can be per#ormed on objects% .he persons8 methods could be eat23, sleep23, work23, pla)23, etc%

Properties
.he s)ntax #or accessing a propert) o# an object is,

objGame!propGame
'ou can add properties to an object b) simpl) giving it a value% (ssume that the person$bj alread) exists 5 )ou can give it properties named #irstname, lastname, age, and e)ecolor as #ollows,

perso perso perso perso

Cbj!2irst ame=".oh "' Cbj!last ame="%oe"' Cbj!age=<A' Cbj!eyecolor="blue"'

docume t!"rite#perso Cbj!2irst ame&'


.he code above will generate the #ollowing output,

.oh

/ethods
(n object can also contain methods% 'ou can call a method with the #ollowing s)ntax,

objGame!methodGame#&
"ote# Parameters reIuired #or the method can be passed between the parentheses% .o call a method called sleep23 #or the person$bj,

perso Cbj!sleep#&'

Creating 'our $wn $bjects


.here are di##erent wa)s to create a new object, 39 )reate a direct instance o an ob<ect .he #ollowing code creates an new instance o# an object, and adds #our properties to it,

perso perso perso perso perso

Cbj= e" Cbject#&' Cbj!2irst ame=".oh "' Cbj!last ame="%oe"' Cbj!age=8A' Cbj!eyecolor="blue"'

alternative s)ntax 2using object literals3,

perso Cbj=32irst ame6".oh "Blast ame6"%oe"Bage68ABeyecolor6"blue"4'


(dding a method to the person$bj is also simple% .he #ollowing code adds a method called eat23 to the person$bj,

perso Cbj!eat=eat'
?9 )reate an ob<ect constructor Create a #unction that construct objects,

2u ctio perso #2irst ameBlast ameBageBeyecolor& 3 this!2irst ame=2irst ame' this!last ame=last ame' this!age=age' this!eyecolor=eyecolor' 4
nside the #unction )ou need to assign things to this%propert)Name% .he reason #or all the 7this7 stu## is that )ou8re going to have more than one person at a time 2which person )ou8re dealing with must be clear3% .hat8s what 7this7 is, the instance o# the object at hand% $nce )ou have the object constructor, )ou can create new instances o# the object, like this,

var myFather= e" perso #".oh "B"%oe"B8AB"blue"&' var myMother= e" perso #"/ally"B"?ally"BL=B"gree "&'
'ou can also add some methods to the person object% .his is also done inside the #unction,

2u ctio perso #2irst ameBlast ameBageBeyecolor& 3 this!2irst ame=2irst ame' this!last ame=last ame' this!age=age' this!eyecolor=eyecolor' this! e"last ame= e"last ame' 4
Note that methods are just #unctions attached to objects% .hen we will have to write the newlastname23 #unction,

2u ctio e"last ame# e"Ilast ame& 3 this!last ame= e"Ilast ame' 4

.he newlastname23 #unction de#ines the person8s new last name and assigns that to the person% JavaScript knows which person )ou8re talking about b) using 7this%7% So, now )ou can write, m)/other%newlastname27Eoe73%

Previous

Next Chapter

'ou -ave 0earned JavaScript, "ow (hat@


Previous Next Chapter

JavaScript Summar)
.his tutorial has taught )ou how to add JavaScript to )our -./0 pages, to make )our web site more d)namic and interactive% 'ou have learned how to create responses to events, validate #orms and how to make di##erent scripts run in response to di##erent scenarios% 'ou have also learned how to create and use objects, and how to use JavaScript8s built5in objects% "or more in#ormation on JavaScript, please look at our JavaScript examples and our JavaScript re#erence%

Now 'ou *now JavaScript, &hat8s Next1


.he next step is to learn about the -./0 E$/, jWuer), and (J(X% # )ou want to learn about server5side scripting, the next step is to learn (SP or P-P% HTML 1-M .he -./0 E$/ de#ines a standard wa) #or accessing and manipulating -./0 documents% .he -./0 E$/ is plat#orm and language independent and can be used b) an) programming language like Java, JavaScript, and M+Script% # )ou want to learn more about the E$/, please visit our -./0 E$/ tutorial% <Auery jWuer) is a JavaScript 0ibrar)% jWuer) greatl) simpli#ies JavaScript programming% # )ou want to learn more about jWuer), please visit our jWuer) tutorial% .J.B

(J(X 9 (s)nchronous JavaScript and X/0% (J(X is not a new programming language, but a new wa) to use existing standards% (J(X is about exchanging data with a server, and update parts o# a web page 5 without reloading the whole page% !xamples o# applications using (J(X, Ooogle /aps, Omail, 'outube, and "acebook tabs% # )ou want to learn more about (J(X, please visit our (J(X tutorial% .S: = :H: &hile scripts in an -./0 #ile are executed on the client 2in the browser3, scripts in an (SPAP-P #ile are executed on the server% &ith (SPAP-P )ou can d)namicall) edit, change or add an) content o# a &eb page, respond to data submitted #rom -./0 #orms, access an) data or databases and return the results to a browser, customi?e a &eb page to make it more use#ul #or individual users% Since (SPAP-P #iles are returned as plain -./0, the) can be viewed in an) browser% # )ou want to learn more about (SP, please visit our (SP tutorial% # )ou want to learn more about P-P, please visit our P-P tutorial%

&PSchools8 $nline Certi#ication


.he per#ect solution #or pro#essionals who need to balance work, #amil), and career building% /ore than ;<<< certi#icates alread) issued4

/et >our )erti icate !


.he -./0 Certi#icate documents )our knowledge o# -./0% .he CSS Certi#icate documents )our knowledge o# advanced CSS% .he JavaScript Certi#icate documents )our knowledge o# JavaScript and -./0 E$/% .he jWuer) Certi#icate documents )our knowledge o# jWuer)% .he X/0 Certi#icate documents )our knowledge o# X/0, X/0 E$/ and XS0.% .he (SP Certi#icate documents )our knowledge o# (SP, SW0, and (E$% .he P-P Certi#icate documents )our knowledge o# P-P and SW0 2/)SW03%

Previous

Next Chapter

JavaScript $+amples
Previous Next Chapter

+asic JavaScript !xamples


&rite to the Eocument with JavaScript Change -./0 elements with JavaScript (n external JavaScript $+amples e+plained

JavaScript Statements, Comments and +locks


JavaScript statements% JavaScript blocks% Single line comments% /ultiple lines comments% Single line comment to prevent execution% /ultiple lines comment to prevent execution% $+amples e+plained

JavaScript Mariables
Eeclare a variable, assign a value to it, and displa) it $+amples e+plained

JavaScript Conditional # %%% !lse


# statement #%%%else statement Handom link Switch statement $+amples e+plained

JavaScript Popup +oxes

(lert box (lert box with line breaks Con#irm box Prompt box $+amples e+plained

JavaScript "unctions
Call a #unction "unction with an argument "unction with an argument : "unction that returns a value "unction with arguments, that returns a value $+amples e+plained

JavaScript 0oops
"or loop 0ooping through -./0 headers &hile loop Eo &hile loop +reak a loop +reak and continue a loop Gse a #or%%%in statement to loop through the elements o# an object $+amples e+plained

JavaScript !vents
(cting to the onclick event (cting to the onmouseover event $+amples e+plained

JavaScript !rror -andling


.he tr)%%%catch statement .he tr)%%%catch statement with a con#irm box .he onerror event $+amples e+plained

(dvanced JavaScript !xamples


Create a welcome cookie Simple timing

(nother simple timing .iming event in an in#inite loop .iming event in an in#inite loop 5 with a Stop button ( clock created with a timing event Create a direct instance o# an object Create an object constructor

Previous

Next Chapter

+asic JavaScript !xamples


1) <html> <body> <h1>My First Web Page</h1> <script type="text/javascript"> doc me!t"#rite$"<p>" % &ate$) % "</p>")' </script> </body> </html>

() <html> <body> <h1>My First Web Page</h1> <p id="demo">)his is a paragraph"</p> <script type="text/javascript"> doc me!t"get*leme!t+y,d$"demo")"i!!er-)M.=&ate$)' </script> </body> </html> /) <html>

<head> </head> <body> <script type="text/javascript" src="xxx"js"> </script> <p> )he act al script is i! a! exter!al script 0ile called "xxx"js"" </p> </body> </html>

JavaScript Statements, Comments and +locks


1) <html> <body> <script type="text/javascript"> doc me!t"#rite$"<h1>)his is a headi!g</h1>")' doc me!t"#rite$"<p>)his is a paragraph"</p>")' doc me!t"#rite$"<p>)his is a!other paragraph"</p>")' </script> </body> </html>

() <html> <body> <script type="text/javascript"> 1 doc me!t"#rite$"<h1>)his is a headi!g</h1>")' doc me!t"#rite$"<p>)his is a paragraph"</p>")' doc me!t"#rite$"<p>)his is a!other paragraph"</p>")' 2 </script>

</body> </html>

3) JavaScript Mariables
<html> <body> <script type="text/javascript"> var 0irst!ame' 0irst!ame="-ege"' doc me!t"#rite$0irst!ame)' doc me!t"#rite$"<br />")' 0irst!ame=")ove"' doc me!t"#rite$0irst!ame)' </script> <p>)he script above declares a variable3 assig!s a val e to it3 displays the val e3 cha!ges the val e3 a!d displays the val e agai!"</p> </body> </html>

JavaScript Conditional # %%% !lse


1) <html> <body> <script type="text/javascript"> var d = !e# &ate$)' var time = d"get-o rs$)' i0 $time < 14) 1 doc me!t"#rite$"<b>5ood mor!i!g</b>")'

2 </script> <p>)his example demo!strates the ,0 stateme!t"</p> <p>,0 the time o! yo r bro#ser is less tha! 143 yo #ill get a "5ood mor!i!g" greeti!g"</p> </body> </html> () <html> <body> <script type="text/javascript"> var d = !e# &ate$)' var time = d"get-o rs$)' i0 $time < 14) 1 doc me!t"#rite$"<b>5ood mor!i!g</b>")' 2 else 1 doc me!t"#rite$"<b>5ood day</b>")' 2 </script> <p> )his example demo!strates the ,0"""*lse stateme!t" </p> <p> ,0 the time o! yo r bro#ser is less tha! 143 yo #ill get a "5ood mor!i!g" greeti!g" 6ther#ise yo #ill get a "5ood day" greeti!g" </p> </body> </html>

7) <html>

<body> <script type="text/javascript"> var r=Math"ra!dom$)' i0 $r>4"8) 1 doc me!t"#rite$"<a hre0=9http://###"#/schools"com9>.ear! Web &evelopme!t;</a>")' 2 else 1 doc me!t"#rite$"<a hre0=9http://###"re0s!esdata"!o9><isit =e0s!es &ata;</a>")' 2 </script> </body> </html>

8) <html> <body> <script type="text/javascript"> var d=!e# &ate$)' var the&ay=d"get&ay$)' s#itch $the&ay) 1 case 8: doc me!t"#rite$"<b>Fi!ally Friday</b>")' brea>' case ?: doc me!t"#rite$"<b>@ per @at rday</b>")' brea>' case 4: doc me!t"#rite$"<b>@leepy @ !day</b>")' brea>' de0a lt: doc me!t"#rite$"<b>,9m really loo>i!g 0or#ard to this #ee>e!d;</b>")' 2 </script> <p>)his Aava@cript #ill ge!erate a di00ere!t greeti!g based o! #hat day it is" Bote that @ !day=43 Mo!day=13 ) esday=(3 etc"</p> </body> </html>

JavaScript Popup +oxes


1" Clert +ox <html> <head> <script type="text/javascript"> 0 !ctio! sho#Dalert$) 1 alert$"-ello; , am a! alert box;")' 2 </script> </head> <body> <i!p t type="b tto!" o!clic>="sho#Dalert$)" val e="@ho# alert box" /> </body> </html>

Clert box #ith li!e brea>s


<html> <head> <script type="text/javascript"> 0 !ctio! dispDalert$) 1 alert$"-ello agai!; )his is ho# #e" % 9E!9 % "add li!e brea>s to a! alert box;")' 2 </script> </head> <body> <i!p t type="b tto!" o!clic>="dispDalert$)" val e="&isplay alert box" /> </body> </html>

Fo!0irm +ox
<html> <head> <script type="text/javascript"> 0 !ctio! sho#Dco!0irm$) 1 var r=co!0irm$"Press a b tto!;")' i0 $r==tr e) 1 alert$"Go pressed 6H;")' 2 else 1 alert$"Go pressed Fa!cel;")' 2 2 </script> </head> <body> <i!p t type="b tto!" o!clic>="sho#Dco!0irm$)" val e="@ho# a co!0irm box" /> </body> </html>

Prompt +ox
<html> <head> <script type="text/javascript"> 0 !ctio! sho#Dprompt$) 1 var !ame=prompt$"Please e!ter yo r !ame"3"-arry Potter")' i0 $!ame;=! ll II !ame;="") 1 doc me!t"#rite$"-ello " % !ame % "; -o# are yo todayJ")' 2 2 </script> </head> <body>

<i!p t type="b tto!" o!clic>="sho#Dprompt$)" val e="@ho# prompt box" /> </body> </html>

JavaScript "unctions

Fall a F !ctio!

<html> <head> <script type="text/javascript"> 0 !ctio! displaymessage$) 1 alert$"-ello World;")' 2 </script> </head> <body> <0orm> <i!p t type="b tto!" val e="Flic> me;" o!clic>="displaymessage$)" /> </0orm> <p>+y pressi!g the b tto! above3 a 0 !ctio! #ill be called" )he 0 !ctio! #ill alert a message"</p> </body> </html>

F !ctio! #ith a! arg me!t


<html> <head>

<script type="text/javascript"> 0 !ctio! my0 !ctio!$txt) 1 alert$txt)' 2 </script> </head> <body> <0orm> <i!p t type="b tto!" o!clic>="my0 !ctio!$9-ello9)" val e="Fall 0 !ctio!"> </0orm> <p>+y pressi!g the b tto! above3 a 0 !ctio! #ill be called #ith "-ello" as a parameter" )he 0 !ctio! #ill alert the parameter"</p> </body> </html>

F !ctio! #ith a! arg me!t (


<html> <head> <script type="text/javascript"> 0 !ctio! my0 !ctio!$txt) 1 alert$txt)' 2 </script> </head> <body> <0orm> <i!p t type="b tto!" o!clic>="my0 !ctio!$95ood Mor!i!g;9)" val e=",! the Mor!i!g"> <i!p t type="b tto!" o!clic>="my0 !ctio!$95ood *ve!i!g;9)" val e=",! the *ve!i!g"> </0orm>

<p> Whe! yo clic> o! o!e o0 the b tto!s3 a 0 !ctio! #ill be called" )he 0 !ctio! #ill alert the arg me!t that is passed to it" </p> </body> </html>

F !ctio! that ret r! a val e


<html> <head> <script type="text/javascript"> 0 !ctio! myF !ctio!$) 1 ret r! $"-ello #orld;")' 2 </script> </head> <body> <script type="text/javascript"> doc me!t"#rite$myF !ctio!$)) </script> </body> </html>

F !ctio! #ith arg me!ts a!d ret r! a val e


<html> <head> <script type="text/javascript"> 0 !ctio! prod ct$a3b) 1 ret r! aKb' 2 </script> </head> <body>

<script type="text/javascript"> doc me!t"#rite$prod ct$73/))' </script> <p>)he script i! the body sectio! calls a 0 !ctio! #ith t#o parameters $7 a!d /)"</p> <p>)he 0 !ctio! #ill ret r! the prod ct o0 these t#o parameters"</p> </body> </html>

JavaScript 0oops

For loop
<html> <body> <script type="text/javascript"> var i=4' 0or $i=4'i<=8'i%%) 1 doc me!t"#rite$")he ! mber is " % i)' doc me!t"#rite$"<br />")' 2 </script> <p>*xpla!atio!:</p> <p>)his 0or loop starts #ith i=4"</p> <p>Cs lo!g as <b>i</b> is less tha!3 or eL al to 83 the loop #ill co!ti! e to r !"</p> <p><b>i</b> #ill i!crease by 1 each time the loop r !s"</p> </body> </html>

.oopi!g #ith -)M. -eaders

<html> <body>

<script type="text/javascript"> 0or $i = 1' i <= ?' i%%) 1 doc me!t"#rite$"<h" % i % ">)his is headi!g " % i)' doc me!t"#rite$"</h" % i % ">")' 2 </script> </body> </html>

While .oop
<html> <body> <script type="text/javascript"> i=4' #hile $i<=8) 1 doc me!t"#rite$")he ! mber is " % i)' doc me!t"#rite$"<br />")' i%%' 2 </script> <p>*xpla!atio!:</p> <p><b>i</b> is eL al to 4"</p> <p>While <b>i</b> is less tha! 3 or eL al to3 83 the loop #ill co!ti! e to r !"</p> <p><b>i</b> #ill i!crease by 1 each time the loop r !s"</p> </body> </html>

&o #hile .oop


<html> <body>

<script type="text/javascript"> i = 4' do 1 doc me!t"#rite$")he ! mber is " % i)' doc me!t"#rite$"<br />")' i%%' 2 #hile $i <= 8) </script> <p>*xpla!atio!:</p> <p><b>i</b> eL al to 4"</p> <p>)he loop #ill r !</p> <p><b>i</b> #ill i!crease by 1 each time the loop r !s"</p> <p>While <b>i</b> is less tha! 3 or eL al to3 83 the loop #ill co!ti! e to r !"</p> </body> </html>

+rea>i!g a .oop
<html> <body> <script type="text/javascript"> var i=4' 0or $i=4'i<=14'i%%) 1 i0 $i==/) 1 brea>' 2 doc me!t"#rite$")he ! mber is " % i)' doc me!t"#rite$"<br />")' 2 </script> <p>*xpla!atio!: )he loop #ill brea> #he! i=/"</p> </body> </html>

+rea> I Fo!ti! e a .oop


<html> <body> <script type="text/javascript"> var i=4' 0or $i=4'i<=14'i%%) 1 i0 $i==/) 1 co!ti! e' 2 doc me!t"#rite$")he ! mber is " % i)' doc me!t"#rite$"<br />")' 2 </script> <p>*xpla!atio!: )he loop #ill brea> the c rre!t loop a!d co!ti! e #ith the !ext val e #he! i=/"</p> </body> </html>

For each .oop


<html> <body> <script type="text/javascript"> var perso!=10!ame:"Aoh!"3l!ame:"&oe"3age:(82' 0or $x i! perso!) 1 doc me!t"#rite$perso!MxN % " ")' 2 </script> </body> </html>

JavaScript !vents

(cting to the $nClick event


<html> <head> <script type="text/javascript"> 0 !ctio! display&ate$) 1 doc me!t"get*leme!t+y,d$"demo")"i!!er-)M.=&ate$)' 2 </script> </head> <body> <h1>My First Web Page</h1> <p id="demo">)his is a paragraph"</p> <b tto! type="b tto!" o!clic>="display&ate$)">&isplay &ate</b tto!> </body> </html>

Mo se6ver *ve!t
<html> <head> <script type="text/javascript"> 0 !ctio! #rite)ext$txt) 1 doc me!t"get*leme!t+y,d$"desc")"i!!er-)M.=txt' 2 </script> </head> <body> <img src ="pla!ets"gi0" #idth ="178" height ="1(?" alt="Pla!ets" semap="Opla!etmap" />

<map !ame="pla!etmap"> <area shape ="rect" coords ="4343P(31(?" o!mo seover="#rite)ext$9)he @ ! a!d the gas gia!t pla!ets li>e A piter are by 0ar the largest objects i! o r @olar @ystem"9)" hre0 ="s !"htm" target ="Dbla!>" alt="@ !" /> <area shape ="circle" coords ="Q438P3/" o!mo seover="#rite)ext$9)he pla!et Merc ry is very di00ic lt to st dy 0rom the *arth beca se it is al#ays so close to the @ !"9)" hre0 ="merc r"htm" target ="Dbla!>" alt="Merc ry" /> <area shape ="circle" coords ="1(738P3P" o!mo seover="#rite)ext$9R!til the 1Q?4s3 <e! s #as o0te! co!sidered a t#i! sister to the *arth beca se <e! s is the !earest pla!et to s3 a!d beca se the t#o pla!ets seem to share ma!y characteristics"9)" hre0 ="ve! s"htm" target ="Dbla!>" alt="<e! s" /> </map> <p id="desc">Mo se over the s ! a!d the pla!ets a!d see the di00ere!t descriptio!s"</p> </body> </html>

JavaScript !rror -andling

)ry Fatch
<html> <head> <script type="text/javascript"> var txt=""' 0 !ctio! message$) 1 try 1 adddlert$"Welcome g est;")' 2 catch$err) 1

txt=")here #as a! error o! this page"E!E!"' txt%="*rror descriptio!: " % err"descriptio! % "E!E!"' txt%="Flic> 6H to co!ti! e"E!E!"' alert$txt)' 2 2 </script> </head> <body> <i!p t type="b tto!" val e="<ie# message" o!clic>="message$)" /> </body>

)ry Fatch #ith Fo!0irm +ox

<html> <head> <script type="text/javascript"> var txt=""' 0 !ctio! message$) 1 try 1 adddlert$"Welcome g est;")' 2 catch$err) 1 txt=")here #as a! error o! this page"E!E!"' txt%="Flic> 6H to co!ti! e vie#i!g this page3E!"' txt%="or Fa!cel to ret r! to the home page"E!E!"' i0$;co!0irm$txt)) 1 doc me!t"locatio!"hre0="http://###"#/schools"com/"' 2 2 2 </script> </head> <body>

6!*rror *ve!t
<html> <head> <script type="text/javascript"> o!error=ha!dle*rr' var txt=""' 0 !ctio! ha!dle*rr$msg3 rl3l) 1 txt=")here #as a! error o! this page"E!E!"' txt%="*rror: " % msg % "E!"' txt%="R=.: " % rl % "E!"' txt%=".i!e: " % l % "E!E!"' txt%="Flic> 6H to co!ti! e"E!E!"' alert$txt)' ret r! tr e' 2 0 !ctio! message$) 1 adddlert$"Welcome g est;")' 2 </script> </head> <body> <i!p t type="b tto!" val e="<ie# message" o!clic>="message$)" /> </body> </html>

(dvanced JavaScript !xamples

Create welcome Cookie


<html> <head> <script type="text/javascript"> 0 !ctio! getFoo>ie$cD!ame)

1 var i3x3y3C==coo>ies=doc me!t"coo>ie"split$"'")' 0or $i=4'i<C==coo>ies"le!gth'i%%) 1 x=C==coo>iesMiN"s bstr$43C==coo>iesMiN"i!dex60$"="))' y=C==coo>iesMiN"s bstr$C==coo>iesMiN"i!dex60$"=")%1)' x=x"replace$/SEs%TEs%U/g3"")' i0 $x==cD!ame) 1 ret r! !escape$y)' 2 2 2 0 !ctio! setFoo>ie$cD!ame3val e3exdays) 1 var exdate=!e# &ate$)' exdate"set&ate$exdate"get&ate$) % exdays)' var cDval e=escape$val e) % $$exdays==! ll) J "" : "' expires="%exdate"toR)F@tri!g$))' doc me!t"coo>ie=cD!ame % "=" % cDval e' 2 0 !ctio! chec>Foo>ie$) 1 var ser!ame=getFoo>ie$" ser!ame")' i0 $ ser!ame;=! ll II ser!ame;="") 1 alert$"Welcome agai! " % ser!ame)' 2 else

1 ser!ame=prompt$"Please e!ter yo r !ame:"3"")' i0 $ ser!ame;=! ll II ser!ame;="") 1 setFoo>ie$" ser!ame"3 ser!ame3/?8)' 2 2 2 </script> </head> <body o!load="chec>Foo>ie$)"> </body> </html>

Simple Timig
<html> <head> <script type="text/javascript"> 0 !ctio! timeMsg$) 1 var t=set)imeo t$"alertMsg$)"3/444)' 2 0 !ctio! alertMsg$) 1 alert$"-ello")' 2 </script> </head> <body>

<0orm> <i!p t type="b tto!" val e="&isplay alert box i! / seco!ds" o!Flic>="timeMsg$)" /> </0orm> </body> </html>

Timing event in an Infinite Loop


<html> <head> <script type="text/javascript"> var c=4' var t' var timerDisDo!=4' 0 !ctio! timedFo !t$) 1 doc me!t"get*leme!t+y,d$9txt9)"val e=c' c=c%1' t=set)imeo t$"timedFo !t$)"31444)' 2 0 !ctio! do)imer$) 1 i0 $;timerDisDo!) 1 timerDisDo!=1' timedFo !t$)' 2 2

</script> </head> <body> <0orm> <i!p t type="b tto!" val e="@tart co !t;" o!Flic>="do)imer$)"> <i!p t type="text" id="txt"> </0orm> <p>Flic> o! the b tto! above" )he i!p t 0ield #ill co !t 0orever3 starti!g at 4"</p> </body> </html>

Timing event in an Infinite Loop with Stop Button


<html> <head> <script type="text/javascript"> var c=4' var t' var timerDisDo!=4' 0 !ctio! timedFo !t$) 1 doc me!t"get*leme!t+y,d$9txt9)"val e=c' c=c%1' t=set)imeo t$"timedFo !t$)"31444)' 2 0 !ctio! do)imer$) 1 i0 $;timerDisDo!)

1 timerDisDo!=1' timedFo !t$)' 2 2 0 !ctio! stopFo !t$) 1 clear)imeo t$t)' timerDisDo!=4' 2 </script> </head> <body> <0orm> <i!p t type="b tto!" val e="@tart co !t;" o!clic>="do)imer$)" /> <i!p t type="text" id="txt" /> <i!p t type="b tto!" val e="@top co !t;" o!clic>="stopFo !t$)" /> </0orm> <p> Flic> o! the "@tart co !t;" b tto! above to start the timer" )he i!p t 0ield #ill co !t 0orever3 starti!g at 4" Flic> o! the "@top co !t;" b tto! to stop the co !ti!g" Flic> o! the "@tart co !t;" b tto! to start the timer agai!" </p> </body> </html>

A clock created with Timing Event


<html> <head> <script type="text/javascript"> 0 !ctio! start)ime$) 1 var today=!e# &ate$)' var h=today"get-o rs$)' var m=today"getMi! tes$)' var s=today"get@eco!ds$)' // add a Vero i! 0ro!t o0 ! mbers<14 m=chec>)ime$m)' s=chec>)ime$s)' doc me!t"get*leme!t+y,d$9txt9)"i!!er-)M.=h%":"%m%":"%s' t=set)imeo t$9start)ime$)93844)' 2 0 !ctio! chec>)ime$i) 1 i0 $i<14) 1 i="4" % i' 2 ret r! i' 2 </script> </head>

<body o!load="start)ime$)"> <div id="txt"></div> </body> </html>

Create a Direct In tance of !"#ect

<html> <body> <script type="text/javascript"> perso!6bj=10irst!ame:"Aoh!"3last!ame:"&oe"3age:843eyecolor:"bl e"2 doc me!t"#rite$perso!6bj"0irst!ame % " is " % perso!6bj"age % " years old"")' </script> </body> </html>

Freate a! 6bject co!str ctor


<html> <body> <script type="text/javascript"> 0 !ctio! perso!$0irst!ame3last!ame3age3eyecolor) 1 this"0irst!ame=0irst!ame' this"last!ame=last!ame' this"age=age' this"eyecolor=eyecolor' 2 myFather=!e# perso!$"Aoh!"3"&oe"3843"bl e")'

doc me!t"#rite$myFather"0irst!ame % " is " % myFather"age % " years old"")' </script> </body> </html>

String $bject

$eturn Length of the String


<html> <body> <script type="text/javascript"> var txt = "-ello World;"' doc me!t"#rite$txt"le!gth)' </script> </body> </html>

St%le String
<html> <body> <script type="text/javascript"> var txt = "-ello World;"' doc me!t"#rite$"<p>+ig: " % txt"big$) % "</p>")' doc me!t"#rite$"<p>@mall: " % txt"small$) % "</p>")' doc me!t"#rite$"<p>+old: " % txt"bold$) % "</p>")' doc me!t"#rite$"<p>,talic: " % txt"italics$) % "</p>")' doc me!t"#rite$"<p>Fixed: " % txt"0ixed$) % "</p>")' doc me!t"#rite$"<p>@tri>e: " % txt"stri>e$) % "</p>")' doc me!t"#rite$"<p>Fo!tcolor: " % txt"0o!tcolor$"gree!") % "</p>")'

doc me!t"#rite$"<p>Fo!tsiVe: " % txt"0o!tsiVe$?) % "</p>")' doc me!t"#rite$"<p>@ bscript: " % txt"s b$) % "</p>")' doc me!t"#rite$"<p>@ perscript: " % txt"s p$) % "</p>")' doc me!t"#rite$"<p>.i!>: " % txt"li!>$"http://###"#/schools"com") % "</p>")' doc me!t"#rite$"<p>+li!>: " % txt"bli!>$) % " $does !ot #or> i! ,*3 Fhrome3 or @a0ari)</p>")' </script> </body> </html>

$turn the po ition of the fir t occurrence of the String & inde'!f()

<html> <body> <script type="text/javascript"> var str="-ello #orld;"' doc me!t"#rite$str"i!dex60$"d") % "<br />")' doc me!t"#rite$str"i!dex60$"W6=.&") % "<br />")' doc me!t"#rite$str"i!dex60$"#orld"))' </script> </body> </html>

Search the te't in a String ) return the te't if found & match()
<html> <body> <script type="text/javascript"> var str="-ello #orld;"' doc me!t"#rite$str"match$"#orld") % "<br />")' doc me!t"#rite$str"match$"World") % "<br />")' doc me!t"#rite$str"match$"#orlld") % "<br />")' doc me!t"#rite$str"match$"#orld;"))' </script>

</body> </html>

$eplace the character in a String & replace()


<html> <body> <script type="text/javascript"> var str="<isit Microso0t;"' doc me!t"#rite$str"replace$"Microso0t"3"W/@chools"))' </script> </body> </html>

Eate $bject
* e Date() returen toda% Date ) Time
<html> <body> <script type="text/javascript"> var d=!e# &ate$)' doc me!t"#rite$d)' </script> </body> </html>

* e getTime to calculate the %ear


<html> <body>

ice +,-.

<script type="text/javascript"> var d=!e# &ate$)' doc me!t"#rite$d"get)ime$) % " milliseco!ds si!ce 1QW4/41/41")' </script> </body> </html>

Rse setF llGear to speci0ic &ate <html> <body> <script type="text/javascript"> var d = !e# &ate$)' d"setF llGear$1QQ(3143/)' doc me!t"#rite$d)' </script> </body> </html>

Rse toR)F@tri!g$) to co!vert today9s date $accordi!g to R)F) to a stri!g


<html> <body> <script type="text/javascript"> var d=!e# &ate$)' doc me!t"#rite$"6rigi!al 0orm: ")' doc me!t"#rite$d % "<br />")' doc me!t"#rite$")o stri!g $ !iversal time): ")' doc me!t"#rite$d"toR)F@tri!g$))' </script> </body>

</html>

Rse get&ay$) a!d a! array to #rite a #ee>day3 a!d !ot j st a ! mber


<html> <body> <script type="text/javascript"> var d=!e# &ate$)' var #ee>day=!e# Crray$W)' #ee>dayM4N="@ !day"' #ee>dayM1N="Mo!day"' #ee>dayM(N=") esday"' #ee>dayM/N="Wed!esday"' #ee>dayM7N=")h rsday"' #ee>dayM8N="Friday"' #ee>dayM?N="@at rday"' doc me!t"#rite$")oday is " % #ee>dayMd"get&ay$)N)' </script> </body> </html>

&isplay a cloc>

<html> <head> <script type="text/javascript"> 0 !ctio! start)ime$) 1 var today=!e# &ate$)' var h=today"get-o rs$)' var m=today"getMi! tes$)' var s=today"get@eco!ds$)'

// add a Vero i! 0ro!t o0 ! mbers<14 m=chec>)ime$m)' s=chec>)ime$s)' doc me!t"get*leme!t+y,d$9txt9)"i!!er-)M.=h%":"%m%":"%s' t=set)imeo t$9start)ime$)93844)' 2 0 !ctio! chec>)ime$i) 1 i0 $i<14) 1 i="4" % i' 2 ret r! i' 2 </script> </head> <body o!load="start)ime$)"> <div id="txt"></div> </body> </html>

(rra) $bject

Create an arra%

<html> <body> <script type="text/javascript"> var i'

var mycars = !e# Crray$)' mycarsM4N = "@aab"' mycarsM1N = "<olvo"' mycarsM(N = "+MW"' 0or $i=4'i<mycars"le!gth'i%%) 1 doc me!t"#rite$mycarsMiN % "<br />")' 2 </script> </body> </html>

Aoi! t#o arrays X co!cat$)


<html> <body> <script type="text/javascript"> var pare!ts = M"Aa!i"3 ")ove"N' var childre! = M"Fecilie"3 ".o!e"N' var 0amily = pare!ts"co!cat$childre!)' doc me!t"#rite$0amily)' </script> </body> </html>

Aoi! three arrays X co!cat$)

<html> <body> <script type="text/javascript"> var pare!ts = M"Aa!i"3 ")ove"N' var brothers = M"@tale"3 "Hai Aim"3 "+orge"N' var childre! = M"Fecilie"3 ".o!e"N' var 0amily = pare!ts"co!cat$brothers3 childre!)'

doc me!t"#rite$0amily)' </script> </body> </html>

Aoi! all eleme!ts o0 a! array i!to a stri!g X joi!$)

<html> <body> <script type="text/javascript"> var 0r its = M"+a!a!a"3 "6ra!ge"3 "Cpple"3 "Ma!go"N' doc me!t"#rite$0r its"joi!$) % "<br />")' doc me!t"#rite$0r its"joi!$"%") % "<br />")' doc me!t"#rite$0r its"joi!$" a!d "))' </script> </body> </html>

=emove the last eleme!t o0 a! array X pop$)


<html> <body> <script type="text/javascript"> var 0r its = M"+a!a!a"3 "6ra!ge"3 "Cpple"3 "Ma!go"N' doc me!t"#rite$0r its"pop$) % "<br />")' doc me!t"#rite$0r its % "<br />")' doc me!t"#rite$0r its"pop$) % "<br />")' doc me!t"#rite$0r its)' </script> </body>

</html>

Cdd !e# eleme!ts to the e!d o0 a! array X p sh$)

<html> <body> <script type="text/javascript"> var 0r its = M"+a!a!a"3 "6ra!ge"3 "Cpple"3 "Ma!go"N' doc me!t"#rite$0r its"p sh$"Hi#i") % "<br />")' doc me!t"#rite$0r its"p sh$".emo!"3"Pi!eapple") % "<br />")' doc me!t"#rite$0r its)' </script> </body> </html>

=everse the order o0 the eleme!ts i! a! array X reverse$)


<html> <body> <script type="text/javascript"> var 0r its = M"+a!a!a"3 "6ra!ge"3 "Cpple"3 "Ma!go"N' doc me!t"#rite$0r its"reverse$))' </script> </body> </html>

=emove the 0irst eleme!t o0 a! array X shi0t$)

<html> <body> <script type="text/javascript"> var 0r its = M"+a!a!a"3 "6ra!ge"3 "Cpple"3 "Ma!go"N' doc me!t"#rite$0r its"shi0t$) % "<br />")' doc me!t"#rite$0r its % "<br />")' doc me!t"#rite$0r its"shi0t$) % "<br />")' doc me!t"#rite$0r its)' </script> </body> </html>

@elect eleme!ts 0rom a! array X slice$)

<html> <body> <script type="text/javascript"> var 0r its = M"+a!a!a"3 "6ra!ge"3 "Cpple"3 "Ma!go"N' doc me!t"#rite$0r its"slice$431) % "<br />")' doc me!t"#rite$0r its"slice$1) % "<br />")' doc me!t"#rite$0r its"slice$X() % "<br />")' doc me!t"#rite$0r its)' </script> </body> </html>

@ort a! array $alphabetically a!d asce!di!g) X sort$)

<html> <body> <script type="text/javascript"> var 0r its = M"+a!a!a"3 "6ra!ge"3 "Cpple"3 "Ma!go"N' doc me!t"#rite$0r its"sort$))' </script> </body> </html>

@ort ! mbers $! merically a!d asce!di!g) X sort$)

<html> <body> <script type="text/javascript"> 0 !ctio! sortB mber$a3 b) 1 ret r! a X b' 2 var ! = M"14"3 "8"3 "74"3 "(8"3 "144"3 "1"N' doc me!t"#rite$!"sort$sortB mber))' </script> </body> </html>

@ort ! mbers $! merically a!d desce!di!g) X sort$)


<html> <body> <script type="text/javascript">

0 !ctio! sortB mber$a3 b) 1 ret r! b X a' 2 var ! = M"14"3 "8"3 "74"3 "(8"3 "144"3 "1"N' doc me!t"#rite$!"sort$sortB mber))' </script> </body> </html>

Cdd a! eleme!t to positio! ( i! a! array X splice$)

<html> <body> <script type="text/javascript"> var 0r its = M"+a!a!a"3 "6ra!ge"3 "Cpple"3 "Ma!go"N' doc me!t"#rite$"=emoved: " % 0r its"splice$(343".emo!") % "<br />")' doc me!t"#rite$0r its)' </script> </body> </html>

Fo!vert a! array to a stri!g X to@tri!g$)


<html> <body> <script type="text/javascript"> var 0r its = M"+a!a!a"3 "6ra!ge"3 "Cpple"3 "Ma!go"N' doc me!t"#rite$0r its"to@tri!g$))' </script>

</body> </html>

Cdd !e# eleme!ts to the begi!!i!g o0 a! array X !shi0t$)

<html> <body> <script type="text/javascript"> var 0r its = M"+a!a!a"3 "6ra!ge"3 "Cpple"3 "Ma!go"N' doc me!t"#rite$0r its" !shi0t$"Hi#i") % "<br />")' doc me!t"#rite$0r its" !shi0t$".emo!"3"Pi!eapple") % "<br />")' doc me!t"#rite$0r its)' </script> <p><b>Bote:</b> )he !shi0t$) method does !ot #or> properly i! ,!ter!et *xplorer3 it o!ly ret r!s !de0i!ed;</p> </body> </html>

+oolean $bject
Fhec> +oolea! val e
<html> <body> <script type="text/javascript"> var b1=!e# +oolea!$ 4)' var b(=!e# +oolea!$1)' var b/=!e# +oolea!$"")' var b7=!e# +oolea!$! ll)' var b8=!e# +oolea!$BaB)' var b?=!e# +oolea!$"0alse")' doc me!t"#rite$"4 is boolea! "% b1 %"<br />")' doc me!t"#rite$"1 is boolea! "% b( %"<br />")'

doc me!t"#rite$"C! empty stri!g is boolea! "% b/ % "<br />")' doc me!t"#rite$"! ll is boolea! "% b7% "<br />")' doc me!t"#rite$"BaB is boolea! "% b8 %"<br />")' doc me!t"#rite$")he stri!g 90alse9 is boolea! "% b? %"<br />")' </script> </body> </html>

/ath $bject
Rse ro !d$) to ro !d a ! mber
<html> <body> <script type="text/javascript"> doc doc doc doc doc me!t"#rite$Math"ro me!t"#rite$Math"ro me!t"#rite$Math"ro me!t"#rite$Math"ro me!t"#rite$Math"ro !d$4"?4) % "<br />")' !d$4"84) % "<br />")' !d$4"7Q) % "<br />")' !d$X7"74) % "<br />")' !d$X7"?4))'

</script> </body> </html>

Rse ra!dom$) to ret r! a ra!dom ! mber bet#ee! 4 a!d 1


<html> <body> <script type="text/javascript"> //ret r! a ra!dom ! mber bet#ee! 4 a!d 1 doc me!t"#rite$Math"ra!dom$) % "<br />")' //ret r! a ra!dom i!teger bet#ee! 4 a!d 14 doc me!t"#rite$Math"0loor$Math"ra!dom$)K11))' </script>

</body> </html>

Rse max$) to ret r! the ! mber #ith the highest val e o0 t#o speci0ied ! mbers

<html> <body> <script type="text/javascript"> doc me!t"#rite$Math"max$8314) % "<br />")' doc me!t"#rite$Math"max$431843/43(43/P) % "<br />")' doc me!t"#rite$Math"max$X8314) % "<br />")' doc me!t"#rite$Math"max$X83X14) % "<br />")' doc me!t"#rite$Math"max$1"83("8))' </script> </body> </html>

<html> <body> <script type="text/javascript"> doc doc doc doc doc me!t"#rite$Math"mi!$8314) % "<br />")' me!t"#rite$Math"mi!$431843/43(43/P) % "<br />")' me!t"#rite$Math"mi!$X8314) % "<br />")' me!t"#rite$Math"mi!$X83X14) % "<br />")' me!t"#rite$Math"mi!$1"83("8))'

</script> </body> </html>

Fo!vert Felsi s to Fahre!heit

<html> <head> <script type="text/javascript"> 0 !ctio! co!vert$degree) 1 i0 $degree=="F") 1 F=doc me!t"get*leme!t+y,d$"c")"val e K Q / 8 % /(' doc me!t"get*leme!t+y,d$"0")"val e=Math"ro !d$F)' 2 else 1 F=$doc me!t"get*leme!t+y,d$"0")"val e X/() K 8 / Q' doc me!t"get*leme!t+y,d$"c")"val e=Math"ro !d$F)' 2 2 </script> </head> <body> <p></p><b>,!sert a ! mber i!to o!e o0 the i!p t 0ields belo#:</b></p> <0orm> <i!p t id="c" !ame="c" o!>ey p="co!vert$9F9)"> degrees Felsi s<br /> eL als<br /> <i!p t id="0" !ame="0" o!>ey p="co!vert$9F9)"> degrees Fahre!heit </0orm> <p>Bote that the <b>Math"ro !d$)</b> method is sed3 so that the res lt #ill be ret r!ed as a! i!teger"</p> </body> </html>

Oeneral
Rse a 0or"""i! stateme!t to loop thro gh the eleme!ts o0 a! object
<html> <body> <script type="text/javascript"> var perso!=10!ame:"Aoh!"3l!ame:"&oe"3age:(82' 0or $x i! perso!) 1

doc me!t"#rite$perso!MxN % " ")' 2 </script> </body> </html>

JavaScript -b<ects !xamples


Previous
!xamples o# using the built5in JavaScript objects%

Next Chapter

String $bject
Heturn the length o# a string St)le strings Heturn the position o# the #irst occurrence o# a text in a string 5 index$#23 Search #or a text in a string and return the text i# #ound 5 match23 Heplace characters in a string 5 replace23 /ore String object examples in our JavaScript re#erence%

Eate $bject
Gse Eate23 to return toda)8s date and time Gse get.ime23 to calculate the )ears since =>@< Gse set"ull'ear23 to set a speci#ic date Gse toG.CString23 to convert toda)8s date 2according to G.C3 to a string Gse getEa)23 and an arra) to write a weekda), and not just a number Eispla) a clock /ore Eate object examples in our JavaScript re#erence%

(rra) $bject
Create an arra) Join two arra)s 5 concat23 Join three arra)s 5 concat23 Join all elements o# an arra) into a string 5 join23 Hemove the last element o# an arra) 5 pop23 (dd new elements to the end o# an arra) 5 push23 Heverse the order o# the elements in an arra) 5 reverse23 Hemove the #irst element o# an arra) 5 shi#t23 Select elements #rom an arra) 5 slice23 Sort an arra) 2alphabeticall) and ascending3 5 sort23 Sort numbers 2numericall) and ascending3 5 sort23 Sort numbers 2numericall) and descending3 5 sort23 (dd an element to position : in an arra) 5 splice23 Convert an arra) to a string 5 toString23 (dd new elements to the beginning o# an arra) 5 unshi#t23 /ore (rra) object examples in our JavaScript re#erence%

+oolean $bject
Check +oolean value /ore +oolean object examples in our JavaScript re#erence%

/ath $bject
Gse round23 to round a number Gse random23 to return a random number between < and = Gse max23 to return the number with the highest value o# two speci#ied numbers Gse min23 to return the number with the lowest value o# two speci#ied numbers Convert Celsius to "ahrenheit

Oeneral
Gse a #or%%%in statement to loop through the elements o# an object /ore /ath object examples in our JavaScript re#erence%

Previous

Next Chapter

JavaScript %rowser -b<ects !xamples


Previous
!xamples o# using JavaScript to access and manipulate the +rowser objects%

Next Chapter

&indow $bject
Eispla) an alert box Eispla) an alert box with line5breaks Eispla) a con#irm box, and alert what the visitor clicked Eispla) a prompt box Create a pop5up window $pen a new window when clicking on a button $pen a new window and control its appearance $pen multiple new windows (ssure that the new window does N$. get #ocus 2send it to the background3 (ssure that the new window O!.S #ocus Close the new window Checks whether the new window has been closed or not Heturn the name o# the new window &rite some text to the source 2parent3 window /ove the new window relative to its current position /ove the new window to the speci#ied position Print the current page Hesi?e a window b) the speci#ied pixels Hesi?e a window to a speci#ied si?e Scroll the content b) the speci#ied number o# pixels Scroll the content to a speci#ied position ( simple timing Set and stop a timer with set.imeout23 and clear.imeout23 Set and stop a timer with set nterval23 and clear nterval23 /ore &indow object examples in our JavaScript re#erence%

Navigator $bject
(ll details about the visitor8s browser /ore Navigator object examples in our JavaScript re#erence%

Screen $bject
(ll details about the visitor8s screen

/ore Screen object examples in our JavaScript re#erence%

-istor) $bject
Heturn the number o# GH0s in the histor) list Create a back button on a page Create a #orward button on a page 0oad a speci#ic GH0 #rom the histor) list /ore -istor) object examples in our JavaScript re#erence%

0ocation $bject
Heturn the hostname and port o# the current GH0 Heturn the entire GH0 o# the current page Heturn the path name o# the current GH0 Heturn the protocol portion o# the current GH0 0oad a new document Heload the current document Heplace the current document +reak out o# a #rame /ore 0ocation object examples in our JavaScript re#erence%

Previous

Next Chapter

JavaScript HTML 1-M !xamples


Previous Next Chapter
!xamples o# using JavaScript to access and manipulate the -./0 E$/ objects%

Eocument $bject
&rite text to the output with document%write23 &rite #ormatted text to the output with document%write23 Heturn the number o# anchors in a document Heturn the inner-./0 o# the #irst anchor in a document Heturn the number o# #orms in a document Heturn the name o# the #irst #orm in a document Heturn the number o# images in a document Heturn the id o# the #irst image in a document Heturn the number o# links in a document Heturn the id o# the #irst link in a document Heturn all nameAvalue pairs o# cookies in a document Heturn the domain name o# the server that loaded the document

Heturn the date and time the document was last modi#ied Heturn the GH0 o# the document that loaded the current document Heturn the title o# a document Heturn the #ull GH0 o# a document $pen an output stream, and add some text $pen an output stream in a new window, and add some text Ei##erence between write23 and writeln23 (lert inner-./0 o# an element with a speci#ic E (lert the number o# elements with a speci#ic name (lert the number o# elements with a speci#ic tagname /ore Eocument object examples in our JavaScript re#erence%

(nchor $bject
Heturn and set the value o# the charset attribute o# a link Heturn the value o# the hre# attribute o# a link Heturn and set the value o# the hre#lang attribute o# a link Heturn the name o# an anchor Heturn the relationship between the current document and the linked document Change the target attribute o# a link Heturn the value o# the t)pe attribute o# a link /ore (nchor object examples in our JavaScript re#erence%

(rea $bject
Heturn Heturn Heturn Heturn Heturn Heturn Heturn Heturn Heturn Heturn Heturn Heturn the the the the the the the the the the the the alternate text #or an area in an image5map coordinates o# an area in an image5map anchor part o# the hre# attribute o# an area hostname,port #or an area in an image5map hostname #or an area in an image5map port #or an area in an image5map hre# o# an area in an image5map pathname #or an area in an image5map protocol #or an area in an image5map Iuer)string part o# the hre# attribute o# an area shape o# an area in an image5map value o# the target attribute #or an area in an image5map

/ore (rea object examples in our JavaScript re#erence%

+ase $bject
Heturn the base GH0 #or all relative GH0s on a page Heturn the base target #or all links on a page /ore +ase object examples in our JavaScript re#erence%

+utton $bject
Set a button to disabled when clicked Heturn the name o# a button

Heturn the t)pe o# a button Heturn the text displa)ed on a button Heturn the id o# the #orm a button belongs to /ore +utton object examples in our JavaScript re#erence%

"orm $bject
Heturn the value o# each element in a #orm Heturn the value o# the accept5charset attribute in a #orm Heturn the value o# the action attribute in a #orm Heturn the value o# the enct)pe attribute in a #orm Heturn the number o# elements in a #orm Heturn the method #or sending #orm data Heturn the name o# a #orm Heturn the value o# the target attribute in a #orm Heset a #orm Submit a #orm /ore "orm object examples in our JavaScript re#erence%

"rameA "rame $bjects


(lign an i#rame Change the background color o# the document contained in an i#rame Heturn the value o# the #rameborder attribute in an i#rame Hemove #rameborder o# an i#rame Change the height and width o# an i#rame Heturn the value o# the longdesc attribute in an i#rame Heturn the value o# the marginheight attribute in an i#rame Heturn the value o# the marginwidth attribute in an i#rame Heturn the value o# the name attribute in an i#rame Heturn and set the value o# the scrolling attribute in an i#rame Change the src attribute o# an i#rame /ore "rameA "rame object examples in our JavaScript re#erence%

mage $bject
(lign an image Heturn the alternate text o# an image (dd border to an image Change the height and width o# an image Set the hspace and vspace properties o# an image Heturn the value o# the longdesc attribute o# an image Create a link to a low5resolution version o# an image Heturn the name o# an image Change the src o# an image Heturn the value o# the usemap attribute o# a client5side image5map /ore mage object examples in our JavaScript re#erence%

!vent $bject

&hich mouse button was clicked1 &hat is the ke)code o# the ke) pressed1 &hat are the coordinates o# the cursor1 &hat are the coordinates o# the cursor, relative to the screen1 &as the shi#t ke) pressed1 &hich element was clicked1 &hich event t)pe occurred1

$ption and Select $bjects


Eisable and enable a dropdown list Oet the id o# the #orm that contains the dropdown list Oet the number o# options in the dropdown list .urn the dropdown list into a multiline list Select multiple options in a dropdown list (lert the selected option in a dropdown list (lert the index o# the selected option in a dropdown list Change the text o# the selected option Hemove options #rom a dropdown list

.able, .able-eader, .ableHow, .ableEata $bjects


Change the width o# a table border Change the cellPadding and cellSpacing o# a table Speci#) #rames o# a table Speci#) rules #or a table nner-./0 o# a row nner-./0 o# a cell Create a caption #or a table Eelete rows in a table (dd rows to a table (dd cells to a table row (lign the cell content in a table row Mertical align the cell content in a table row (lign the cell content in a single cell Mertical align the cell content in a single cell Change the content o# a table cell Change the colspan o# a table row

Previous

Next Chapter

JavaScript AuiC Test


Previous
'ou can test )our JavaScript skills with &PSchools8 Wui?%

Next Chapter

.he .est
.he test contains :< Iuestions and there is no time limit% .he test is not o##icial, it8s just a nice wa) to see how much )ou know, or don8t know, about JavaScript%

Count 'our Score


'ou will get = point #or each correct answer% (t the end o# the Wui?, )our total score will be displa)ed% /aximum score is :< points% Oood luck4 Start the JavaScript Wui?

Previous

Next Chapter

JavaScript and -./0 E$/ 2e erence


&PSchools -ome
.his section contains a complete re#erence o#

Next He#erence

(ll built5in JavaScript objects (ll browser objects (ll -./0 E$/ objects

JavaScript $bjects He#erence


.he re#erences describe the properties and methods o# each object, along with examples%

(rra) object +oolean object Eate object /ath object Number object String object Heg!xp object Olobal properties and #unctions

+rowser $bjects He#erence


.he re#erences describe the properties and methods o# each object, along with examples%

&indow object Navigator object Screen object -istor) object 0ocation object

-./0 E$/ $bjects He#erence


.he re#erences describe the properties and methods o# each object, along with examples%

Eocument object !vent object -./0!lement object (nchor object (rea object +ase object +od) object +utton object "orm object "rameA "rame object "rameset object mage object nput +utton object nput Checkbox object nput "ile object nput -idden object nput Password object nput Hadio object nput Heset object nput Submit object nput .ext object 0ink object /eta object $bject object $ption object Select object St)le object .able object td A th object tr object .extarea object

&PSchools -ome

Next He#erence

Você também pode gostar