Transcript

Introduction to Introduction to JavaScriptJavaScript

T.ShanmugapriyaT.Shanmugapriya

IntroductionIntroduction

• What is it?• How does it work?• What is Java?• Learning JavaScript

– JavaScript Statements– JavaScript and HTML forms

What is JavaScript?What is JavaScript?• Browsers have limited functionality

– Text, images, tables, frames• JavaScript allows for interactivity• Browser/page manipulation

– Reacting to user actions• A type of programming language

– Easy to learn– Developed by Netscape– Now a standard exists – www.ecma-international.org/publications/standards/ECMA-262.HTM

JavaScript Allows InteractivityJavaScript Allows Interactivity

• Improve appearance – Especially graphics– Visual feedback

• Site navigation• Perform calculations• Validation of input• Other technologies

javascript.internet.com

How Does It Work?How Does It Work?

• Embedded within HTML page– View source

• Executes on client– Fast, no connection needed once loaded

• Simple programming statements combined with HTML tags

• Interpreted (not compiled)– No special tools required

What is Java?What is Java?

• Totally different• A full programming language• Much harder!• A compiled language• Independent of the web• Sometimes used together

JavaScript StatementsJavaScript Statements<html><head><title>My Page</title></head><body><script language="JavaScript">

document.write('This is my first JavaScript Page');

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

JavaScript StatementsJavaScript Statements<html><head><title>My Page</title></head><body><script language=“JavaScript">

document.write('<h1>This is my first JavaScript Page</h1>');

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

HTML writteninside JavaScript

JavaScript StatementsJavaScript Statements<html><head><title>My Page</title></head><body><p><a href="myfile.html">My Page</a><br /><a href="myfile.html"onMouseover="window.alert('Hello');">My Page</A></p></body></html>

JavaScript writteninside HTML

An Event

Example StatementsExample Statements<script language="JavaScript">

window.prompt('Enter your name:','');

</script>

<form>

<input type="button" Value="Press" onClick="window.alert('Hello');">

</form>

Another event

Note quotes: " and '

JavaScript CommentsJavaScript Comments

• Comments can be added to explain the JavaScript, or to make the code more readable.

• Single line comments start with //.• The following example uses single

line comments to explain the code:

• Example

<script type="text/javascript">// Write a headingdocument.write("<h1>This is a heading</h1>");// Write two paragraphs:document.write("<p>This is a paragraph.</p>");document.write("<p>This is another paragraph.</p>");</script>

JavaScript Multi-Line JavaScript Multi-Line CommentsComments

• Multi line comments start with /* and end with */.

• The following example uses a multi line comment to explain the code:

• Example

<script type="text/javascript">/*The code below will writeone heading and two paragraphs*/document.write("<h1>This is a heading</h1>");document.write("<p>This is a paragraph.</p>");document.write("<p>This is another paragraph.</p>");</script>

Using Comments at the End of Using Comments at the End of a Linea Line

• Example

<script type="text/javascript">document.write("Hello"); // Write "Hello"document.write(" Dolly!"); // Write " Dolly!"</script>

Simple Program: Printing a Line of Text in a Web Page

• Inline scripting– Written in the <body> of a document– <script> tag

• Indicate that the text is part of a script• type attribute

– Specifies the type of file and the scripting language use

• writeln method– Write a line in the document

• alert method– Dialog box

welcome.html(1 of 1)

1 <?xml version = "1.0"?>

2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

4

5 <!-- -->

6 <!-- Displaying a line of text -->

7

8 <html xmlns = "http://www.w3.org/1999/xhtml">

9 <head>

10 <title>A First Program in JavaScript</title>

11

12 <script type = "text/javascript">

13 <!--

14 document.writeln(

15 "<h1>Welcome to JavaScript Programming!</h1>" );

16 // -->

17 </script>

18

19 </head><body></body>

20 </html>

welcome2.html(1 of 1)

1 <?xml version = "1.0"?>

2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

4

5 <!-- -->

6 <!-- Printing a Line with Multiple Statements -->

7

8 <html xmlns = "http://www.w3.org/1999/xhtml">

9 <head>

10 <title>Printing a Line with Multiple Statements</title>

11

12 <script type = "text/javascript">

13 <!--

14 document.write( "<h1 style = \"color: magenta\">" );

15 document.write( "Welcome to JavaScript " +

16 "Programming!</h1>" );

17 // -->

18 </script>

19

20 </head><body></body>

21 </html>

welcome3.html1 of 1

1 <?xml version = "1.0"?>

2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

4

5 <!-- -->

6 <!-- Printing Multiple Lines -->

7

8 <html xmlns = "http://www.w3.org/1999/xhtml">

9 <head><title>Printing Multiple Lines</title>

10

11 <script type = "text/javascript">

12 <!--

13 document.writeln( "<h1>Welcome to<br />JavaScript" +

14 "<br />Programming!</h1>" );

15 // -->

16 </script>

17

18 </head><body></body>

19 </html>

welcome4.html1 of 1

1 <?xml version = "1.0"?>

2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

4

5

6 <!-- Printing multiple lines in a dialog box -->

7

8 <html xmlns = "http://www.w3.org/1999/xhtml">

9 <head><title>Printing Multiple Lines in a Dialog Box</title>

10

11 <script type = "text/javascript">

12 <!--

13 window.alert( "Welcome to\nJavaScript\nProgramming!"

);

14 // -->

15 </script>

16

17 </head>

18

19 <body>

20 <p>Click Refresh (or Reload) to run this script again.</p>

21 </body>

22 </html>

welcome5.html(1 of 2)

1 <?xml version = "1.0"?>

2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"

3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

4

5

6 <!-- Using Prompt Boxes -->

7

8 <html xmlns = "http://www.w3.org/1999/xhtml">

9 <head>

10 <title>Using Prompt and Alert Boxes</title>

11

12 <script type = "text/javascript">

13 <!--

14 var name; // string entered by the user

15

16 // read the name from the prompt box as a string

17 name = window.prompt( "Please enter your name", "GalAnt"

);

18

19 document.writeln( "<h1>Hello, " + name +

20 ", welcome to JavaScript programming!</h1>" );

21 // -->

22 </script>

welcome5.html(2 of 2)

23

24 </head>

25

26 <body>

27 <p>Click Refresh (or Reload) to run this script again.</p>

28 </body>

29 </html>

Adding Integers

• Prompt user for two integers and calculate the sum NaN (not a number)

• parseInt– Converts its string argument to an

integer

Addition.html(1 of 2)

1 <?xml version = "1.0"?>

2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

4

5 <!--

6 <!-- Addition Program -->

7

8 <html xmlns = "http://www.w3.org/1999/xhtml">

9 <head>

10 <title>An Addition Program</title>

11

12 <script type = "text/javascript">

13 <!--

14 var firstNumber, // first string entered by user

15 secondNumber, // second string entered by user

16 number1, // first number to add

17 number2, // second number to add

18 sum; // sum of number1 and number2

19

20 // read in first number from user as a string

21 firstNumber =

22 window.prompt( "Enter first integer", "0" );

23

Addition.html(2 of 2)

24 // read in second number from user as a string

25 secondNumber =

26 window.prompt( "Enter second integer", "0" );

27

28 // convert numbers from strings to integers

29 number1 = parseInt( firstNumber );

30 number2 = parseInt( secondNumber );

31

32 // add the numbers

33 sum = number1 + number2;

34

35 // display the results

36 document.writeln( "<h1>The sum is " + sum + "</h1>" );

37 // -->

38 </script>

39

40 </head>

41 <body>

42 <p>Click Refresh (or Reload) to run the script again</p>

43 </body>

44 </html>

ArithmeticArithmetic• Many scripts perform arithmetic

calculations– Expressions in JavaScript must be written in

straight-line form

ArithmeticArithmetic

• Precedence and associativity

JavaScript operation

Arithmetic operator

Algebraic expression

JavaScript expression

Addition + f + 7 f + 7

Subtraction - p – c p - c

Multiplication * bm b * m

Division / x / y or or x y x / y

Remainder % r mod s r % s

Operator(s) Operation(s) Order of evaluation (precedence) *, / or % Multiplication

Division Modulus

Evaluated second. If there are several such operations, they are evaluated from left to right.

+ or - Addition Subtraction

Evaluated last. If there are several such operations, they are evaluated from left to right.

ArithmeticArithmeticy = 2 * 5 * 5 + 3 * 5 + 7;

2 * 5 is 10 (Leftmost multiplication)

y = 10 * 5 + 3 * 5 + 7;

10 * 5 is 50 (Leftmost multiplication)

y = 50 + 3 * 5 + 7;

3 * 5 is 15 (Multiplication before addition)

y = 50 + 15 + 7;

50 + 15 is 65 (Leftmost addition)

y = 65 + 7;

65 + 7 is 72 (Last addition)

y = 72; (Last operation—place 72 into y )

Step 1.

Step 2.

Step 5.

Step 3.

