Escolar Documentos
Profissional Documentos
Cultura Documentos
# )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
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
!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%
!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#&'
<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 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#&'
!xample
"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 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,
"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 !
!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>"&'
!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 !
!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
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
!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
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%
5 L A Q 66 55
!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
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
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
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&
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 !
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
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
(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%
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%
# 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%
!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 !
/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 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
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 !
/ore !xamples
0ooping through -./0 headings 0oop through the six di##erent -./0 headings%
Previous
Next Chapter
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 !
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
!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 !
!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 />"&'
Previous
Next Chapter
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#&'
!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,
/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%
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,
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
Next Chapter
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 !
Previous
Next Chapter
Next Chapter
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
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
&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
Previous
Next Chapter
Next Chapter
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,
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>
.he output o# the code above will be,
+(--C WC?-%0
Previous
Next Chapter
Next Chapter
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,
1;
.he #ollowing example uses the toGpperCase23 method o# the String object to convert a string to uppercase letters,
+(--C WC?-%0
Previous
Next Chapter
Next Chapter
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%
%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,
today d1 = d; = d< =
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 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
Next Chapter
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
&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,
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"'
:,
(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
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
.he re#erence contains a brie# description and examples o# use #or each propert) and method4
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
Next Chapter
/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#
/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,
/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,
8
.he #ollowing example uses the random23 method o# the /ath object to return a random number between < and =,
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 =<,
Previous
Next Chapter
Next Chapter
&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,
9isit W</chools
Try it yoursel !
!xample :
Eo a global search #or 7is7,
var patt1=/is/g'
.he marked text below shows where the expression gets a match,
!xample P
Eo a global, case5insensitive search #or 7is7,
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
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%
!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>"'
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
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
!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
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
Next Chapter
JavaScript can be executed in time5intervals% .his is called timing events%
8 9 10 11 12
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%
!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 !
!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 !
!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
Next Chapter
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,
.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#&'
Cbj= e" Cbject#&' Cbj!2irst ame=".oh "' Cbj!last ame="%oe"' Cbj!age=8A' Cbj!eyecolor="blue"'
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,
.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
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%
(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%
Previous
Next Chapter
JavaScript $+amples
Previous Next Chapter
JavaScript Mariables
Eeclare a variable, assign a value to it, and displa) it $+amples e+plained
(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
(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
() <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>
() <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>
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>
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>
<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>
<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>
<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>
<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>
<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>
JavaScript !vents
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>
)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>
<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>
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>
</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>
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>
<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>
doc me!t"#rite$myFather"0irst!ame % " is " % myFather"age % " years old"")' </script> </body> </html>
String $bject
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>
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>
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>
</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%
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>
<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!)'
<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>
</html>
<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>
<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>
<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>
<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>
<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>
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>
<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>
</body> </html>
<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))'
</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))'
<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
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
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
-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
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
+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%
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
Previous
Next Chapter
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%
Previous
Next Chapter
Next He#erence
(ll built5in JavaScript objects (ll browser objects (ll -./0 E$/ objects
(rra) object +oolean object Eate object /ath object Number object String object Heg!xp object Olobal properties and #unctions
&indow object Navigator object Screen object -istor) object 0ocation object
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