0% found this document useful (0 votes)
89 views

Introduction To Javascript: What You Should Already Know

JavaScript is used in millions of web pages to improve design and functionality. It is the most popular scripting language on the internet and works across all major browsers. JavaScript can dynamically update HTML pages, react to user events like clicks, modify HTML element content, validate form data, and more. It is case-sensitive, ignores extra whitespace, and supports both single-line and multi-line comments. JavaScript code can be embedded directly in HTML pages or linked externally via script tags and the src attribute. Code can be placed in the head or body section, with head scripts executing while the page loads and body scripts executing on page load. Variables are used to store and update data as the script runs, with variable scope and lifetime depending

Uploaded by

sauvish
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
89 views

Introduction To Javascript: What You Should Already Know

JavaScript is used in millions of web pages to improve design and functionality. It is the most popular scripting language on the internet and works across all major browsers. JavaScript can dynamically update HTML pages, react to user events like clicks, modify HTML element content, validate form data, and more. It is case-sensitive, ignores extra whitespace, and supports both single-line and multi-line comments. JavaScript code can be embedded directly in HTML pages or linked externally via script tags and the src attribute. Code can be placed in the head or body section, with head scripts executing while the page loads and body scripts executing on page load. Variables are used to store and update data as the script runs, with variable scope and lifetime depending

Uploaded by

sauvish
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 54

Introduction to JavaScript

JavaScript is used in millions of Web pages to improve the design, validate forms, detect browsers, create cookies, and much more. JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer, o!illa, "irefox, #etscape, $pera.

What You Should Already Know


%efore &ou continue &ou should have a basic understanding of the following'

() * + ,() *

If &ou want to stud& these subjects first, find the tutorials on our (ome page.

What is JavaScript?

JavaScript was designed to add interactivit& to () * pages JavaScript is a scripting language -a scripting language is a lightweight programming language. / JavaScript consists of lines of executable computer code / JavaScript is usuall& embedded directl& into () * pages JavaScript is an interpreted language -means that scripts execute without preliminar& compilation. Ever&one can use JavaScript without purchasing a license

Are Java and JavaScript the Same?


#$0 Java and JavaScript are two completel& different languages in both concept and design0 Java -developed b& Sun icros&stems. is a powerful and much more complex programming language 1 in the same categor& as 2 and 233.

What can a JavaScript Do?

JavaScript gives HT ! designers a programming tool " () * authors are normall& not programmers, but JavaScript is a scripting language with a ver& simple s&ntax0 /lmost an&one can put small 4snippets4 of code into their () * pages JavaScript can put dynamic te#t into an HT ! page " / JavaScript statement like this' document.write-45h674 3 name 3 45+h674. can write a variable text into an () * page JavaScript can react to events " / JavaScript can be set to execute when something happens, like when a page has finished loading or when a user clicks on an () * element JavaScript can read and write HT ! elements " / JavaScript can read and change the content of an () * element JavaScript can $e used to validate data " / JavaScript can be used to validate form data before it is submitted to a server, this will save the server from extra processing JavaScript can $e used to detect the visitor%s $rowser 1 / JavaScript can be used to detect the visitor8s browser, and 1 depending on the browser 1 load another page specificall& designed for that browser JavaScript can $e used to create coo&ies 1 / JavaScript can be used to store and retrieve information on the visitor8s computer

JavaScript 'uidelines
Some other important things to know when scripting with JavaScript.

JavaScript is (ase Sensitive


/ function named 4m&function4 is not the same as 4m&"unction4 and a variable named 4m&9ar4 is not the same as 4m&var4. JavaScript is case sensitive 1 therefore watch &our capitali!ation closel& when &ou create or call variables, objects and functions.

White Space
JavaScript ignores extra spaces. :ou can add white space to &our script to make it more readable. )he following lines are e;uivalent'
name="Hege" name = "Hege"

)rea& up a (ode !ine

:ou can break up a code line within a te#t string with a backslash. )he example below will be displa&ed properl&'
document.write("Hello \ World!")

(owever, &ou cannot break up a code line like this'


document.write \ ("Hello World!")

(omments
:ou can add comments to &our script b& using two slashes ++'
//this is a comment document.write("Hello World!")

or b& using +< and <+ -this creates a multi1line comment block.'
/* This is a comment block. t contains se!eral lines */ document.write("Hello World!")

JavaScript How To ***


)he () * 5script7 tag is used to insert a JavaScript into an () * page.

+#amples
Write text (ow to write text on a page. Write text with formatting (ow to format the text on &our page with () * tags.

How to ,ut a JavaScript Into an HT ! ,age


"html# "bod$#

"scri%t t$%e="te&t/'a!ascri%t"# document.write("Hello World!") "/scri%t# "/bod$# "/html#

)he code above will produce this output on an () * page' (ello World0

Example Explained
)o insert a JavaScript into an () * page, we use the 5script7 tag -also use the t&pe attribute to define the scripting language.. So, the 5script t&pe=4text+javascript47 and 5+script7 tells where the JavaScript starts and ends'
"html# "bod$# "scri%t t$%e="te&t/'a!ascri%t"# ... "/scri%t# "/bod$# "/html#

)he word document*write is a standard JavaScript command for writing output to a page. %& entering the document.write command between the 5script t&pe=4text+javascript47 and 5+script7 tags, the browser will recogni!e it as a JavaScript command and execute the code line. In this case the browser will write (ello World0 to the page'
"html# "bod$# "scri%t t$%e="te&t/'a!ascri%t"# document.write("Hello World!") "/scri%t# "/bod$# "/html#

-ote. If we had not entered the 5script7 tag, the browser would have treated the document.write-4(ello World04. command as pure text, and just write the entire line on the page.

+nding Statements With a Semicolon?


With traditional programming languages, like 233 and Java, each code statement has to end with a semicolon.

an& programmers continue this habit when writing JavaScript, but in general, semicolons are optional0 (owever, semicolons are re;uired if &ou want to put more than one statement on a single line.

How to Handle /lder )rowsers


%rowsers that do not support JavaScript will displa& the script as page content. )o prevent them from doing this, we ma& use the () * comment tag'
"scri%t t$%e="te&t/'a!ascri%t"# "!(( document.write("Hello World!") //((# "/scri%t#

)he two forward slashes at the end of comment line -++. are a JavaScript comment s&mbol. )his prevents the JavaScript compiler from compiling the line.

JavaScript Where To ***