Step 4.

Step 6.

Adding Strings and NumbersAdding Strings and Numbers• The rule is: If you add a number and a string, the result will

be a string!

• Examplex=5+5;document.write(x);

x="5"+"5";document.write(x);

x=5+"5";document.write(x);

x="5"+5;document.write(x);

Decision Making: Equality and Decision Making: Equality and Relational OperatorsRelational Operators

• Decision based on the truth or falsity of a condition– Equality operators– Relational operators

Decision Making: Equality and Decision Making: Equality and Relational OperatorsRelational Operators

Standard algebraic equality operator or relational operator

JavaScript equality or relational operator

Sample JavaScript condition

Meaning of JavaScript condition

Equality operators = == x == y x is equal to y != x != y x is not equal to y Relational operators > > x > y x is greater than y < < x < y x is less than y >= x >= y x is greater than or

equal to y <= x <= y x is less than or

equal to y

Decision Making: Equality and Decision Making: Equality and Relational OperatorsRelational Operators

• Precedence and associativity

Operators Associativity Type * / % left to right multiplicative + - left to right additive < <= > >= left to right relational == != left to right equality = right to left assignment

JavaScript Assignment OperatorsJavaScript Assignment Operators

• Assignment operators are used to assign values to JavaScript variables.

Assignment operator

Initial value of variable

Sample expression

Explanation Assigns

+= c = 3 c += 7 c = c + 7

10 to c

-= d = 5 d -= 4 d = d - 4

1 to d

*= e = 4 e *= 5 e = e * 5

20 to e

/= f = 6 f /= 3 f = f / 3

2 to f

%= g = 12 g %= 9 g = g % 9

3 to g

Increment and Decrement Increment and Decrement OperatorsOperators

• Preincrement or predecrement operator– Increment of decrement operator placed

before a variable

• Postincrement or postdecrement operator– Increment of decrement operator placed after

a variable

Increment and Decrement Increment and Decrement OperatorsOperators

Operator Called Sample expression

Explanation

++ preincrement ++a Increment a by 1, then use the new value of a in the expression in which a resides.

++ postincrement a++ Use the current value of a in the expression in which a resides, then increment a by 1.

-- predecrement --b Decrement b by 1, then use the new value of b in the expression in which b resides.

-- postdecrement b-- Use the current value of b in the expression in which b resides, then decrement b by 1.

Increment and Decrement Increment and Decrement OperatorsOperators

• Precedence and associativity

Operator Associativity Type ++ -- right to left unary * / % left to right multiplicative + - left to right additive < <= > >= left to right relational == != left to right equality ?: right to left conditional = += -= *= /= %= right to left assignment

Logical OperatorsLogical Operators• More logical operators

– Logical AND ( && )– Logical OR ( || )– Logical NOT ( ! )

• Truth table for the && (logical AND) operator.

expression1 expression2 expression1 && expression2

false false false false true false true false false true true true

Logical OperatorsLogical Operators• Truth table for the || (logical OR) operator.

• Truth table for operator ! (logical negation).

expression1 expression2 expression1 || expression2

false false false false true true true false true true true true

expression !expression false true true false

Logical OperatorsLogical Operators• Precedence and associativity

Operator Associativity Type ++ -- ! right to left unary * / % left to right multiplicative + - left to right additive < <= > >= left to right relational == != left to right equality && left to right logical AND || left to right logical OR ?: right to left conditional = += -= *= /= %= right to left assignment

Conditional StatementsConditional Statements

• In JavaScript we have the following conditional statements:

• if statement - use this statement to execute some code only if a specified condition is true

• if...else statement - use this statement to execute some code if the condition is true and another code if the condition is false

• if...else if....else statement - use this statement to select one of many blocks of code to be executed

• switch statement - use this statement to select one of many blocks of code to be executed

If StatementIf Statement

• Use the if statement to execute some code only if a specified condition is true.

• Syntaxif (condition)  {  code to be executed if condition is true  }

ExampleExample

• <script type="text/javascript">//Write a "Good morning" greeting if//the time is less than 10

var d=new Date();var time=d.getHours();

if (time<10)  {  document.write("<b>Good morning</b>");  }</script>

If...else StatementIf...else Statement

• Use the if....else statement to execute some code if a condition is true and another code if the condition is not true.

• Syntaxif (condition)  {  code to be executed if condition is true  }else  {  code to be executed if condition is not true  }

ExampleExample

• <script type="text/javascript">//If the time is less than 10, you will get a "Good morning" greeting.//Otherwise you will get a "Good day" greeting.

var d = new Date();var time = d.getHours();

if (time < 10)  {  document.write("Good morning!");  }else  {  document.write("Good day!");  }</script>

If...else if...else StatementIf...else if...else Statement

• Use the if....else if...else statement to select one of several blocks of code to be executed.

• Syntaxif (condition1)  {  code to be executed if condition1 is true  }else if (condition2)  {  code to be executed if condition2 is true  }else  {  code to be executed if condition1 and condition2 are not true  }

ExampleExample

• <script type="text/javascript">var d = new Date()var time = d.getHours()if (time<10)  {  document.write("<b>Good morning</b>");  }else if (time>10 && time<16)  {  document.write("<b>Good day</b>");  }else  {  document.write("<b>Hello World!</b>");  }</script>

The JavaScript Switch StatementThe JavaScript Switch Statement

• Use the switch statement to select one of many blocks of code to be executed.

• Syntaxswitch(n){case 1:  execute code block 1  break;case 2:  execute code block 2  break;default:  code to be executed if n is different from case 1 and 2}

ExampleExample

• <script type="text/javascript">//You will receive a different greeting based//on what day it is. Note that Sunday=0,//Monday=1, Tuesday=2, etc.

var d=new Date();theDay=d.getDay();switch (theDay){case 5:  document.write("Finally Friday");  break;case 6:  document.write("Super Saturday");  break;case 0:  document.write("Sleepy Sunday");  break;default:  document.write("I'm looking forward to this weekend!");}</script>

Function Definitions

• Format of a function definition

function function-name( parameter-list ){ declarations and statements}

– Function name any valid identifier– Parameter list names of variables that will

receive arguments• Must have same number as function call• May be empty

– Declarations and statements• Function body (“block” of code)

Function Definitions

• Returning control– return statement– Can return either nothing, or a valuereturn expression;

– No return statement same as return;– Not returning a value when expected

is an error

Function Definitions

• Writing a function to square two numbers– for loop from 1 to 10– Pass each number as argument to square

– return value of argument multiplied by itself

– Display result

1 <?xml version = "1.0"?>

2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

4

5

6 <!-- Square function -->

7

8 <html xmlns = "http://www.w3.org/1999/xhtml">

9 <head>

10 <title>A Programmer-Defined square Function</title>

11

12 <script type = "text/javascript">

13 <!--

14 document.writeln(

15 "<h1>Square the numbers from 1 to 10</h1>" );

16

17 // square the numbers from 1 to 10

18 for ( var x = 1; x <= 10; ++x )

19 document.writeln( "The square of " + x + " is " +

20 square( x ) + "<br />" );

21

Calling function square and passing it the value of x.

22 // The following square function's body is executed

23 // only when the function is explicitly called.

24

25 // square function definition

26 function square( y )

27 {

28 return y * y;

29 }

30 // -->

31 </script>

32

33 </head><body></body>

34 </html>

Variable y gets the value of variable x.

The return statement passes the value of y * y back to the calling function.

Function Definitions

Function Definitions• Finding the maximum of 3

numbers– Prompt for 3 inputs– Convert to numbers– Pass to maximum– Math.max

1 <?xml version = "1.0"?>

2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

4

6 <!-- Maximum function -->

7

8 <html xmlns = "http://www.w3.org/1999/xhtml">

9 <head>

10 <title>Finding the Maximum of Three Values</title>

11

12 <script type = "text/javascript">

13 <!--

14 var input1 =

15 window.prompt( "Enter first number", "0" );

16 var input2 =

17 window.prompt( "Enter second number", "0" );

18 var input3 =

19 window.prompt( "Enter third number", "0" );

20

21 var value1 = parseFloat( input1 );

22 var value2 = parseFloat( input2 );

23 var value3 = parseFloat( input3 );

Prompt for the user to input three integers.

24

25 var maxValue = maximum( value1, value2, value3 );

26

27 document.writeln( "First number: " + value1 +

28 "<br />Second number: " + value2 +

29 "<br />Third number: " + value3 +

30 "<br />Maximum is: " + maxValue );

31

32 // maximum method definition (called from line 25)

33 function maximum( x, y, z )

34 {

35 return Math.max( x, Math.max( y, z ) );

36 }

37 // -->

38 </script>

39

40 </head>

41 <body>

42 <p>Click Refresh (or Reload) to run the script again</p>

43 </body>

44 </html>

Call function maximum and pass it the value of variables value1, value2 and value3.

Variables x, y and z get the value of variables value1, value2 and value3, respectively.

Method max returns the larger of the two integers passed to it.

Function Definitions

Function Definitions

JavaScript LoopsJavaScript Loops

• In JavaScript, there are two different kind of loops:

• for - loops through a block of code a specified number of times

• while - loops through a block of code while a specified condition is true

The for LoopThe for Loop

• The for loop is used when you know in advance how many times the script should run.

• Syntaxfor (var=startvalue;var<=endvalue;var=var+increment){code to be executed}

ExampleExample

• <html><body><script type="text/javascript">var i=0;for (i=0;i<=5;i++){document.write("The number is " + i);document.write("<br />");}</script></body></html>

The while LoopThe while Loop

• The while loop loops through a block of code while a specified condition is true.

• Syntaxwhile (var<=endvalue)  {  code to be executed  }

ExampleExample

• <html><body><script type="text/javascript">var i=0;while (i<=5)  {  document.write("The number is " + i);  document.write("<br />");  i++;  }</script></body></html>

The do...while LoopThe do...while Loop

• The do...while loop is a variant of the while loop. This loop will execute the block of code ONCE, and then it will repeat the loop as long as the specified condition is true.

• Syntaxdo  {  code to be executed  }while (var<=endvalue);

ExampleExample

• <html><body><script type="text/javascript">var i=0;do  {  document.write("The number is " + i);  document.write("<br />");  i++;  }while (i<=5);</script></body></html>

JavaScript Break and Continue JavaScript Break and Continue StatementsStatements

• The break Statement

The break statement will break the loop and continue executing the code that follows after the loop (if any).

ExampleExample

• <html><body><script type="text/javascript">var i=0;for (i=0;i<=10;i++)  {  if (i==3)    {    break;    }  document.write("The number is " + i);  document.write("<br />");  }</script></body></html>

• The continue Statement

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

ExampleExample

• <html><body><script type="text/javascript">var i=0for (i=0;i<=10;i++)  {  if (i==3)    {    continue;    }  document.write("The number is " + i);  document.write("<br />");  }</script></body></html>

JavaScript For...In StatementJavaScript For...In Statement

• The for...in statement loops through the elements of an array or through the properties of an object.

• Syntaxfor (variable in object)  {  code to be executed  }

ExampleExample

• <html><body><script type="text/javascript">var x;var mycars = new Array();mycars[0] = "Saab";mycars[1] = "Volvo";mycars[2] = "BMW";for (x in mycars)  {  document.write(mycars[x] + "<br />");  }</script></body></html>

JavaScript Popup BoxesJavaScript Popup Boxes

• JavaScript has three kind of popup boxes:– Alert box,– Confirm box, and – Prompt box.

Alert BoxAlert Box

• An alert box is often used if you want to make sure information comes through to the user.

• When an alert box pops up, the user will have to click "OK" to proceed.

• Syntaxalert("sometext");

ExampleExample

<html><head><script type="text/javascript">function show_alert(){alert("I am an alert box!");}</script></head><body>

<input type="button" onclick="show_alert()" value="Show alert box" />

</body></html>

Confirm BoxConfirm Box

• A confirm box is often used if you want the user to verify or accept something.

• When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed.

• If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns false.

• Syntaxconfirm("sometext");

ExampleExample

• <html><head><script type="text/javascript">function show_confirm(){var r=confirm("Press a button");if (r==true)  {  alert("You pressed OK!");  }else  {  alert("You pressed Cancel!");  }}</script></head><body>

<input type="button" onclick="show_confirm()" value="Show confirm box" />

</body></html>

Prompt BoxPrompt Box

• A prompt box is often used if you want the user to input a value before entering a page.

• When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after entering an input value.

• If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the box returns null.

• Syntaxprompt("sometext","defaultvalue");

JavaScript FunctionsJavaScript Functions

• How to Define a Function

• Syntaxfunction functionname(var1,var2,...,varX){some code}

ExampleExample

• <html><head><script type="text/javascript">function displaymessage(){alert("Hello World!");}</script></head>

ExampleExampleContd...Contd...

<body><form><input type="button" value="Click me!" onclick="displaymessage()" /></form></body></html>

EventsEvents

• Events are actions that can be detected by JavaScript.

• Examples of events:– A mouse click– A web page or an image loading– Mousing over a hot spot on the web page– Selecting an input field in an HTML form– Submitting an HTML form– A keystroke

• onLoad and onUnloadThe onLoad and onUnload events are

triggered when the user enters or leaves the page.

• onFocus, onBlur and onChangeThe onFocus, onBlur and onChange

events are often used in combination with validation of form fields.– <input type="text" size="30" id="email"

onchange="checkEmail()">

• onSubmitThe onSubmit event is used to validate

ALL form fields before submitting it.– <form method="post" action=“abc.htm"

onsubmit="return checkForm()">

• onMouseOver and onMouseOutonMouseOver and onMouseOut are

often used to create "animated" buttons.– <a href="http://www.annauniv.edu" onmouseover="alert('An

onMouseOver event');return false"><img src=“anna.gif" alt=“annauniv" /></a>

JavaScript Try...Catch StatementJavaScript Try...Catch Statement

• The try...catch statement allows you to test a block of code for errors.