JavaScripts in the bod& section will be executed W(I*E the page loads. JavaScripts in the head section will be executed when 2/**E>.

+#amples
(ead section Scripts that contain functions go in the head section of the document. )hen we can be sure that the script is loaded before the function is called. %od& section Execute a script that is placed in the bod& section. External script (ow to access an external script.

Where to ,ut the JavaScript


JavaScripts in a page will be executed immediatel& while the page loads into the browser. )his is not alwa&s what we want. Sometimes we want to execute a script when a page loads, other times when a user triggers an event.

Scripts in the head section. Scripts to be executed when the& are called, or when an event is triggered, go in the head section. When &ou place a script in the head section, &ou will ensure that the script is loaded before an&one uses it.
"html# "head# "scri%t t$%e="te&t/'a!ascri%t"# .... "/scri%t# "/head#

Scripts in the $ody section. Scripts to be executed when the page loads go in the bod& section. When &ou place a script in the bod& section it generates the content of the page.
"html# "head# "/head# "bod$# "scri%t t$%e="te&t/'a!ascri%t"# .... "/scri%t# "/bod$#

Scripts in $oth the $ody and the head section. :ou can place an unlimited number of scripts in &our document, so &ou can have scripts in both the bod& and the head section.
"html# "head# "scri%t t$%e="te&t/'a!ascri%t"# .... "/scri%t# "/head# "bod$# "scri%t t$%e="te&t/'a!ascri%t"# .... "/scri%t# "/bod$#

0sing an +#ternal JavaScript


Sometimes &ou might want to run the same JavaScript on several pages, without having to write the same script on ever& page. )o simplif& this, &ou can write a JavaScript in an external file. Save the external JavaScript file with a .js file extension. -ote. )he external script cannot contain the 5script7 tag0 )o use the external script, point to the .js file in the 4src4 attribute of the 5script7 tag'
"html#

"head# "scri%t src="&&&.'s"#"/scri%t# "/head# "bod$# "/bod$# "/html#

-ote. ?emember to place the script exactl& where &ou normall& would write the script0

JavaScript 1aria$les
/ variable is a 4container4 for information &ou want to store.

+#amples
9ariable 9ariables are used to store data. )his example will show &ou how.

1aria$les
/ variable is a 4container4 for information &ou want to store. / variable8s value can change during the script. :ou can refer to a variable b& name to see its value or to change its value. ?ules for variable names'

9ariable names are case sensitive )he& must begin with a letter or the underscore character

I ,/2TA-T3 JavaScript is case1sensitive0 / variable named strname is not the same as a variable named S)?#/ E0

Declare a 1aria$le
:ou can create a variable with the var statement'
!ar strname = some value

:ou can also create a variable without the var statement'


strname = some value

Assign a 1alue to a 1aria$le


:ou can assign a value to a variable like this'
!ar strname = "Hege"

$r like this'
strname = "Hege"

)he variable name is on the left side of the expression and the value &ou want to assign to the variable is on the right. #ow the variable 4strname4 has the value 4(ege4.

!i4etime o4 1aria$les
When &ou declare a variable within a function, the variable can onl& be accessed within that function. When &ou exit the function, the variable is destro&ed. )hese variables are called local variables. :ou can have local variables with the same name in different functions, because each is recogni!ed onl& b& the function in which it is declared. If &ou declare a variable outside a function, all the functions on &our page can access it. )he lifetime of these variables starts when the& are declared, and ends when the page is closed.

JavaScript I4***+lse Statements


2onditional statements in JavaScript are used to perform different actions based on different conditions.

+#amples
If statement (ow to write an if statement. If...else statement (ow to write an if...else statement. If..else if...else statement (ow to write an if..else if...else statement. ?andom link )his example demonstrates a link, when &ou click on the link it will take &ou to [email protected] $? to ?efsnes>ata.no. )here is a ABC chance for each of them.

(onditional Statements
9er& often when &ou write code, &ou want to perform different actions for different decisions. :ou can use conditional statements in &our code to do this. In JavaScript we have the following conditional statements'

i4 statement 1 use this statement if &ou want to execute some code onl& if a specified condition is true i4***else statement 1 use this statement if &ou want to execute some code if the condition is true and another code if the condition is false i4***else i4****else statement 1 use this statement if &ou want to select one of man& blocks of code to be executed switch statement 1 use this statement if &ou want to select one of man& blocks of code to be executed

I4 Statement
:ou should use the if statement if &ou want to execute some code onl& if a specified condition is true.

Syntax
i) (condition) * code to be executed if condition is true +

#ote that if is written in lowercase letters. Dsing uppercase letters -I". will generate a JavaScript error0

Example 1
"scri%t t$%e="te&t/'a!ascri%t"# //Write a ",ood morning" greeting i) //the time is less than -. !ar d=new /ate() !ar time=d.getHours() i) (time"-.) * document.write(""b#,ood morning"/b#") + "/scri%t#

Example 2
"scri%t t$%e="te&t/'a!ascri%t"# //Write "0unch(time!" i) the time is -!ar d=new /ate() !ar time=d.getHours()

i) (time==--) * document.write(""b#0unch(time!"/b#") + "/scri%t#

-ote. When comparing variables &ou must alwa&s use two e;uals signs next to each other -==.0 #otice that there is no ..else.. in this s&ntax. :ou just tell the code to execute some code only i4 the speci4ied condition is true.

I4***else Statement
If &ou want to execute some code if a condition is true and another code if the condition is not true, use the if....else statement.

Syntax
i) (condition) * code to be executed if condition is true + else * code to be executed if condition is not true +

Example
"scri%t t$%e="te&t/'a!ascri%t"# // ) the time is less than -.1 //$ou will get a ",ood morning" greeting. //2therwise $ou will get a ",ood da$" greeting. !ar d = new /ate() !ar time = d.getHours() i) (time " -.) * document.write(",ood morning!") + else * document.write(",ood da$!") + "/scri%t#

I4***else i4***else Statement


:ou should use the if....else if...else statement if &ou want to select one of man& sets of lines to execute.

Syntax
i) (condition1) * code to be executed if condition1 is true + else i) (condition2) * code to be executed if condition2 is true + else * code to be executed if condition1 and condition2 are not true +

Example
"scri%t t$%e="te&t/'a!ascri%t"# !ar d = new /ate() !ar time = d.getHours() i) (time"-.) * document.write(""b#,ood morning"/b#") + else i) (time#-. 33 time"-4) * document.write(""b#,ood da$"/b#") + else * document.write(""b#Hello World!"/b#") + "/scri%t#

JavaScript Switch Statement


2onditional statements in JavaScript are used to perform different actions based on different conditions.

+#amples
Switch statement (ow to write a switch statement.

The JavaScript Switch Statement


:ou should use the switch statement if &ou want to select one of man& blocks of code to be executed.

Syntax
switch(n) * case -5 execute code block 1 break case 65 execute code block 2 break de)ault5 code to be executed if n is different from case 1 and 2 +

)his is how it works' "irst we have a single expression n -most often a variable., that is evaluated once. )he value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed. Dse $rea& to prevent the code from running into the next case automaticall&.

Example
"scri%t t$%e="te&t/'a!ascri%t"# //7ou will recei!e a di))erent greeting based //on what da$ it is. 8ote that 9unda$=.1 //:onda$=-1 Tuesda$=61 etc. !ar d=new /ate() the/a$=d.get/a$() switch (the/a$) * case ;5 document.write("<inall$ <rida$") break case 45 document.write("9u%er 9aturda$") break case .5 document.write("9lee%$ 9unda$") break de)ault5 document.write(" =m looking )orward to this weekend!") + "/scri%t#

JavaScript /perators
Arithmetic /perators
/perator 3 Description /ddition +#ample x=E &=E x3& 2esult F

Subtraction

x=A &=E x1& x=A &=F x<& 6A+A A+E ACE 6BCG 6BCE x=A x33 x=A x11

<

ultiplication

EB

+ C

>ivision odulus -division remainder.

@ E.A 6 E B x=H x=F

33 11

Increment >ecrement

Assignment /perators
/perator = 3= 1= <= += C= +#ample x=& x3=& x1=& x<=& x+=& xC=& Is The Same As x=& x=x3& x=x1& x=x<& x=x+& x=xC&

(omparison /perators
/perator == === Description is e;ual to is e;ual to -checks for both value and t&pe. +#ample A==G returns false x=A &=4A4 x==& returns true x===& returns false 0= 7 5 7= 5= is not e;ual is greater than is less than is greater than or e;ual to is less than or e;ual to A0=G returns true A7G returns false A5G returns true A7=G returns false A5=G returns true

!ogical /perators
/perator II Description and +#ample x=H &=@ -x 5 6B II & 7 6. returns true JJ or x=H &=@ -x==A JJ &==A. returns false 0 not x=H &=@ 0-x==&. returns true

String /perator
/ string is most often text, for example 4(ello World04. )o stick two or more string variables together, use the 3 operator.
t&t-="What a !er$" t&t6="nice da$!" t&t>=t&t-?t&t6

)he variable txt@ now contains 4What a ver&nice da&04. )o add a space between two string variables, insert a space into the expression, $? in one of the strings.
t&t-="What a !er$" t&t6="nice da$!" t&t>=t&t-?" "?t&t6 or t&t-="What a !er$ " t&t6="nice da$!" t&t>=t&t-?t&t6

)he variable txt@ now contains 4What a ver& nice da&04.

(onditional /perator
JavaScript also contains a conditional operator that assigns a value to a variable based on some condition.

Syntax
!ariablename=(condition)@!alue-5!alue6

Example
greeting=(!isitor=="ABC9")@"/ear Aresident "5"/ear "

If the variable visitor is e;ual to K?ES, then put the string 4>ear Kresident 4 in the variable named greeting. If the variable visitor is not e;ual to K?ES, then put the string 4>ear 4 into the variable named greeting.

JavaScript ,opup )o#es


In JavaScript we can create three kind of popup boxes' /lert box, 2onfirm box, and Krompt box.

+#amples
/lert box /lert box with line breaks 2onfirm box Krompt box

Alert )o#
/n alert box is often used if &ou want to make sure information comes through to the user. When an alert box pops up, the user will have to click 4$L4 to proceed. Synta#.
alert("somete&t")

(on4irm )o#
/ confirm box is often used if &ou want the user to verif& or accept something. When a confirm box pops up, the user will have to click either 4$L4 or 42ancel4 to proceed. If the user clicks 4$L4, the box returns true. If the user clicks 42ancel4, the box returns false. Synta#.

con)irm("somete&t")

,rompt )o#
/ prompt box is often used if &ou want the user to input a value before entering a page. When a prompt box pops up, the user will have to click either 4$L4 or 42ancel4 to proceed after entering an input value. If the user clicks 4$L4 the box returns the input value. If the user clicks 42ancel4 the box returns null. Synta#.
%rom%t("somete&t"1"de)ault!alue")

JavaScript 5unctions
/ function is a reusable code1block that will be executed b& an event, or when the function is called.

+#amples
"unction (ow to call a function. "unction with arguments (ow to pass a variable to a function, and use the variable in the function. "unction with arguments E (ow to pass variables to a function, and use these variables in the function. "unction that returns a value (ow to let the function return a value. / function with arguments, that returns a value (ow to let the function find the product of E arguments and return the result.

JavaScript 5unctions

)o keep the browser from executing a script as soon as the page is loaded, &ou can write &our script as a function. / function contains some code that will be executed onl& b& an event or b& a call to that function. :ou ma& call a function from an&where within the page -or even from other pages if the function is embedded in an external .js file.. "unctions are defined at the beginning of a page, in the 5head7 section.

Example
"html# "head# "scri%t t$%e="te&t/'a!ascri%t"# )unction dis%la$message() * alert("Hello World!") + "/scri%t# "/head# "bod$# ")orm# "in%ut t$%e="button" !alue="Dlick me!" onclick="dis%la$message()" # "/)orm# "/bod$# "/html#

If the line' alert-4(ello world004., in the example above had not been written within a function, it would have been executed as soon as the line was loaded. #ow, the script is not executed before the user hits the button. We have added an on2lick event to the button that will execute the function displa&message-. when the button is clicked. :ou will learn more about JavaScript events in the JS Events chapter.

How to De4ine a 5unction


)he s&ntax for creating a function is'
)unction functionname(var1,var2,...,varX) * some code +

var6, varE, etc are variables or values passed into the function. )he M and the N defines the start and end of the function. -ote. / function with no parameters must include the parentheses -. after the function name'

)unction functionname() * some code +

-ote. >o not forget about the importance of capitals in JavaScript0 )he word function must be written in lowercase letters, otherwise a JavaScript error occurs0 /lso note that &ou must call a function with the exact same capitals as in the function name.

The return Statement


)he return statement is used to specif& the value that is returned from the function. So, functions that are going to return a value must use the return statement.

Example
)he function below should return the product of two numbers -a and b.'
)unction %rod(a1b) * &=a*b return & +

When &ou call the function above, &ou must pass along two parameters'
%roduct=%rod(61>)

)he returned value from the prod-. function is H, and it will be stored in the variable called product.

JavaScript 5or !oop


*oops in JavaScript are used to execute the same block of code a specified number of times or while a specified condition is true.

+#amples
"or loop (ow to write a for loop. Dse a "or loop to run the same block of code a specified number of times.

*ooping through () * headers (ow to use the for loop to loop through the different () * headers.

JavaScript !oops
9er& often when &ou write code, &ou want the same block of code to run over and over again in a row. Instead of adding several almost e;ual lines in a script we can use loops to perform a task like this. In JavaScript there are two different kind of loops'

4or 1 loops through a block of code a specified number of times while 1 loops through a block of code while a specified condition is true

The 4or !oop


)he for loop is used when &ou know in advance how man& times the script should run. Synta#
)or (!ar=start!alueE!ar"=end!alueE!ar=!ar?increment) * code to be executed +

+#ample Explanation' )he example below defines a loop that starts with i=B. )he loop will continue to run as long as i is less than, or e;ual to 6B. i will increase b& 6 each time the loop runs. -ote. )he increment parameter could also be negative, and the 5= could be an& comparing statement.
"html# "bod$# "scri%t t$%e="te&t/'a!ascri%t"# !ar i=. )or (i=.Ei"=-.Ei??) * document.write("The number is " ? i) document.write(""br /#") + "/scri%t# "/bod$# "/html#

2esult

The The The The The The The The The The The

number number number number number number number number number number number

is is is is is is is is is is is

. 6 > F ; 4 G H I -.

The while loop


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

JavaScript While !oop


*oops in JavaScript are used to execute the same block of code a specified number of times or while a specified condition is true.

+#amples
While loop (ow to write a while loop. Dse a while loop to run the same block of code while a specified condition is true. >o while loop (ow to write a do...while loop. Dse a do...while loop to run the same block of code while a specified condition is true. )his loop will alwa&s be executed at least once, even if the condition is false, because the statements are executed before the condition is tested.

The while loop


)he while loop is used when &ou want the loop to execute and continue executing while the specified condition is true.
while (!ar"=end!alue) * code to be executed +

-ote. )he 5= could be an& comparing statement.

+#ample Explanation' )he example below defines a loop that starts with i=B. )he loop will continue to run as long as i is less than, or e;ual to 6B. i will increase b& 6 each time the loop runs.
"html# "bod$# "scri%t t$%e="te&t/'a!ascri%t"# !ar i=. while (i"=-.) * document.write("The number is " ? i) document.write(""br /#") i=i?+ "/scri%t# "/bod$# "/html#

2esult
The The The The The The The The The The The number number number number number number number number number number number is is is is is is is is is is is . 6 > F ; 4 G H I -.

The do***while !oop


)he do...while loop is a variant of the while loop. )his loop will alwa&s execute a block of code $#2E, and then it will repeat the loop as long as the specified condition is true. )his loop will alwa&s be executed at least once, even if the condition is false, because the code is executed before the condition is tested.
do *

code to be executed + while (!ar"=end!alue)

+#ample
"html# "bod$# "scri%t t$%e="te&t/'a!ascri%t"# !ar i=. do *

document.write("The number is " ? i) document.write(""br /#") i=i?+ while (i".) "/scri%t# "/bod$# "/html#

2esult
The number is .

JavaScript )rea& and (ontinue


)here are two special statements that can be used inside loops' break and continue.

+#amples
%reak statement Dse the break statement to break the loop. 2ontinue statement Dse the continue statement to break the current loop and continue with the next value.

JavaScript $rea& and continue Statements


)here are two special statements that can be used inside loops' break and continue.

Break
)he break command will break the loop and continue executing the code that follows after the loop -if an&.. +#ample
"html# "bod$# "scri%t t$%e="te&t/'a!ascri%t"# !ar i=. )or (i=.Ei"=-.Ei??) * i) (i==>)*break+ document.write("The number is " ? i) document.write(""br /#")

+ "/scri%t# "/bod$# "/html#

2esult
The number is . The number is The number is 6

Continue
)he continue command will break the current loop and continue with the next value. +#ample
"html# "bod$# "scri%t t$%e="te&t/'a!ascri%t"# !ar i=. )or (i=.Ei"=-.Ei??) * i) (i==>)*continue+ document.write("The number is " ? i) document.write(""br /#") + "/scri%t# "/bod$# "/html#

2esult
The The The The The The The The The The number number number number number number number number number number is is is is is is is is is is . 6 F ; 4 G H I -.

JavaScript 5or***In Statement


)he for...in statement is used to loop -iterate. through the elements of an arra& or through the properties of an object.

+#amples
"or...In statement (ow to use a for...in statement to loop through the elements of an arra&.

JavaScript 5or***In Statement


)he for...in statement is used to loop -iterate. through the elements of an arra& or through the properties of an object. )he code in the bod& of the for ... in loop is executed once for each element+propert&. Synta#
)or (!ariable in ob'ect) * code to be executed +

)he variable argument can be a named variable, an arra& element, or a propert& of an object.

Example
Dsing for...in to loop through an arra&'
"html# "bod$# "scri%t t$%e="te&t/'a!ascri%t"# !ar & !ar m$cars = new Jrra$() m$carsK.L = "9aab" m$carsK-L = "Mol!o" m$carsK6L = "N:W" )or (& in m$cars) * document.write(m$carsK&L ? ""br /#") + "/scri%t# "/bod$# "/html#

JavaScript +vents
Events are actions that can be detected b& JavaScript.

+vents
%& using JavaScript, we have the abilit& to create d&namic web pages. Events are actions that can be detected b& JavaScript. Ever& element on a web page has certain events which can trigger JavaScript functions. "or example, we can use the on2lick event of a button element to indicate that a function will run when a user clicks on the button. We define the events in the () * tags. Examples of events'

/ mouse click / web page or an image loading ousing over a hot spot on the web page Selecting an input box in an () * form Submitting an () * form / ke&stroke

)he following table lists the events recogni!ed b& JavaScript' -ote. Events are normall& used in combination with functions, and the function will not be executed before the event occurs0 "or a complete reference of the events recogni!ed b& JavaScript, go to our complete Event reference.

onload and on0nload


)he onload and onDnload events are triggered when the user enters or leaves the page. )he onload event is often used to check the visitor8s browser t&pe and browser version, and load the proper version of the web page based on the information. %oth the onload and onDnload events are also often 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 for the user8s name upon his first arrival to &our page. )he name is then stored in a cookie. #ext time the visitor arrives at &our page, &ou could have another popup sa&ing something like' 4Welcome John >oe04.

on5ocus6 on)lur and on(hange


)he on"ocus, on%lur and on2hange events are often used in combination with validation of form fields. %elow is an example of how to use the on2hange event. )he checkEmail-. function will be called whenever the user changes the content of the field'

"in%ut t$%e="te&t" siOe=">." id="email" onchange="checkCmail()"#E

onSu$mit
)he onSubmit event is used to validate /** form fields before submitting it. %elow is an example of how to use the onSubmit event. )he check"orm-. function will be called when the user clicks the submit button in the form. If the field values are not accepted, the submit should be cancelled. )he function check"orm-. returns either true or false. If it returns true the form will be submitted, otherwise the submit will be cancelled'
")orm method="%ost" action="&&&.htm" onsubmit="return check<orm()"#

on ouse/ver and on ouse/ut


on ouse$ver and on ouse$ut are often used to create 4animated4 buttons. %elow is an example of an on ouse$ver event. /n alert box appears when an on ouse$ver event is detected'
"a hre)="htt%5//www.w>schools.com" onmouseo!er="alert(=Jn on:ouse2!er e!ent=)Ereturn )alse"# "img src="w>schools.gi)" width="-.." height=">."# "/a#

JavaScript Try***(atch Statement


)he tr&...catch statement allows &ou to test a block of code for errors.

+#amples
)he tr&...catch statement (ow to write a tr&...catch statement. )he tr&...catch statement with a confirm box /nother example of how to write a tr&...catch statement.

JavaScript " (atching +rrors

When browsing Web pages on the internet, I guess we have all seen a JavaScript alert box, telling &ou there is a runtime error, and asking' 4>o &ou wish to debugO4 on some pages. Error message like that ma& be useful for developers, but not for the users. When users see errors, the& often leave the Web page. )his chapter will teach &ou how to trap and handle JavaScript error messages, so &ou don8t lose &our audience. )here are two wa&s of catching errors in a Web page'

%& using the try***catch statement -available in IEA3, o!illa 6.B, and #etscape H. %& using the onerror event. )his is the old standard solution to catch errors -available since #etscape @.

Try***(atch Statement
)he tr&...catch statement allows &ou to test a block of code for errors. )he tr& block contains the code to be run, and the catch block contains the code to be executed if an error occurs.

Syntax
tr$ * //Bun some code here + catch(err) * //Handle errors here +

#ote that tr&...catch is written in lowercase letters. Dsing uppercase letters will generate a JavaScript error0

Example 1
)he example below contains a script that is supposed to displa& the message 4Welcome guest04 when &ou click on a button. (owever, there8s a t&po in the message-. function. alert-. is misspelled as adddlert-.. / JavaScript error occurs'
"html# "head# "scri%t t$%e="te&t/'a!ascri%t"# )unction message() * adddlert("Welcome guest!") + "/scri%t# "/head# "bod$# "in%ut t$%e="button" !alue="Miew message" onclick="message()" /# "/bod$#

"/html#

)o take more appropriate action when an error occurs, &ou can add a tr&...catch statement. )he example below contains the 4Welcome guest04 example rewritten to use the tr&...catch statement. Since alert-. is misspelled, a JavaScript error occurs. (owever, this time, the catch block catches the error and executes a custom code to handle it. )he code displa&s a custom error message informing the user what happened'
"html# "head# "scri%t t$%e="te&t/'a!ascri%t"# !ar t&t="" )unction message() * tr$ * adddlert("Welcome guest!") + catch(err) * t&t="There was an error on this %age.\n\n" t&t?="Crror descri%tion5 " ? err.descri%tion ? "\n\n" t&t?="Dlick 2P to continue.\n\n" alert(t&t) + + "/scri%t# "/head# "bod$# "in%ut t$%e="button" !alue="Miew message" onclick="message()" /# "/bod$# "/html#

Example 2
)he next example uses a confirm box to displa& a custom message telling users the& can click $L to continue viewing the page or click 2ancel to go to the homepage. If the confirm method returns false, the user clicked 2ancel, and the code redirects the user. If the confirm method returns true, the code does nothing'
"html# "head# "scri%t t$%e="te&t/'a!ascri%t"# !ar t&t="" )unction message() * tr$ * adddlert("Welcome guest!") + catch(err) *

+ "/scri%t# "/head# "bod$# "in%ut t$%e="button" !alue="Miew message" onclick="message()" /# "/bod$# "/html#

t&t="There was an error on this %age.\n\n" t&t?="Dlick 2P to continue !iewing this %age1\n" t&t?="or Dancel to return to the home %age.\n\n" i)(!con)irm(t&t)) * document.location.hre)="htt%5//www.w>schools.com/" + +

The onerror +vent


)he onerror event will be explained soon, but first &ou will learn how to use the throw statement to create an exception. )he throw statement can be used together with the tr&...catch statement.

JavaScript Throw Statement


)he throw statement allows &ou to create an exception.

+#amples
)he throw statement (ow to use the throw statement.

The Throw Statement


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

Syntax
throw(e&ce%tion)

)he exception can be a string, integer, %oolean or an object. #ote that throw is written in lowercase letters. Dsing uppercase letters will generate a JavaScript error0

Example 1
)he example below determines the value of a variable called x. If the value of x is higher than 6B or lower than B we are going to throw an error. )he error is then caught b& the catch argument and the proper error message is displa&ed'
"html# "bod$# "scri%t t$%e="te&t/'a!ascri%t"# !ar &=%rom%t("Cnter a number between . and -.5"1"") tr$ * i)(&#-.) throw "Crr-" else i)(&".) throw "Crr6" + catch(er) * i)(er=="Crr-") alert("Crror! The !alue is too high") i)(er == "Crr6") alert("Crror! The !alue is too low") + "/scri%t# "/bod$# "/html#

JavaScript The onerror +vent


Dsing the onerror event is the old standard solution to catch errors in a web page.

+#amples
)he onerror event (ow to use the onerror event to catch errors in a web page.

The onerror +vent


We have just explained how to use the tr&...catch statement to catch errors in a web page. #ow we are going to explain how to use the onerror event for the same purpose. )he onerror event is fired whenever there is a script error in the page.

)o use the onerror event, &ou must create a function to handle the errors. )hen &ou call the function with the onerror event handler. )he event handler is called with three arguments' msg -error message., url -the url of the page that caused the error. and line -the line where the error occurred..

Syntax
onerror=handleCrr )unction handleCrr(msg1url1l) * //Handle the error here return true or )alse +

)he value returned b& onerror determines whether the browser displa&s a standard error message. If &ou return false, the browser displa&s the standard error message in the JavaScript console. If &ou return true, the browser does not displa& the standard error message.

Example
)he following example shows how to catch the error with the onerror event'
"html# "head# "scri%t t$%e="te&t/'a!ascri%t"# onerror=handleCrr !ar t&t="" )unction handleCrr(msg1url1l) * t&t="There was an error on this %age.\n\n" t&t?="Crror5 " ? msg ? "\n" t&t?="QB05 " ? url ? "\n" t&t?="0ine5 " ? l ? "\n\n" t&t?="Dlick 2P to continue.\n\n" alert(t&t) return true + )unction message() * adddlert("Welcome guest!") + "/scri%t# "/head# "bod$# "in%ut t$%e="button" !alue="Miew message" onclick="message()" /# "/bod$# "/html#

JavaScript Special (haracters


In JavaScript &ou can add special characters to a text string b& using the backslash sign.

Insert Special (haracters


)he backslash -P. is used to insert apostrophes, new lines, ;uotes, and other special characters into a text string. *ook at the following JavaScript code'
!ar t&t="We are the so(called "Mikings" )rom the north." document.write(t&t)

In JavaScript, a string is started and stopped with either single or double ;uotes. )his means that the string above will be chopped to' We are the so1called )o solve this problem, &ou must place a backslash -P. before each double ;uote in 49iking4. )his turns each double ;uote into a string literal'
!ar t&t="We are the so(called \"Mikings\" )rom the north." document.write(t&t)

JavasScript will now output the proper text string' We are the so1called 49ikings4 from the north. (ere is another example'
document.write ("7ou \3 me are singing!")

)he example above will produce the following output'


7ou 3 me are singing!

)he table below lists other special characters that can be added to a text string with the backslash sign' (ode P8 P4 PI PP Pn Pr Pt Pb Pf /utputs single ;uote double ;uote ampersand backslash new line carriage return tab backspace form feed

JavaScript /$7ects Introduction


JavaScript is an $bject $riented Krogramming -$$K. language. /n $$K language allows &ou to define &our own objects and make &our own variable t&pes.

/$7ect /riented ,rogramming


JavaScript is an $bject $riented Krogramming -$$K. language. /n $$K language allows &ou to define &our own objects and make &our own variable t&pes. (owever, creating &our own objects will be explained later, in the /dvanced JavaScript section. We will start b& looking at the built1in JavaScript objects, and how the& are used. )he next pages will explain each built1in JavaScript object in detail. #ote that an object is just a special kind of data. /n object has properties and methods.

,roperties
Kroperties are the values associated with an object. In the following example we are using the length propert& of the String object to return the number of characters in a string'
"scri%t t$%e="te&t/'a!ascri%t"# !ar t&t="Hello World!" document.write(t&t.length) "/scri%t#

)he output of the code above will be'


-6

ethods
ethods are the actions that can be performed on objects. In the following example we are using the toDpper2ase-. method of the String object to displa& a text in uppercase letters'
"scri%t t$%e="te&t/'a!ascri%t"#

!ar str="Hello world!" document.write(str.toQ%%erDase()) "/scri%t#

)he output of the code above will be'


HC002 W2B0/!

JavaScript String /$7ect


)he String object is used to manipulate a stored piece of text.

+#amples
?eturn the length of a string (ow to use the length propert& to find the length of a string. St&le strings (ow to st&le strings. )he index$f-. method (ow to use the index$f-. method to return the position of the first occurrence of a specified string value in a string. )he match-. method (ow to use the match-. method to search for a specified string value within a string and return the string value if found ?eplace characters in a string 1 replace-. (ow to use the replace-. method to replace some characters with some other characters in a string. Tip. :ou will find a lot more examples in the String o$7ect re4erence 1 look at the bottom of this page0

String o$7ect
)he String object is used to manipulate a stored piece of text. +#amples o4 use. )he following example uses the length propert& of the String object to find the length of a string'

!ar t&t="Hello world!" document.write(t&t.length)

)he code above will result in the following output'


-6

)he following example uses the toDpper2ase-. method of the String object to convert a string to uppercase letters'
!ar t&t="Hello world!" document.write(t&t.toQ%%erDase())

)he code above will result in the following output'


HC002 W2B0/!

(omplete String /$7ect 2e4erence


"or a complete reference of all the properties and methods that can be used with the String object, go to our complete String object reference. )he reference contains a brief description and examples of use for each propert& and method0

JavaScript Date /$7ect


)he >ate object is used to work with dates and times.

+#amples
?eturn toda&8s date and time (ow to use the >ate-. method to get toda&8s date. get)ime-. Dse get)ime-. to calculate the &ears since 6QRB. set"ull:ear-. (ow to use set"ull:ear-. to set a specific date. toD)2String-. (ow to use toD)2String-. to convert toda&8s date -according to D)2. to a string.

get>a&-. Dse get>a&-. and an arra& to write a weekda&, and not just a number. >ispla& a clock (ow to displa& a clock on &our web page. Tip. :ou will find a lot more examples in the Date o$7ect re4erence 1 look at the bottom of this page0

De4ining Dates
)he >ate object is used to work with dates and times. We define a >ate object with the new ke&word. )he following code line defines a >ate object called m&>ate'
!ar m$/ate=new /ate()

-ote. )he >ate object will automaticall& hold the current date and time as its initial value0

anipulate Dates
We can easil& manipulate the date b& using the methods available for the >ate object. In the example below we set a >ate object to a specific date -6Fth Januar& EB6B.'
!ar m$/ate=new /ate() m$/ate.set<ull7ear(6.-.1.1-F)

/nd in the following example we set a >ate object to be A da&s into the future'
!ar m$/ate=new /ate() m$/ate.set/ate(m$/ate.get/ate()?;)

-ote. If adding five da&s to a date shifts the month or &ear, the changes are handled automaticall& b& the >ate object itself0

(omparing Dates
)he >ate object is also used to compare two dates. )he following example compares toda&8s date with the 6Fth Januar& EB6B'
!ar m$/ate=new /ate()

m$/ate.set<ull7ear(6.-.1.1-F) !ar toda$ = new /ate() i) (m$/ate#toda$) alert("Toda$ is be)ore -Fth Ranuar$ 6.-.") else alert("Toda$ is a)ter -Fth Ranuar$ 6.-.")

(omplete Date /$7ect 2e4erence


"or a complete reference of all the properties and methods that can be used with the >ate object, go to our complete >ate object reference. )he reference contains a brief description and examples of use for each propert& and method0

JavaScript Array /$7ect


)he /rra& object is used to store a set of values in a single variable name.

+#amples
2reate an arra& 2reate an arra&, assign values to it, and write the values to the output. "or...In Statement (ow to use a for...in statement to loop through the elements of an arra&. Join two arra&s 1 concat-. (ow to use the concat-. method to join two arra&s. Kut arra& elements into a string 1 join-. (ow to use the join-. method to put all the elements of an arra& into a string. *iteral arra& 1 sort-. (ow to use the sort-. method to sort a literal arra&. #umeric arra& 1 sort-. (ow to use the sort-. method to sort a numeric arra&. Tip. :ou will find a lot more examples in the Array o$7ect re4erence 1 look at the bottom of this page0

De4ining Arrays

)he /rra& object is used to store a set of values in a single variable name. We define an /rra& object with the new ke&word. )he following code line defines an /rra& object called m&/rra&'
!ar m$Jrra$=new Jrra$()

)here are two wa&s of adding values to an arra& -&ou can add as man& values as &ou need to define as man& variables &ou re;uire.. 6'
!ar m$cars=new Jrra$() m$carsK.L="9aab" m$carsK-L="Mol!o" m$carsK6L="N:W"

:ou could also pass an integer argument to control the arra&8s si!e'
!ar m$cars=new Jrra$(>) m$carsK.L="9aab" m$carsK-L="Mol!o" m$carsK6L="N:W"

E'
!ar m$cars=new Jrra$("9aab"1"Mol!o"1"N:W")

-ote. If &ou specif& numbers or true+false values inside the arra& then the t&pe of variables will be numeric or %oolean instead of string.

Accessing Arrays
:ou can refer to a particular element in an arra& b& referring to the name of the arra& and the index number. )he index number starts at B. )he following code line'
document.write(m$carsK.L)

will result in the following output'


9aab

odi4y 1alues in +#isting Arrays

)o modif& a value in an existing arra&, just add a new value to the arra& with a specified index number'
m$carsK.L="2%el"

#ow, the following code line'


document.write(m$carsK.L)

will result in the following output'


2%el

(omplete Array /$7ect 2e4erence


"or a complete reference of all the properties and methods that can be used with the /rra& object, go to our complete /rra& object reference. )he reference contains a brief description and examples of use for each propert& and method0

JavaScript )oolean /$7ect


)he %oolean object is used to convert a non1%oolean value to a %oolean value -true or false..

+#amples
2heck %oolean value 2heck if a %oolean object is true or false. Tip. :ou will find more examples in the )oolean o$7ect re4erence 1 look at the bottom of this page0

)oolean /$7ect
)he %oolean object is an object wrapper for a %oolean value. )he %oolean object is used to convert a non1%oolean value to a %oolean value -true or false.. We define a %oolean object with the new ke&word. )he following code line defines a %oolean object called m&%oolean'

!ar m$Noolean=new Noolean()

-ote. If the %oolean object has no initial value or if it is B, 1B, null, 44, false, undefined, or #a#, the object is set to false. $therwise it is true -even with the string 4false4.0 /ll the following lines of code create %oolean objects with an initial value of false'
!ar !ar !ar !ar !ar !ar m$Noolean=new m$Noolean=new m$Noolean=new m$Noolean=new m$Noolean=new m$Noolean=new Noolean() Noolean(.) Noolean(null) Noolean("") Noolean()alse) Noolean(8a8)

/nd all the following lines of code create %oolean objects with an initial value of true'
!ar !ar !ar !ar m$Noolean=new m$Noolean=new m$Noolean=new m$Noolean=new Noolean(true) Noolean("true") Noolean(")alse") Noolean("Bichard")

(omplete )oolean /$7ect 2e4erence


"or a complete reference of all the properties and methods that can be used with the %oolean object, go to our complete %oolean object reference. )he reference contains a brief description and examples of use for each propert& and method0

JavaScript
)he

ath /$7ect

ath object allows &ou to perform common mathematical tasks.

+#amples
round-. (ow to use round-.. random-. (ow to use random-. to return a random number between B and 6. max-. (ow to use max-. to return the number with the highest value of two specified numbers.

min-. (ow to use min-. to return the number with the lowest value of two specified numbers. Tip. :ou will find a lot more examples in the this page0 ath o$7ect re4erence 1 look at the bottom of

ath /$7ect
)he ath object allows &ou to perform common mathematical tasks. )he ath object includes several mathematical values and functions. :ou do not need to define the ath object before using it.

athematical 1alues
JavaScript provides eight mathematical values -constants. that can be accessed from the ath object. )hese are' E, KI, s;uare root of E, s;uare root of 6+E, natural log of E, natural log of 6B, base1E log of E, and base16B log of E. :ou ma& reference these values from &our JavaScript like this'
:ath.C :ath.A :ath.9SBT6 :ath.9SBT-T6 :ath.086 :ath.08-. :ath.02,6C :ath.02,-.C

athematical

ethods
ath object there are

In addition to the mathematical values that can be accessed from the also several functions -methods. available. +#amples o4 4unctions 8methods9. )he following example uses the round-. method of the nearest integer'
document.write(:ath.round(F.G))

ath object to round a number to the

)he code above will result in the following output'


;

)he following example uses the random-. method of the number between B and 6'
document.write(:ath.random())

ath object to return a random

)he code above can result in the following output'


..F.G.G>4G>G>4-..G

)he following example uses the floor-. and random-. methods of the random number between B and 6B'
document.write(:ath.)loor(:ath.random()*--))

ath object to return a

)he code above can result in the following output'


4

(omplete

ath /$7ect 2e4erence


ath

"or a complete reference of all the properties and methods that can be used with the object, go to our complete ath object reference.

)he reference contains a brief description and examples of use for each propert& and method0

JavaScript HT ! D/

/$7ects

In addition to the built1in JavaScript objects, &ou can also access and manipulate all of the () * >$ objects with JavaScript.

The HT ! D/
)he () * >$ for () *. is a W@2 standard and it is an abbreviation for the >ocument $bject odel

)he () * >$ defines a standard set of objects for () *, and a standard wa& to access and manipulate () * documents. /ll () * elements, along with their containing text and attributes, can be accessed through the >$ . )he contents can be modified or deleted, and new elements can be created.

)he () * >$ is platform and language independent. It can be used b& an& programming language like Java, JavaScript, and 9%Script. "ollow the links below to learn more about how to access and manipulate each >$ with JavaScript' /$7ect /nchor /pplet /rea %ase %asefont %od& %utton Description ?epresents an () * a element -a h&perlink. ?epresents an () * applet element. )he applet element is used to place executable content on a page ?epresents an area of an image1map. /n image1map is an image with clickable regions ?epresents an () * base element ?epresents an () * basefont element ?epresents the bod& of the document -the () * bod&. ?epresents a push button on an () * form. "or each instance of an () * 5input t&pe=4button47 tag on an () * form, a %utton object is created ?epresents a checkbox on an () * form. "or each instance of an () * 5input t&pe=4checkbox47 tag on an () * form, a 2heckbox object is created Dsed to access all elements in a page ?epresents the state of an event, such as the element in which the event occurred, the state of the ke&board ke&s, the location of the mouse, and the state of the mouse buttons "or each instance of an () * 5input t&pe=4file47 tag on a form, a "ileDpload object is created "orms are used to prompt users for input. ?epresents an () * form element ?epresents an () * frame ?epresents an () * frameset ?epresents a hidden field on an () * form. "or each instance of an () * 5input t&pe=4hidden47 tag on a form, a (idden object is created / predefined object which can be accessed through the histor& propert& of the Window object. )his object consists of an arra& of D?*s. )hese D?*s are all the D?*s the user has visited within a browser window ?epresents an () * inline1frame ?epresents an () * img element ?epresents an () * link element. )he link element can onl& be used within the 5head7 tag 2ontains information about the current D?* object

2heckbox

>ocument Event

"ileDpload "orm "rame "rameset (idden

(istor&

Iframe Image *ink *ocation

eta #avigator $ption

?epresents an () * meta element 2ontains information about the client browser ?epresents an option in a selection list on an () * form. "or each instance of an () * 5option7 tag in a selection list on a form, an $ption object is created ?epresents a password field on an () * form. "or each instance of an () * 5input t&pe=4password47 tag on a form, a Kassword object is created ?epresents radio buttons on an () * form. "or each instance of an () * 5input t&pe=4radio47 tag on a form, a ?adio object is created ?epresents a reset button on an () * form. "or each instance of an () * 5input t&pe=4reset47 tag on a form, a ?eset object is created /utomaticall& created b& the JavaScript runtime engine and it contains information about the client8s displa& screen ?epresents a selection list on an () * form. "or each instance of an () * 5select7 tag on a form, a Select object is created ?epresents an individual st&le statement. )his object can be accessed from the document or from the elements to which that st&le is applied ?epresents a submit button on an () * form. "or each instance of an () * 5input t&pe=4submit47 tag on a form, a Submit object is created ?epresents an () * table element ?epresents an () * td element ?epresents an () * th element ?epresents an () * tr element ?epresents a text field on an () * form. "or each instance of an () * 5input t&pe=4text47 tag on a form, a )ext object is created ?epresents an () * textarea element 2orresponds to the browser window. / Window object is created automaticall& with ever& instance of a 5bod&7 or 5frameset7 tag

Kassword

?adio ?eset Screen Select St&le Submit

)able )able>ata )able(eader )able?ow )ext )extarea Window

JavaScript )rowser Detection


)he JavaScript #avigator object contains information about the visitor8s browser.

+#amples
>etect the visitor8s browser and browser version

ore details about the visitor8s browser /ll details about the visitor8s browser /lert user, depending on browser

)rowser Detection
/lmost ever&thing in this tutorial works on all JavaScript1enabled browsers. (owever, there are some things that just don8t work on certain browsers 1 speciall& on older browsers. So, sometimes it can be ver& useful to detect the visitor8s browser t&pe and version, and then serve up the appropriate information. )he best wa& to do this is to make &our web pages smart enough to look one wa& to some browsers and another wa& to other browsers. JavaScript includes an object called the #avigator object, that can be used for this purpose. )he #avigator object contains information about the visitor8s browser name, browser version, and more.

The -avigator /$7ect


)he JavaScript #avigator object contains all information about the visitor8s browser. We are going to look at two properties of the #avigator object'

app#ame 1 holds the name of the browser app9ersion 1 holds, among other things, the version of the browser

Example
"html# "bod$# "scri%t t$%e="te&t/'a!ascri%t"# !ar browser=na!igator.a%%8ame !ar bT!ersion=na!igator.a%%Mersion !ar !ersion=%arse<loat(bT!ersion) document.write("Nrowser name5 "? browser) document.write(""br /#") document.write("Nrowser !ersion5 "? !ersion) "/scri%t# "/bod$# "/html#

)he variable browser in the example above holds the name of the browser, i.e. 4#etscape4 or 4 icrosoft Internet Explorer4.

)he app9ersion propert& in the example above returns a string that contains much more information than just the version number, but for now we are onl& interested in the version number. )o pull the version number out of the string we are using a function called parse"loat-., which pulls the first thing that looks like a decimal number out of a string and returns it. I ,/2TA-T3 )he version number is W?$#S in IE A.B or later0 icrosoft starts the app9ersion string with the number F.B. in IE A.B and IE H.B000 Wh& did the& do thatOOO (owever, JavaScript is the same in IEH, IEA and IEF, so for most scripts it is ok.

Example
)he script below displa&s a different alert, depending on the visitor8s browser'
"html# "head# "scri%t t$%e="te&t/'a!ascri%t"# )unction detectNrowser() * !ar browser=na!igator.a%%8ame !ar bT!ersion=na!igator.a%%Mersion !ar !ersion=%arse<loat(bT!ersion) i) ((browser=="8etsca%e"UUbrowser==":icroso)t nternet C&%lorer") 33 (!ersion#=F)) *alert("7our browser is good enough!")+ else *alert(" t=s time to u%grade $our browser!")+ + "/scri%t# "/head# "bod$ onload="detectNrowser()"# "/bod$# "/html#

JavaScript (oo&ies
/ cookie is often used to identif& a user.

+#amples
2reate a welcome cookie

What is a (oo&ie?

/ cookie is a variable that is stored on the visitor8s computer. Each time the same computer re;uests a page with a browser, it will send the cookie too. With JavaScript, &ou can both create and retrieve cookie values. Examples of cookies'

#ame cookie 1 )he first time a visitor arrives to &our web page, he or she must fill in her+his name. )he name is then stored in a cookie. #ext time the visitor arrives at &our page, he or she could get a welcome message like 4Welcome John >oe04 )he name is retrieved from the stored cookie Kassword cookie 1 )he first time a visitor arrives to &our web page, he or she must fill in a password. )he password is then stored in a cookie. #ext time the visitor arrives at &our page, the password is retrieved from the cookie >ate cookie 1 )he first time a visitor arrives to &our web page, the current date is stored in a cookie. #ext time the visitor arrives at &our page, he or she could get a message like 4:our last visit was on )uesda& /ugust 66, EBBA04 )he date is retrieved from the stored cookie

(reate and Store a (oo&ie


In this example we will create a cookie that stores the name of a visitor. )he first time a visitor arrives to the web page, he or she will be asked to fill in her+his 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 function that stores the name of the visitor in a cookie variable'
)unction setDookie(cTname1!alue1e&%ireda$s) * !ar e&date=new /ate() e&date.set/ate(e&date.get/ate()?e&%ireda$s) document.cookie=cTname? "=" ?esca%e(!alue)? ((e&%ireda$s==null) @ "" 5 "Ee&%ires="?e&date) +

)he parameters of the function above hold the name of the cookie, the value of the cookie, and the number of da&s until the cookie expires. In the function above we first convert the number of da&s to a valid date, then we add the number of da&s until the cookie should expire. /fter that we store the cookie name, cookie value and the expiration date in the document.cookie object. )hen, we create another function that checks if the cookie has been set'
)unction getDookie(cTname) * i) (document.cookie.length#.) * cTstart=document.cookie.inde&2)(cTname ? "=") i) (cTstart!=(-)

+ return null +

* cTstart=cTstart ? cTname.length?cTend=document.cookie.inde&2)("E"1cTstart) i) (cTend==(-) cTend=document.cookie.length return unesca%e(document.cookie.substring(cTstart1cTend)) +

)he function above first checks if a cookie is stored at all in the document.cookie object. If the document.cookie object holds some cookies, then check to see if our specific cookie is stored. If our cookie is found, then return the value, if not 1 return null. *ast, we create the function that displa&s a welcome message if the cookie is set, and if the cookie is not set it will displa& a prompt box, asking for the name of the user'
)unction checkDookie() * username=getDookie(=username=) i) (username!=null) *alert(=Welcome again =?username?=!=)+ else * username=%rom%t(=Alease enter $our name5=1"") i) (username!=nullUUusername!="") * setDookie(=username=1username1>4;) + + +

/ll together now'


"html# "head# "scri%t t$%e="te&t/'a!ascri%t"# )unction getDookie(cTname) * i) (document.cookie.length#.) * cTstart=document.cookie.inde&2)(cTname ? "=") i) (cTstart!=(-) * cTstart=cTstart ? cTname.length?cTend=document.cookie.inde&2)("E"1cTstart) i) (cTend==(-) cTend=document.cookie.length return unesca%e(document.cookie.substring(cTstart1cTend)) + + return null + )unction setDookie(cTname1!alue1e&%ireda$s) * !ar e&date=new /ate() e&date.set/ate(e&date.get/ate()?e&%ireda$s) document.cookie=cTname? "=" ?esca%e(!alue)?

((e&%ireda$s==null) @ "" 5 "Ee&%ires="?e&date) + )unction checkDookie() * username=getDookie(=username=) i) (username!=null) *alert(=Welcome again =?username?=!=)+ else * username=%rom%t(=Alease enter $our name5=1"") i) (username!=nullUUusername!="") * setDookie(=username=1username1>4;) + + + "/scri%t# "/head# "bod$ on0oad="checkDookie()"# "/bod$# "/html#

)he example above runs the check2ookie-. function when the page loads.

JavaScript 5orm 1alidation


JavaScript can be used to validate input data in () * forms before sending off the content to a server.

JavaScript 5orm 1alidation


JavaScript can be used to validate input data in () * forms before sending off the content to a server. "orm data that t&picall& are checked b& a JavaScript could be'

has the user left re;uired fields empt&O has the user entered a valid e1mail addressO has the user entered a valid dateO has the user entered text in a numeric fieldO

2e:uired 5ields
)he function below checks if a re;uired field has been left empt&. If the re;uired field is blank, an alert box alerts a message and the function returns false. If a value is entered, the function returns true -means that data is $L.'

)unction !alidateTreVuired()ield1alertt&t) * with ()ield) * i) (!alue==nullUU!alue=="") *alert(alertt&t)Ereturn )alse+ else *return true+ + +

)he entire script, with the () * form could look something like this'
"html# "head# "scri%t t$%e="te&t/'a!ascri%t"# )unction !alidateTreVuired()ield1alertt&t) * with ()ield) * i) (!alue==nullUU!alue=="") *alert(alertt&t)Ereturn )alse+ else *return true+ + + )unction !alidateT)orm(this)orm) * with (this)orm) * i) (!alidateTreVuired(email1"Cmail must be )illed out!")==)alse) *email.)ocus()Ereturn )alse+ + + "/scri%t# "/head# "bod$# ")orm action="submit%age.htm" onsubmit="return !alidateT)orm(this)" method="%ost"# Cmail5 "in%ut t$%e="te&t" name="email" siOe=">."# "in%ut t$%e="submit" !alue="9ubmit"# "/)orm# "/bod$# "/html#

+"mail 1alidation
)he function below checks if the content has the general s&ntax of an email. )his means that the input data must contain at least an T sign and a dot -... /lso, the T must not be the first character of the email address, and the last dot must at least be one character after the T sign'
)unction !alidateTemail()ield1alertt&t) *

with ()ield) * a%os=!alue.inde&2)("W") dot%os=!alue.last nde&2)(".") i) (a%os"-UUdot%os(a%os"6) *alert(alertt&t)Ereturn )alse+ else *return true+ + +

)he entire script, with the () * form could look something like this'
"html# "head# "scri%t t$%e="te&t/'a!ascri%t"# )unction !alidateTemail()ield1alertt&t) * with ()ield) * a%os=!alue.inde&2)("W") dot%os=!alue.last nde&2)(".") i) (a%os"-UUdot%os(a%os"6) *alert(alertt&t)Ereturn )alse+ else *return true+ + + )unction !alidateT)orm(this)orm) * with (this)orm) * i) (!alidateTemail(email1"8ot a !alid e(mail address!")==)alse) *email.)ocus()Ereturn )alse+ + + "/scri%t# "/head# "bod$# ")orm action="submit%age.htm" onsubmit="return !alidateT)orm(this)" method="%ost"# Cmail5 "in%ut t$%e="te&t" name="email" siOe=">."# "in%ut t$%e="submit" !alue="9ubmit"# "/)orm# "/bod$# "/html#

JavaScript (reate Your /wn /$7ects


$bjects are useful to organi!e information.

+#amples

2reate a direct instance of an object 2reate a template for an object

JavaScript /$7ects
Earlier in this tutorial we have seen that JavaScript has several built1in objects, like String, >ate, /rra&, and more. In addition to these built1in objects, &ou can also create &our own. /n object is just a special kind of data, with a collection of properties and methods. *et8s illustrate with an example' / person is an object. Kroperties 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 of those properties will differ from person to person. $bjects also have methods. ethods are the actions that can be performed on objects. )he persons8 methods could be eat-., sleep-., work-., pla&-., etc.

Properties
)he s&ntax for accessing a propert& of an object is'
ob'8ame.%ro%8ame

:ou can add properties to an object b& simpl& giving it a value. /ssume that the person$bj alread& exists 1 &ou can give it properties named firstname, lastname, age, and e&ecolor as follows'
%erson2b'.)irstname="Rohn" %erson2b'.lastname="/oe" %erson2b'.age=>. %erson2b'.e$ecolor="blue" document.write(%erson2b'.)irstname)

)he code above will generate the following output'


Rohn

Methods
/n object can also contain methods. :ou can call a method with the following s&ntax'
ob'8ame.method8ame()

-ote. Karameters re;uired for the method can be passed between the parentheses.

)o call a method called sleep-. for the person$bj'


%erson2b'.slee%()

(reating Your /wn /$7ects


)here are different wa&s to create a new object' ;* (reate a direct instance o4 an o$7ect )he following code creates an instance of an object and adds four properties to it'
%erson2b'=new 2b'ect() %erson2b'.)irstname="Rohn" %erson2b'.lastname="/oe" %erson2b'.age=;. %erson2b'.e$ecolor="blue"

/dding a method to the person$bj is also simple. )he following code adds a method called eat-. to the person$bj'
%erson2b'.eat=eat

<* (reate a template o4 an o$7ect )he template defines the structure of an object'
)unction %erson()irstname1lastname1age1e$ecolor) * this.)irstname=)irstname this.lastname=lastname this.age=age this.e$ecolor=e$ecolor +

#otice that the template is just a function. Inside the function &ou need to assign things to this.propert&#ame. )he reason for all the 4this4 stuff in is that &ou8re going to have more than one person at a time -which person &ou8re dealing with must be clear.. )hat8s what 4this4 is' the instance of the object at hand. $nce &ou have the template, &ou can create new instances of the object, like this'
m$<ather=new %erson("Rohn"1"/oe"1;.1"blue") m$:other=new %erson("9all$"1"Ball$"1FH1"green")

:ou can also add some methods to the person object. )his is also done inside the template'

)unction %erson()irstname1lastname1age1e$ecolor) * this.)irstname=)irstname this.lastname=lastname this.age=age this.e$ecolor=e$ecolor this.newlastname=newlastname +

#ote that methods are just functions attached to objects. )hen we will have to write the newlastname-. function'
)unction newlastname(newTlastname) * this.lastname=newTlastname +

)he newlastname-. function defines the person8s new last name and assigns that to the person. JavaScript knows which person &ou8re talking about b& using 4this.4. So, now &ou can write' m& other.newlastname-4>oe4..

You might also like