• Syntax• try

  {  //Run some code here  }catch(err)  {  //Handle errors here  }

ExampleExample

• <html><head><script type="text/javascript">var txt="";function message(){try  {  adddlert("Welcome guest!");  }catch(err)  {  txt="There was an error on this page.\n\n";  txt+="Error description: " + err.description + "\n\n"; 

ExampleExampleContd...Contd...

• txt+="Click OK to continue.\n\n";  alert(txt);  }}</script></head>

<body><input type="button" value="View message" onclick="message()" /></body>

</html>

The Throw StatementThe Throw Statement

• The throw statement allows you to create an exception. If you use this statement together with the try...catch statement, you can control program flow and generate accurate error messages.

• Syntaxthrow(exception)

ExampleExample

• <html><body><script type="text/javascript">var x=prompt("Enter a number between 0 and 10:","");try  {   if(x>10)    {    throw "Err1";    }  else if(x<0)    {    throw "Err2";    }  else if(isNaN(x))    {    throw "Err3";    }  }

ExampleExampleContd...Contd...

• catch(er)  {  if(er=="Err1")    {    alert("Error! The value is too high");    }  if(er=="Err2")    {    alert("Error! The value is too low");    }  if(er=="Err3")    {    alert("Error! The value is not a number");    }  }</script></body></html>

JavaScript ObjectsJavaScript Objects

• JavaScript is an Object Oriented Programming (OOP) language.

• An OOP language allows you to define your own objects and make your own variable types.

  Introduction

• Use JavaScript to manipulate every element of XHTML document from a script

• Reference for several of JavaScript’s built-in objects

• Demonstrates the capabilities

12.2  Thinking About Objects

• Objects– Attributes– Behaviors– Encapsulate data and methods– Property of information hiding– Details hidden within the objects

themselves

 Math Object

• Allow the programmer to perform many common mathematical calculations

12.3  Math ObjectMethod Description Example abs( x ) absolute value of x abs( 7.2 ) is 7.2

abs( 0.0 ) is 0.0 abs( -5.6 ) is 5.6

ceil( x ) rounds x to the smallest integer not less than x

ceil( 9.2 ) is 10.0 ceil( -9.8 ) is -9.0

cos( x ) trigonometric cosine of x (x in radians)

cos( 0.0 ) is 1.0

exp( x ) exponential method ex exp( 1.0 ) is 2.71828 exp( 2.0 ) is 7.38906

floor( x ) rounds x to the largest integer not greater than x

floor( 9.2 ) is 9.0 floor( -9.8 ) is -10.0

log( x ) natural logarithm of x (base e)

log( 2.718282 ) is 1.0 log( 7.389056 ) is 2.0

max( x, y ) larger value of x and y max( 2.3, 12.7 ) is 12.7 max( -2.3, -12.7 ) is -2.3

.

 Math Objectmin( x, y ) smaller value of x

and y min( 2.3, 12.7 ) is 2.3 min( -2.3, -12.7 ) is -12.7

pow( x, y ) x raised to power y (xy)

pow( 2.0, 7.0 ) is 128.0 pow( 9.0, .5 ) is 3.0

round( x ) rounds x to the closest integer

round( 9.75 ) is 10 round( 9.25 ) is 9

sin( x ) trigonometric sine of x (x in radians)

sin( 0.0 ) is 0.0

sqrt( x ) square root of x sqrt( 900.0 ) is 30.0 sqrt( 9.0 ) is 3.0

tan( x ) trigonometric tangent of x (x in radians)

tan( 0.0 ) is 0.0

Fig. 12.1 Math object methods.

 Math ObjectConstant Description Value Math.E Base of a natural

logarithm (e). Approximately 2.718.

Math.LN2 Natural logarithm of 2. Approximately 0.693. Math.LN10 Natural logarithm of 10. Approximately 2.302. Math.LOG2E Base 2 logarithm of e. Approximately 1.442. Math.LOG10E Base 10 logarithm of e. Approximately 0.434. Math.PI —the ratio of a circle’s

circumference to its diameter.

Approximately 3.141592653589793.

Math.SQRT1_2 Square root of 0.5. Approximately 0.707. Math.SQRT2 Square root of 2.0. Approximately 1.414. Fig. 12.2 Properties of the Math object.

 Date Object

• Provides methods for date and time manipulations

12.5  Date ObjectMethod Description

getDate() getUTCDate()

Returns a number from 1 to 31 representing the day of the month in local time or UTC, respectively.

getDay() getUTCDay()

Returns a number from 0 (Sunday) to 6 (Saturday) representing the day of the week in local time or UTC, respectively.

getFullYear() getUTCFullYear()

Returns the year as a four-digit number in local time or UTC, respectively.

getHours() getUTCHours()

Returns a number from 0 to 23 representing hours since midnight in local time or UTC, respectively.

getMilliseconds() getUTCMilliSeconds()

Returns a number from 0 to 999 representing the number of milliseconds in local time or UTC, respectively. The time is stored in hours, minutes, seconds and milliseconds.

getMinutes() getUTCMinutes()

Returns a number from 0 to 59 representing the minutes for the time in local time or UTC, respectively.

getMonth() getUTCMonth()

Returns a number from 0 (January) to 11 (December) representing the month in local time or UTC, respectively.

getSeconds() getUTCSeconds()

Returns a number from 0 to 59 representing the seconds for the time in local time or UTC, respectively.

getTime() Returns the number of milliseconds between January 1, 1970 and the time in the Date object.

getTimezoneOffset() Returns the difference in minutes between the current time on the local computer and UTC—previously known as Greenwich Mean Time (GMT).

setDate( val ) setUTCDate( val )

Sets the day of the month (1 to 31) in local time or UTC, respectively.

Fig. 12.8 Methods of the Date object.

12.5  Date ObjectMethod Description

setFullYear( y, m, d ) setUTCFullYear( y, m, d )

Sets the year in local time or UTC, respectively. The second and third arguments representing the month and the date are optional. If an optional argument is not specified, the current value in the Date object is used.

setHours( h, m, s, ms ) setUTCHours( h, m, s, ms )

Sets the hour in local time or UTC, respectively. The second, third and fourth arguments representing the minutes, seconds and milliseconds are optional. If an optional argument is not specified, the current value in the Date object is used.

setMilliSeconds( ms ) setUTCMilliseconds( ms )

Sets the number of milliseconds in local time or UTC, respectively.

setMinutes( m, s, ms ) setUTCMinutes( m, s, ms )

Sets the minute in local time or UTC, respectively. The second and third arguments representing the seconds and milliseconds are optional. If an optional argument is not specified, the current value in the Date object is used.

setMonth( m, d ) setUTCMonth( m, d )

Sets the month in local time or UTC, respectively. The second argument representing the date is optional. If the optional argument is not specified, the current date value in the Date object is used.

setSeconds( s, ms ) setUTCSeconds( s, ms )

Sets the second in local time or UTC, respectively. The second argument representing the milliseconds is optional. If this argument is not specified, the current millisecond value in the Date object is used.

Fig. 12.8 Methods of the Date object.

12.5  Date ObjectMethod Description

setTime( ms ) Sets the time based on its argument—the number of elapsed milliseconds since January 1, 1970.

toLocaleString() Returns a string representation of the date and time in a form specific to the computer’s locale. For example, September 13, 2001 at 3:42:22 PM is represented as 09/13/01 15:47:22 in the United States and 13/09/01 15:47:22 in Europe.

toUTCString() Returns a string representation of the date and time in the form: 19 Sep 2001 15:47:22 UTC

toString() Returns a string representation of the date and time in a form specific to the locale of the computer (Mon Sep 19 15:47:22 EDT 2001 in the United States).

valueOf() The time in number of milliseconds since midnight, January 1, 1970.

Fig. 12.8 Methods of the Date object.

DateTime.html1 of 3

1 <?xml version = "1.0"?>

2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

4

5 <!-- Fig. 12.9: DateTime.html -->

6 <!-- Date and Time Methods -->

7

8 <html xmlns = "http://www.w3.org/1999/xhtml">

9 <head>

10 <title>Date and Time Methods</title>

11

12 <script type = "text/javascript">

13 <!--

14 var current = new Date();

15

16 document.writeln(

17 "<h1>String representations and valueOf</h1>" );

18 document.writeln( "toString: " + current.toString() +

19 "<br />toLocaleString: " + current.toLocaleString() +

20 "<br />toUTCString: " + current.toUTCString() +

21 "<br />valueOf: " + current.valueOf() );

22

23 document.writeln(

24 "<h1>Get methods for local time zone</h1>" );

DateTime.html2 of 3

25 document.writeln( "getDate: " + current.getDate() +

26 "<br />getDay: " + current.getDay() +

27 "<br />getMonth: " + current.getMonth() +

28 "<br />getFullYear: " + current.getFullYear() +

29 "<br />getTime: " + current.getTime() +

30 "<br />getHours: " + current.getHours() +

31 "<br />getMinutes: " + current.getMinutes() +

32 "<br />getSeconds: " + current.getSeconds() +

33 "<br />getMilliseconds: " +

34 current.getMilliseconds() +

35 "<br />getTimezoneOffset: " +

36 current.getTimezoneOffset() );

37

38 document.writeln(

39 "<h1>Specifying arguments for a new Date</h1>" );

40 var anotherDate = new Date( 2001, 2, 18, 1, 5, 0, 0 );

41 document.writeln( "Date: " + anotherDate );

42

43 document.writeln(

44 "<h1>Set methods for local time zone</h1>" );

45 anotherDate.setDate( 31 );

46 anotherDate.setMonth( 11 );

47 anotherDate.setFullYear( 2001 );

48 anotherDate.setHours( 23 );

49 anotherDate.setMinutes( 59 );

50 anotherDate.setSeconds( 59 );

51 document.writeln( "Modified date: " + anotherDate );

52 // -->

53 </script>

54

55 </head><body></body>

56 </html>

JavaScript Date ObjectJavaScript Date Object

• The Date object is used to work with dates and times.

• Date objects are created with the Date() constructor.

• There are four ways of instantiating a date:– new Date() // current date and time– new Date(milliseconds) //milliseconds since 1970/01/01– new Date(dateString)– new Date(year, month, day, hours, minutes, seconds,

milliseconds)

• To set a Date object to a specific date (30th November 2010):– var myDate=new Date();

myDate.setFullYear(2010,10,30);

• To set a Date object to be 5 days into the future:– var myDate=new Date();

myDate.setDate(myDate.getDate()+5);

• Compare Two Datesvar myDate=new Date();myDate.setFullYear(2010,10,30);var today = new Date();

if (myDate>today)  {  alert("Today is before 30th November 2010");  }else  {  alert("Today is after 30th November 2010");  }

12.6  Boolean and Number Objects

• Object wrappers for boolean true/false values and numbers

12.6  Boolean and Number ObjectsMethod Description

toString() Returns the string “true” if the value of the Boolean object is true; otherwise, returns the string “false.”

valueOf() Returns the value true if the Boolean object is true; otherwise, returns false.

Fig. 12.10 Boolean object methods.

12.6  Boolean and Number ObjectsMethod or Property Description

toString( radix ) Returns the string representation of the number. The optional radix argument (a number from 2 to 36) specifies the number’s base. For example, radix 2 results in the binary representation of the number, 8 results in the octal representation, 10 results in the decimal representation and 16 results in the hexadecimal representation. See Appendix E, Number Systems for a review of the binary, octal, decimal and hexadecimal number systems.

valueOf() Returns the numeric value. Number.MAX_VALUE This property represents the largest value that can be stored in a

JavaScript program—approximately 1.79E+308

Number.MIN_VALUE This property represents the smallest value that can be stored in a JavaScript program—approximately 2.22E–308

Number.NaN This property represents not a number—a value returned from an arithmetic expression that does not result in a number (e.g., the expression parseInt( "hello" ) cannot convert the string "hello" into a number, so parseInt would return Number.NaN. To determine whether a value is NaN, test the result with function isNaN, which returns true if the value is NaN; otherwise, it returns false.

Number.NEGATIVE_INFINITY This property represents a value less than -Number.MAX_VALUE.

Number.POSITIVE_INFINITY This property represents a value greater than Number.MAX_VALUE.

Fig. 12.11 Number object methods and properties.

JavaScript Boolean ObjectJavaScript Boolean Object

• The Boolean object is used to convert a non-Boolean value to a Boolean value (true or false).

• The following code creates a Boolean object called myBoolean:

-var myBoolean=new Boolean();

• All the following lines of code create Boolean objects with an initial value of false:var myBoolean=new Boolean();var myBoolean=new Boolean(0);var myBoolean=new Boolean(null);var myBoolean=new Boolean("");var myBoolean=new Boolean(false);var myBoolean=new Boolean(NaN);

• And all the following lines of code create Boolean objects with an initial value of true:var myBoolean=new Boolean(1);var myBoolean=new Boolean(true);var myBoolean=new Boolean("true");var myBoolean=new Boolean("false");var myBoolean=new Boolean("Richard");

JavaScript Math ObjectJavaScript Math Object

• The Math object allows you to perform mathematical tasks.

– round()How to use round().

– random()How to use random() to return a random number between 0 and 1.

– max()How to use max() to return the number with the highest value of two specified numbers.

– min()How to use min() to return the number with the lowest value of two specified numbers.

Mathematical ConstantsMathematical Constants

– Math.E– Math.PI– Math.SQRT2– Math.SQRT1_2– Math.LN2– Math.LN10– Math.LOG2E– Math.LOG10E

Mathematical MethodsMathematical Methods

• Few Examples:

– document.write(Math.round(4.7));– document.write(Math.random());– document.write(Math.floor(Math.random()*11));

JavaScript Browser DetectionJavaScript Browser Detection• The Navigator object contains information about the visitor's browser.• Example• <html>

<body><script type="text/javascript">document.write("Browser CodeName: " + navigator.appCodeName);document.write("<br /><br />");document.write("Browser Name: " + navigator.appName);document.write("<br /><br />");document.write("Browser Version: " + navigator.appVersion);document.write("<br /><br />");document.write("Cookies Enabled: " + navigator.cookieEnabled);document.write("<br /><br />");document.write("Platform: " + navigator.platform);document.write("<br /><br />");document.write("User-agent header: " + navigator.userAgent);</script></body></html>

Java Script String Object

Method Description

anchor() Creates an HTML anchor

big() Displays a string in a big font

blink() Displays a blinking string

bold() Displays a string in bold

charAt() Returns the character at a specified position

charCodeAt() Returns the Unicode of the character at a specified position

concat() Joins two or more strings

fixed() Displays a string as teletype text

fontcolor() Displays a string in a specified color

fontsize() Displays a string in a specified size

fromCharCode()

Takes the specified Unicode values and returns a string

indexOf() Returns the position of the first occurrence of a specified string value in a string

String Object

italics() Displays a string in italic

lastIndexOf() Returns the position of the last occurrence of a specified string value, searching backwards from the specified position in a string

link() Displays a string as a hyperlink

match() Searches for a specified value in a string

replace() Replaces some characters with some other characters in a string

search() Searches a string for a specified value

slice() Extracts a part of a string and returns the extracted part in a new string

small() Displays a string in a small font

split() Splits a string into an array of strings

strike() Displays a string with a strikethrough

String object

sub() Displays a string as subscript

substr() Extracts a specified number of characters in a string, from a start index

substring() Extracts the characters in a string between two specified indices

sup() Displays a string as superscript

toLowerCase() Displays a string in lowercase letters

toUpperCase() Displays a string in uppercase letters

toSource() Represents the source code of an object

valueOf() Returns the primitive value of a String object

String Object Properties

constructor A reference to the function that created the object

length Returns the number of characters in a string

prototype Allows you to add properties and methods to the object

CharAt method

• The charAt() method returns the character at a specified position.

– stringObject.charAt(index)

• In the string "Hello world!", we will return the character at position 1:

<script type="text/javascript"> var str="Hello world!"; document.write(str.charAt(1));</script>

Index of Method• The indexOf() method returns the position of the first

occurrence of a specified string value in a string.– stringObject.indexOf(searchvalue,fromindex)

• Specifies a string value to search forfromindexOptional. Specifies where to start the searchNote: This method returns -1 if the string value to search for never occurs.

Example• In this example we will do different searches within a "Hello

world!" string:<script type="text/javascript">

var str="Hello world!"; document.write(str.indexOf("Hello") + "<br />"); document.write(str.indexOf("World") + "<br />"); document.write(str.indexOf("world"));</script>

Substring method

• The substring() method extracts the characters in a string between two specified indices.

• Syntax• stringObject.substring(start,stop)

we will use substring() to extract some characters from a string:• <script type="text/javascript">

var str="Hello world!"; document.write(str.substring(3)); </script>The output of the code above will be:

lo world!• <script type="text/javascript">• var str="Hello world!";

document.write(str.substring(3,7)); </script>The output of the code above will be:• lo w

toSource method• <script type="text/javascript"> var str="Hello world!"; document.write(str.substring(3,7)); </script>The output of the code above will be:• lo wThe toSource() method represents the source code of an object.• object.toSource()

<script type="text/javascript"> function employee(name,jobtitle,born) {this.name=name; this.jobtitle=jobtitle;this.born=born;} var fred=new employee("Fred Flintstone","Caveman",1970); document.write(fred.toSource()); </script>

The output of the code above will be:• ({name:"Fred Flintstone", jobtitle:"Caveman", born:1970})

Slice• The slice() method extracts a part of a string and returns

the extracted part in a new string.• Syntax• stringObject.slice(start,end)

• Specify where to start the selection. Must be a numberendOptional. Specify where to end the selection. Must be a number.

In this example we will extract all characters from a string, starting at position 6:

• <script type="text/javascript">var str="Hello happy world!";document.write(str.slice(6));</script>

The output of the code above will be:• happy world!

Search• The search() method is used to search a string for

a specified value.• Syntax• stringObject.search(searchstring)

• The value to search for in a string. To perform a case-insensitive search add an 'i' flag.

In the following example we will search for the word "W3Schools":

• <script type="text/javascript">var str="Visit W3Schools!";document.write(str.search(/W3Schools/));</script>

The output of the code above will be:• 6

Replace• The replace() method is used to replace some characters with

some other characters in a string.• Syntax• stringObject.replace(findstring,newstring)

• Specifies a string value to find. To perform a global search add a 'g' flag to this parameter and to perform a case-insensitive search add an 'i' flagnewstringRequired.

• Specifies the string to replace the found value from findstring.In the following example we will replace the word Microsoft with

W3Schools:• <script type="text/javascript">var str="Visit

Microsoft!";document.write(str.replace(/Microsoft/, "W3Schools"));</script>

The output of the code above will be:• Visit W3Schools!

Match method• <script type="text/javascript">

var str="Hello world!"; document.write(str.match("world") +

"<br />"); document.write(str.match("World") +

"<br/>"); document.write(str.match("worlld") +

"<br />"); document.write(str.match("world!")); </script>The output of the code above will be:• worldnullnullworld!

Split method• <script type="text/javascript">var

str="How are you doing today?"; document.write(str.split(" ") + "<br />"); document.write(str.split("") + "<br />"); document.write(str.split(" ",3)); </script>The output of the code above will be:• How,are,you,doing,today?

H,o,w, ,a,r,e, ,y,o,u, ,d,o,i,n,g, ,t,o,d,a,y,?How,are,you

JavaScript String ObjectJavaScript String Object

• The String object is used to manipulate a stored piece of text.

• Examples:– var txt="Hello world!";

document.write(txt.length);

– var txt="Hello world!";document.write(txt.toUpperCase());

JavaScript Array ObjectJavaScript Array Object

• The Array object is used to store multiple values in a single variable.

• Create an Array– An array can be defined in three ways.

• 1)var myCars=new Array(); // regular array (add an optional integermyCars[0]="Saab";       // argument to control array's size)myCars[1]="Volvo";myCars[2]="BMW";

• 2) var myCars=new Array("Saab","Volvo","BMW"); // condensed array

• 3) var myCars=["Saab","Volvo","BMW"]; // literal array

• Access an Array– document.write(myCars[0]);

• Modify Values in an Array– myCars[0]="Opel";

Array Object

concat() Joins two or more arrays and returns the result

join() Puts all the elements of an array into a string. The elements are separated by a specified delimiter

pop() Removes and returns the last element of an array

push() Adds one or more elements to the end of an array and returns the new length

reverse() Reverses the order of the elements in an array

shift() Removes and returns the first element of an array

slice() Returns selected elements from an existing array

Array Object

sort() Sorts the elements of an array

splice() Removes and adds new elements to an array

toSource()

Represents the source code of an object

toString()

Converts an array to a string and returns the result

unshift() Adds one or more elements to the beginning of an array and returns the new length

valueOf() Returns the primitive value of an Array object

Array Examples - concat• The concat() method is used to join two or more arrays.• This method does not change the existing arrays, it only

returns a copy of the joined arrays.• Syntax• arrayObject.concat(arrayX,arrayX,......,arrayX)• One or more array objects to be joined to an array.

Here we create two arrays and show them as one using concat():

• <script type="text/javascript"> var arr = new Array(3); arr[0] = "Jani";arr[1] = "Tove";arr[2] = "Hege";var arr2 =

new Array(3);arr2[0] = "John";arr2[1] = "Andy";arr2[2] = "Wendy";

document.write(arr.concat(arr2));</script>

Join method• The join() method is used to put all the elements of

an array into a string.• The elements will be separated by a specified

separator.• Syntax• arrayObject.join(separator)• Specifies the separator to be used.we will create an array, and then put all the elements in

a string:• <script type="text/javascript">var arr = new

Array(3);arr[0] = "Jani";arr[1] = "Hege";arr[2] = "Stale";document.write(arr.join() + "<br />");document.write(arr.join("."));</script>

The output of the code above will be:• Jani,Hege,StaleJani.Hege.Stale

Push method• The push() method adds one or more elements to the end of

an array and returns the new length.• Syntax• arrayObject.push(newelement1,newelement2,....,newelement

X)• The first element to add to the arraynewelement2Optional.

The second element to add to the arraynewelementXOptional. Several elements may be added.

In this example we will create an array, and then change the length of it by adding a element:

• <script type="text/javascript">var arr = new Array(3);arr[0] = "Jani";arr[1] = "Hege";arr[2] = "Stale";document.write(arr + "<br />");document.write(arr.push("Kai Jim") + "<br />");document.write(arr);</script>

The output of the code above will be:• Jani,Hege,Stale• Jani,Hege,Stale,Kai Jim

Slice method• <script type="text/javascript">

var arr = new Array(3);arr[0] = "Jani";arr[1] = "Hege";arr[2] = "Stale";document.write(arr + "<br />");document.write(arr.slice(1) + "<br />");document.write(arr);

</script>The output of the code above will be:• Jani,Hege,Stale• Hege,Stale• Jani,Hege,Stale

Sorting<script type="text/javascript">var arr = new Array(6);arr[0] = "Jani";arr[1] = "Hege";arr[2] = "Stale";arr[3] = "Kai Jim";arr[4] = "Borge";arr[5] = "Tove";document.write(arr + "<br />");document.write(arr.sort());</script>

Splice method• The splice() method is used to remove and add new elements to an array.• Syntax• arrayObject.splice(index,howmany,element1,.....,elementX)• Specify where to add/remove elements. • Must be a numberhowmanyRequired • Specify how many elements should be removed. Must be a number, but

can be "0"element1Optional.• Specify a new element to add to the arrayelementXOptional. Several

elements can be added

In this example we will create an array and add an element to it:• <script type="text/javascript">var arr = new Array(5);arr[0] = "Jani";arr[1]

= "Hege";arr[2] = "Stale";arr[3] = "Kai Jim";arr[4] = "Borge";document.write(arr + "<br />");arr.splice(2,0,"Lene");document.write(arr + "<br />");</script>

The output of the code above will be:• Jani,Hege,Stale,Kai Jim,Borge• Jani,Hege,Lene,Stale,Kai Jim,Borge

Create an array and convert it into String

• <script type="text/javascript">var arr = new Array(3);arr[0] = "Jani";arr[1] = "Hege";arr[2] = "Stale";

document.write(arr.toString());</script>The output of the code above will be:• Jani,Hege,Stale

JavaScript Cookies• A cookie is a variable that is stored on the visitor's computer. Each

time the same computer requests a page with a browser, it will send the cookie too. With JavaScript, you can both create and retrieve cookie values.

Examples of cookies:• Name cookie - The first time a visitor arrives to your web page, he

or she must fill in her/his name. The name is then stored in a cookie. Next time the visitor arrives at your page, he or she could get a welcome message like "Welcome John Doe!" The name is retrieved from the stored cookie

• Password cookie - The first time a visitor arrives to your web page, he or she must fill in a password. The password is then stored in a cookie. Next time the visitor arrives at your page, the password is retrieved from the cookie

• Date cookie - The first time a visitor arrives to your web page, the current date is stored in a cookie. Next time the visitor arrives at your page, he or she could get a message like "Your last visit was on Tuesday August 11, 2005!" The date is retrieved from the stored cookie

JavaScript CookiesJavaScript Cookies

• A cookie is often used to identify a user.• Create and Store a Cookie

function setCookie(c_name,value,expiredays){var exdate=new Date();exdate.setDate(exdate.getDate()+expiredays);document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toUTCString());}

  Using Cookies

• Cookie– Data stored on user’s computer to maintain

information about client during and between browser sessions

– Can be accessed through cookie property– Set expiration date through expires property– Use escape function to convert non-

alphanumeric characters to hexadecimal escape sequences

– unescape function converts hexadecimal escape sequences back to English characters

cookie.html1 of 4

1 <?xml version = "1.0"?>

2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"

3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

4

5 <!-- Fig. 12.15: cookie.html -->

6 <!-- Using Cookies -->

7

8 <html xmlns = "http://www.w3.org/1999/xhtml">

9 <head>

10 <title>Using Cookies</title>

11

12 <script type = "text/javascript">

13 <!--

14 var now = new Date(); // current date and time

15 var hour = now.getHours(); // current hour (0-23)

16 var name;

17

18 if ( hour < 12 ) // determine whether it is morning

19 document.write( "<h1>Good Morning, " );

20 else

21 {

22 hour = hour - 12; // convert from 24 hour clock to PM time

23

cookie.html2 of 4

24 // determine whether it is afternoon or evening

25 if ( hour < 6 )

26 document.write( "<h1>Good Afternoon, " );

27 else

28 document.write( "<h1>Good Evening, " );

29 }

30

31 // determine whether there is a cookie

32 if ( document.cookie )

33 {

34 // convert escape characters in the cookie string to

their

35 // english notation

36 var myCookie = unescape( document.cookie );

37

38 // split the cookie into tokens using = as delimiter

39 var cookieTokens = myCookie.split( "=" );

40

41 // set name to the part of the cookie that follows the

= sign

42 name = cookieTokens[ 1 ];

43 }

44 else

45 {

46 // if there was no cookie then ask the user to input a

name

47 name = window.prompt( "Please enter your name",

"GalAnt" );

48

cookie.html3 of 4

49 // escape special characters in the name string

50 // and add name to the cookie

51 document.cookie = "name=" + escape( name );

52 }

53

54 document.writeln(

55 name + ", welcome to JavaScript programming! </h1>" );

56 document.writeln( "<a href= \" JavaScript:wrongPerson() \" > "

+

57 "Click here if you are not " + name + "</a>" );

58

59 // reset the document's cookie if wrong person

60 function wrongPerson()

61 {

62 // reset the cookie

63 document.cookie= "name=null;" +

64 " expires=Thu, 01-Jan-95 00:00:01 GMT";

65

66 // after removing the cookie reload the page to get a new

name

67 location.reload();

68 }

69

70 // -->

71 </script>

72 </head>

73

cookie.html4 of 4

74 <body>

75 <p>Click Refresh (or Reload) to run the script again</p>

76 </body>

77 </html>

Event ModelingEvent Description Clipboard events

onbeforecut Fires before a selection is cut to the clipboard. onbeforecopy Fires before a selection is copied to the clipboard. onbeforepaste Fires before a selection is pasted from the clipboard. oncopy Fires when a selection is copied to the clipboard. oncut Fires when a selection is cut to the clipboard. onabort Fires if image transfer has been interrupted by user. onpaste Fires when a selection is pasted from the clipboard. Data binding events onafterupdate Fires immediately after a databound object has been updated. onbeforeupdate Fires before a data source is updated. oncellchange Fires when a data source has changed. ondataavailable Fires when new data from a data source become available. ondatasetchanged Fires when content at a data source has changed. ondatasetcomplete Fires when transfer of data from the data source has

completed. onerrorupdate Fires if an error occurs while updating a data field. onrowenter Fires when a new row of data from the data source is

available. onrowexit Fires when a row of data from the data source has just

finished. onrowsdelete Fires when a row of data from the data source is deleted. onrowsinserted Fires when a row of data from the data source is inserted. Fig. 14.10 Dynamic HTML events.

Event Description Keyboard events

onhelp Fires when the user initiates help (i.e., by pressing the F1 key). onkeydown Fires when the user pushes down a key. onkeypress Fires when the user presses a key. onkeyup Fires when the user ends a key press. Marquee events onbounce Fires when a scrolling marquee bounces back in the other

direction. onfinish Fires when a marquee finishes its scrolling. onstart Fires when a marquee begins a new loop. Mouse events oncontextmenu Fires when the context menu is shown (right-click). ondblclick Fires when the mouse is double clicked. ondrag Fires during a mouse drag. ondragend Fires when a mouse drag ends. ondragenter Fires when something is dragged onto an area. ondragleave Fires when something is dragged out of an area. ondragover Fires when a drag is held over an area. ondragstart Fires when a mouse drag begins.

ondrop Fires when a mouse button is released over a valid target during a drag.

onmousedown Fires when a mouse button is pressed down. Fig. 14.10 Dynamic HTML events.

Event Description onmouseup Fires when a mouse button is released. Miscellaneous events onafterprint Fires immediately after the document prints. onbeforeeditfocus Fires before an element gains focus for editing. onbeforeprint Fires before a document is printed. onbeforeunload Fires before a document is unloaded (i.e., the window was closed or a link was

clicked). onchange Fires when a new choice is made in a select element, or when a text input is

changed and the element loses focus. onfilterchange Fires when a filter changes properties or finishes a transition (see Chapter 15,

Dynamic HTML: Filters and Transitions). onlosecapture Fires when the releaseCapture method is invoked. onpropertychange Fires when the property of an object is changed. onreadystatechange Fires when the readyState property of an element

changes. onreset Fires when a form resets (i.e., the user clicks a reset button). onresize Fires when the size of an object changes (i.e., the user resizes a window or frame). onscroll Fires when a window or frame is scrolled. onselect Fires when a text selection begins (applies to input or

textarea). onselectstart Fires when the object is selected. onstop Fires when the user stops loading the object. onunload Fires when a page is about to unload.

Fig. 14.10 Dynamic HTML events.

Frequently used Eventsonabort Loading of an image is interrupted

onblur An element loses focus

onchange The user changes the content of a field

onclick Mouse clicks an object

ondblclick Mouse double-clicks an object

onerror An error occurs when loading a document or an image

onfocus An element gets focus

onkeydown A keyboard key is pressed

onkeypress A keyboard key is pressed or held down

onkeyup A keyboard key is released

onload A page or an image is finished loading

onmousedown A mouse button is pressed

onmousemove The mouse is moved

onmouseout The mouse is moved off an element

onmouseover The mouse is moved over an element

onmouseup A mouse button is released

onreset The reset button is clicked

onresize A window or frame is resized

onselect Text is selected

onsubmit The submit button is clicked

onunload The user exits the page

HTML Forms and JavaScriptHTML Forms and JavaScript

• JavaScript is very good at processing user input in the web browser

• HTML <form> elements receive input

• Forms and form elements have unique names– Each unique element can be identified– Uses JavaScript Document Object Model

(DOM)

Naming Form Elements in Naming Form Elements in HTML HTML

<form name="addressform">Name: <input name="yourname"><br />Phone: <input name="phone"><br />Email: <input name="email"><br /></form>

Forms and JavaScriptForms and JavaScriptdocument.formname.elementname.value

Thus:

document.addressform.yourname.value

document.addressform.phone.value

document.addressform.email.value

Using Form DataUsing Form DataPersonalising an alert box

<form name="alertform">

Enter your name:

<input type="text" name="yourname">

<input type="button" value= "Go" onClick="window.alert('Hello ' + document.alertform.yourname.value);">

</form>

JavaScript Form ValidationJavaScript Form Validation

• JavaScript can be used to validate data in HTML forms before sending off the content to a server.

• Required Field Validationfunction validate_required(field,alerttxt)

{with (field)  {  if (value==null||value=="")    {    alert(alerttxt);return false;    }  else    {    return true;    }  }}

• E-mail Validationfunction validate_email(field,alerttxt){with (field)  {  apos=value.indexOf("@");  dotpos=value.lastIndexOf(".");  if (apos<1||dotpos-apos<2)    {alert(alerttxt);return false;}  else {return true;}  }}

JavaScript AnimationJavaScript Animation

• It is possible to use JavaScript to create animated images.

• The HTML code looks like this:<a href="http://www.annauniv.edu" target="_blank"><img border="0" alt="Visit AnnaUniv!" src="b_pink.gif" id="b1"onmouseOver="mouseOver()" onmouseOut="mouseOut()" /></a>

• The changing between the images is done with the following JavaScript:

<script type="text/javascript">function mouseOver(){document.getElementById("b1").src ="b_blue.gif";}function mouseOut(){document.getElementById("b1").src ="b_pink.gif";}</script>

JavaScript Timing EventsJavaScript Timing Events

• JavaScript can be executed in time-intervals.

• This is called timing events.

• The two key methods that are used are:• setTimeout() - executes a code some time in

the future• clearTimeout() - cancels the setTimeout()

• The setTimeout() Method• Syntax

– var t=setTimeout("javascript statement",milliseconds);

• The clearTimeout() Method• Syntax

– clearTimeout(setTimeout_variable)

 document Object

Method or Property Description write( string ) Writes the string to the XHTML document as

XHTML code. writeln( string ) Writes the string to the XHTML document as

XHTML code and adds a newline character at the end.

document.cookie This property is a string containing the values of all the cookies stored on the user’s computer for the current document. See Section 12.9, Using Cookies.

document.lastModified This property is the date and time that this document was last modified.

Fig. 12.12 Important document object methods and properties.

window Object

• Provides methods for manipulating browser window

window.html1 of 7

1 <?xml version = "1.0" encoding = "utf-8"?>

2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"

3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

4

5 <!-- Fig. 12.13: window.html -->

6 <!-- Using the Window Object -->

7

8 <html xmlns = "http://www.w3.org/1999/xhtml">

9 <head>

10 <title>Using the Window Object</title>

11

12 <script type = "text/javascript">

13 <!--

14 var childWindow; // variable to control the child window

15

16 function createChildWindow()

17 {

18 // these variables all contain either "yes" or "no"

19 // to enable or disable a feature in the child window

20 var toolBar // specify if toolbar will appear in child window

21 var menuBar; // specify if menubar will appear in child window

22 var location; // specify if address bar will appear in child window

23 var scrollBars; // specify if scrollbars will appear in child window

24 var status; // specify if status bar will appear in child window

25 var resizable; // specify if the child window will be resizable

window.html2 of 7

26

27 // determine whether the Tool Bar checkbox is checked

28 if ( toolBarCheckBox.checked )

29 toolBar = "yes";

30 else

31 toolBar = "no";

32

33 // determine whether the Menu Bar checkbox is checked

34 if ( menuBarCheckBox.checked )

35 menuBar = "yes";

36 else

37 menuBar = "no";

38

39 // determine whether the Address Bar checkbox is checked

40 if ( locationCheckBox.checked )

41 location = "yes";

42 else

43 location = "no";

44

45 // determine whether the Scroll Bar checkbox is checked

46 if ( scrollBarsCheckBox.checked )

47 scrollBars = "yes";

48 else

49 scrollBars = "no";

50

window.html3 of 7

51 // determine whether the Status Bar checkbox is checked

52 if ( statusCheckBox.checked )

53 status = "yes";

54 else

55 status = "no";

56

57 // determine whether the Resizable checkbox is checked

58 if ( resizableCheckBox.checked )

59 resizable = "yes";

60 else

61 resizable = "no";

62

63 // display window with selected features

64 childWindow = window.open( "", "", "resizable = " + resizable +

65 ", toolbar = " + toolBar + ", menubar = " + menuBar +

66 ", status = " + status + ", location = " + location +

67 ", scrollbars = " + scrollBars );

68

69 // disable buttons

70 closeButton.disabled = false;

71 modifyButton.disabled = false;

72 getURLButton.disabled = false;

73 setURLButton.disabled = false;

74 } // end function createChildWindow

75

window.html4 of 7

76 // insert text from the textbox into the child window

77 function modifyChildWindow()

78 {

79 if ( childWindow.closed )

80 alert( "You attempted to interact with a closed window" );

81 else

82 childWindow.document.write( textForChild.value );

83 } // end function modifyChildWindow

84

85 // close the child window

86 function closeChildWindow()

87 {

88 if ( childWindow.closed )

89 alert( "You attempted to interact with a closed window" );

90 else

91 childWindow.close();

92

93 closeButton.disabled = true;

94 modifyButton.disabled = true;

95 getURLButton.disabled = true;

96 setURLButton.disabled = true;

97 } // end function closeChildWindow

98

window.html5 of 7

99 // copy the URL of the child window into the parent window’s myChildURL

100 function getChildWindowURL()

101 {

102 if ( childWindow.closed )

103 alert( "You attempted to interact with a closed window" );

104 else

105 myChildURL.value = childWindow.location;

106 } // end function getChildWindowURL

107

108 // set the URL of the child window to the URL

109 // in the parent window’s myChildURL

110 function setChildWindowURL()

111 {

112 if ( childWindow.closed )

113 alert( "You attempted to interact with a closed window" );

114 else

115 childWindow.location = myChildURL.value;

116 } // end function setChildWindowURL

117 //-->

118 </script>

119

120 </head>

121

122 <body>

123 <h1>Hello, This is the main window</h1>

window.html6 of 7

124 <p>Please check the features to enable for the child window<br/>

125 <input id = "toolBarCheckBox" type = "checkbox" value = ""

126 checked = "checked" />

127 <label>Tool Bar</label>

128 <input id = "menuBarCheckBox" type = "checkbox" value = ""

129 checked = "checked" />

130 <label>Menu Bar</label>

131 <input id = "locationCheckBox" type = "checkbox" value = ""

132 checked = "checked" />

133 <label>Address Bar</label><br/>

134 <input id = "scrollBarsCheckBox" type = "checkbox" value = ""

135 checked = "checked" />

136 <label>Scroll Bars</label>

137 <input id = "statusCheckBox" type = "checkbox" value = ""

138 checked = "checked" />

139 <label>Status Bar</label>

140 <input id = "resizableCheckBox" type = "checkbox" value = ""

141 checked = "checked" />

142 <label>Resizable</label><br/></p>

143

144 <p>Please enter the text that you would like to display

145 in the child window<br/>

146 <input id = "textForChild" type = "text"

147 value = "<h1> Hello, I am a child window</h1> <br\>"/>

window.html7 of 7

148 <input id = "createButton" type = "button"

149 value = "Create Child Window" onclick = "createChildWindow()" />

150 <input id= "modifyButton" type = "button" value = "Modify Child Window"

151 onclick = "modifyChildWindow()" disabled = "disabled"/>

152 <input id = "closeButton" type = "button" value = "Close Child Window"

153 onclick = "closeChildWindow()" disabled = "disabled"/></p>

154

155 <p>The other window's URL is: <br/>

156 <input id = "myChildURL" type = "text" value = "./"/>

157 <input id = "setURLButton" type = "button" value = "Set Child URL"

158 onclick = "setChildWindowURL()" disabled = "disabled"/>

159 <input id = "getURLButton" type = "button" value = "Get URL From Child"

160 onclick = "getChildWindowURL()" disabled = "disabled"/></p>

161

162 </body>

163 </html>

window ObjectMethod or Property Description open( url, name, options ) Creates a new window with the URL of the window set to

url, the name set to name, and the visible features set by the string passed in as option.

prompt( prompt, default ) Displays a dialog box asking the user for input. The text of the dialog is prompt, and the default value is set to default.

close() Closes the current window and deletes its object from memory.

window.focus() This method gives focus to the window (i.e., puts the window in the foreground, on top of any other open browser windows).

window.document This property contains the document object representing the document currently inside the window.

window.closed This property contains a boolean value that is set to true if the window is closed, and false if it is not.

window.opener This property contains the window object of the window that opened the current window, if such a window exists.

Fig. 12.14 Important window object methods and properties.

  Final JavaScript Example

• Combines concepts discussed previously

final.html1 of 6

1 <?xml version = "1.0"?>

2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"

3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

4

5 <!-- Fig. 12.16: final.html -->

6 <!-- Putting It All Together -->

7

8 <html xmlns = "http://www.w3.org/1999/xhtml">

9 <head>

10 <title>Putting It All Together</title>

11

12 <script type = "text/javascript">

13 <!--

14 var now = new Date(); // current date and time

15 var hour = now.getHours(); // current hour

16

17 // array with names of the images that will be randomly selected

18 var pictures =

19 [ "CPE", "EPT", "GPP", "GUI", "PERF", "PORT", "SEO" ];

20

21 // array with the quotes that will be randomly selected

22 var quotes = [ "Form ever follows function.<br/>" +

23 " Louis Henri Sullivan", "E pluribus unum." +

24 " (One composed of many.) <br/> Virgil", "Is it a" +

25 " world to hide virtues in?<br/> William Shakespeare" ];

final.html2 of 6

26

27 // write the current date and time to the web page

28 document.write( "<p>" + now.toLocaleString() + "<br/></p>" );

29

30 // determine whether it is morning

31 if ( hour < 12 )

32 document.write( "<h2>Good Morning, " );

33 else

34 {

35 hour = hour - 12; // convert from 24 hour clock to PM time

36

37 // determine whether it is afternoon or evening

38 if ( hour < 6 )

39 document.write( "<h2>Good Afternoon, " );

40 else

41 document.write( "<h2>Good Evening, " );

42 }

43

44 // determine whether there is a cookie

45 if ( document.cookie )

46 {

47 // convert escape characters in the cookie string to their

48 // english notation

49 var myCookie = unescape( document.cookie );

50

final.html3 of 6

51 // split the cookie into tokens using = as delimiter

52 var cookieTokens = myCookie.split( "=" );

53

54 // set name to the part of the cookie that follows the = sign

55 name = cookieTokens[ 1 ];

56 }

57 else

58 {

59 // if there was no cookie then ask the user to input a name

60 name = window.prompt( "Please enter your name", "GalAnt" );

61

62 // escape special characters in the name string

63 // and add name to the cookie

64 document.cookie = "name =" + escape( name );

65 }

66

67 // write the greeting to the page

68 document.writeln(

69 name + ", welcome to JavaScript programming!</h2>" );

70

71 // write the link for deleting the cookie to the page

72 document.writeln( "<a href = \" JavaScript:wrongPerson() \" > " +

73 "Click here if you are not " + name + "</a><br/>" );

74

final.html4 of 6

75 // write the random image to the page

76 document.write ( "<img src = \"" +

77 pictures[ Math.floor( Math.random() * 7 ) ] +

78 ".gif\" width= \" 105 \" height= \" 100 \" /> <br/>" );

79

80 // write the random quote to the page

81 document.write ( quotes[ Math.floor( Math.random() * 3 ) ] );

82

83 // create a window with all the quotes in it

84 function allQuotes()

85 {

86 // create the child window for the quotes

87 quoteWindow = window.open( "", "", "resizable=yes, toolbar" +

88 "=no, menubar=no, status=no, location=no," +

89 " scrollBars=yes" );

90 quoteWindow.document.write( "<p>" )

91

92 // loop through all quotes and write them in the new window

93 for ( var i = 0; i < quotes.length; i++ )

94 quoteWindow.document.write( ( i + 1 ) + ".) " +

95 quotes[ i ] + "<br/><br/>");

96

final.html5 of 6

97 // write a close link to the new window

98 quoteWindow.document.write( "</p><br/><a href = \" " +

99 "JavaScript:window.close()\">" +

100 " Close this window </a>" )

101 }

102

103 // reset the document's cookie if wrong person

104 function wrongPerson()

105 {

106 // reset the cookie

107 document.cookie= "name=null;" +

108 " expires=Thu, 01-Jan-95 00:00:01 GMT";

109

110 // after removing the cookie reload the page to get a new name

111 location.reload();

112 }

113

114 // open a new window with the quiz2.html file in it

115 function openQuiz()

116 {

117 window.open( "quiz2.html", "", "resizable = yes, " +

118 "toolbar = no, menubar = no, status = no, " +

119 "location = no, scrollBars = no");

120 }

121 // -->

final.html6 of 6

122 </script>

123

124 </head>

125

126 <body>

127 <p><a href = "JavaScript:allQuotes()">View all quotes</a></p>

128

129 <p id = "quizSpot">

130 <a href = "JavaScript:openQuiz()">Please take our quiz</a></p>

131

132 <script type = "text/javascript">

133 // variable that gets the last midification date and time

134 var modDate = new Date( document.lastModified );

135

136 // write the last modified date and time to the page

137 document.write ( "This page was last modified " +

138 modDate.toLocaleString() );

139 </script>

140

141 </body>

142 </html>

quiz2.html1 of 3

1 <?xml version = "1.0" encoding = "utf-8"?>

2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"

3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

4

5 <!-- Fig. 12.14: quiz2.html -->

6 <!-- Online Quiz -->

7

8 <html xmlns = "http://www.w3.org/1999/xhtml">

9 <head>

10 <title>Online Quiz</title>

11

12 <script type = "text/JavaScript">

13 <!--

14 function checkAnswers()

15 {

16 // determine whether the answer is correct

17 if ( myQuiz.radiobutton[ 1 ].checked )

18 window.opener.quizSpot.innerText =

19 "Congratulations, your answer is correct";

20 else // if the answer is incorrect

21 window.opener.quizSpot.innerHTML = "Your answer is incorrect." +

22 " Please try again <br /> <a href= \" JavaScript:openQuiz()" +

23 " \" > Please take our quiz</a>";

24

25 window.opener.focus();

quiz2.html2 of 3

26 window.close();

27 } // end checkAnswers function

28 //-->

29 </script>

30

31 </head>

32

33 <body>

34 <form id = "myQuiz" action = "JavaScript:checkAnswers()">

35 <p>Select the name of the tip that goes with the image shown:<br />

36 <img src = "EPT.gif" width = "108" height = "100"

37 alt = "mystery tip"/>

38 <br />

39

40 <input type = "radio" name = "radiobutton" value = "CPE" />

41 <label>Common Programming Error</label>

42

43 <input type = "radio" name = "radiobutton" value = "EPT" />

44 <label>Error-Prevention Tip</label>

45

46 <input type = "radio" name = "radiobutton" value = "PERF" />

47 <label>Performance Tip</label>

48

49 <input type = "radio" name = "radiobutton" value = "PORT" />

50 <label>Portability Tip</label><br />

quiz2.html3 of 3

51

52 <input type = "submit" name = "Submit" value = "Submit" />

53 <input type = "reset" name = "reset" value = "Reset" />

54 </p>

55 </form>

56 </body>

57 </html>

THANK YOUTHANK YOU

top related