95
JavaScript Chapter 4

JavaScript Chapter 4. Topic to be covered.. What is JavaScript? What is JavaScript? Simple Program: Displaying a Line of Text in a Web Page Simple Program:

Embed Size (px)

Citation preview

JavaScript

Chapter 4

Topic to be covered..• What is JavaScript? What is JavaScript?

• Simple Program: Displaying a Line of Text in a Simple Program: Displaying a Line of Text in a Web Page Web Page

• VariablesVariables• Screen Output & Keyboard InputScreen Output & Keyboard Input• Data typesData types• Assignment Assignment • ExpressionExpression• OperatorsOperators• Conditional StatementConditional Statement

What is JavaScript?What is JavaScript?

Originally developed by Netscape, as LiveScript

Became a joint venture of Netscape and Sun in 1995, renamed JavaScript

Now standardized by the European Computer Manufacturers Association as ECMA-262 (also ISO 16262).

JavaScript Scripting language that facilitates a disciplined approach

to designing computer programs that enhance the functionality and appearance of web pages.

3

JavaScript

(3)Client runs JavaScript

(client-side scripting)

(1)HTTP Request

HTTP Response

(2)HTML file with

embedded JavaScript

JavaScript is seldom used to write complete “programs” Instead, small bits of JavaScript are used to add

functionality to HTML pages JavaScript is often used in conjunction with HTML

“forms” JavaScript is reasonably platform-independent

Common Uses of JavaScriptCommon Uses of JavaScript Display a message box Select list navigation Edit and validate form information Create a new window with a specified size

and screen position Image Rollovers Status Messages Display Current Date Calculations

6

7

Simple Program: Displaying a Line of Text in a Web PageSpacing displayed by a browser in a web page is

determined by the XHTML elements used to format the page

Often, JavaScripts appear in the <head> section of the XHTML document

The browser interprets the contents of the <head> section first

The <script> tag indicates to the browser that the text that follows is part of a script. Attribute type specifies the scripting language used in the script—such as text/javascript

Simple Program: Displaying a Line of Text in a Web Page (cont)

- Either directly, as in

<script type = "text/javaScript"> -- JavaScript script – </script>or

<script language="JavaScript">-- JavaScript script – </script>

- Or indirectly, as a file specified in the src attribute of <script>, as in

<script type = "text/javaScript" src = "myScript.js"> </script>

9

Portability Tip

Some browsers do not support the <script> </script> tags. If your document is to be rendered with such browsers, enclose the script code between these tags in an XHTML comment, so that the script text does not get displayed as part of the web page. The closing comment tag of the XHTML comment (-->) is preceded by a JavaScript comment (//) to prevent the browser from trying to interpret the XHTML comment as a JavaScript statement.

10Simple Program: Displaying a Line of Text in a Web Page (Cont.)A string of characters can be contained

between double (") or single (') quotation marks

A string is sometimes called a character string, a message or a string literal

Comments are as in C or Java: Between // and the end of the line Between /* and */

11Simple Program: Displaying a Line of Text in a Web Page (Cont.)The parentheses following the name of a

method contain the arguments that the method requires to perform its task (or its action)

Every statement should end with a semicolon (also known as the statement terminator), although none is required by JavaScript

JavaScript is case sensitive Not using the proper uppercase and lowercase

letters is a syntax error

12Simple Program: Displaying a Line of Text in a Web Page (Cont.)Browser’s document object represents the XHTML

document currently being displayed in the browser

Allows a script programmer to specify XHTML text to be displayed in the XHTML document

Browser contains a complete set of objects that allow script programmers to access and manipulate every element of an XHTML document

Object Resides in the computer’s memory and contains information

used by the script The term object normally implies that attributes (data) and

behaviors (methods) are associated with the object An object’s methods use the attributes’ data to perform useful

actions for the client of the object—the script that calls the methods

13Simple Program: Displaying a Line of Text in a Web Page (Cont.)The document object’s writeln method

Writes a line of XHTML text in the XHTML document

Text displayed is dependent on the contents of the string written, which is subsequently rendered by the browser.

Browser will interpret the XHTML elements as it normally does to render the final text in the document

14

Displaying a line

of text.

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

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. 6.2: welcome.html -->

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

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

8 <head>

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

10 <script type = "text/javascript">

11 <!--

12 document.writeln(

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

14 // -->

15 </script>

16 </head><body></body>

17 </html>

Script begins

Specifies that we are using the JavaScript language

Writes an h1 welcome message in the XHTML document

Prevents older browsers that do not support scripting from displaying the text of the script

XHTML comment delimiter, commented for correct interpretation by all browsers

Script ends

15

Modifying Our First ProgramMethod write displays a string like writeln, but does not position the output cursor in the XHTML document at the beginning of the next line after writing its argument

16

Modifying Our First Program (Cont.)You cannot split a statement in the middle

of a string. The + operator (called the “concatenation operator” when used in this manner) joins two strings together

17

Printing one line with separate statements.

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

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. 6.3: welcome2.html -->

6 <!-- Printing one line with multiple statements. -->

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

8 <head>

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

10 <script type = "text/javascript">

11 <!--

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

13 document.write( "Welcome to JavaScript " +

14 "Programming!</h1>" );

15 // -->

16 </script>

17 </head><body></body>

18 </html>

Two write statements create one line of XHTML text

Concatenation operator joins the string together, as it is split into multiple lines

18

Modifying Our First Program (Cont.)A single statement can cause the browser

to display multiple lines by using line-break XHTML tags ( <br/>) throughout the string of XHTML text in a write or writeln method call

19

Printing on multiple lines with a single statement.

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

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. 6.4: welcome3.html -->

6 <!-- Printing on multiple lines with a single statement. -->

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

8 <head>

9 <title>Printing Multiple Lines</title>

10 <script type = "text/javascript">

11 <!--

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

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

14 // -->

15 </script>

16 </head><body></body>

17 </html>

Inserts line-break

Inserts line-break

Checkpoint Checkpoint

1. Netscape's original name for JavaScript was ____________.

2. A standardized version of JavaScript is called____________.

3. The ____________ tag allows JavaScript to be inserted into an HTML/XHTML document.

4. JavaScript is mainly used for ____________ scripting.

5. _______________is used to denote a single-line comment and ____________ is used to denote a multi-line comment.

6. Every statement should end with a __________________.

21

Write a script that displays the numbers 1 to 4 on the same line, with each pair of adjacentnumbers separated by one space. Write the program using the following methods:

a) Using document.writeln statement.ANS: document.writeln( "1 2 3 4" );b) Using document.write statements.ANS: document.write( "1 " );document.write( "2 " );document.write( "3 " );document.write( "4" ); or document.write( “1 2 3 4" );

VariableVariable A variable is a placeholder for information. The variable is stored in the computer’s memory (RAM). Variables are declared with a var statement:

Variables names must begin with a letter or underscore Comprise of sequence of letters, numbers, _, Variable names are case-sensitive

Eg. NAME, name, a, A, cs_170 Variables are untyped (they can hold values of any type)

23

Variable declaration – declaring use

• State variables to be used

• var statement var a;

• Declaration precedes variable usage in programvar a; a = 5;document.write(a);

var userName = "Karen";document.write(userName);

Variable declaration – declaring use More than one

variable can be declared in a statement.

var a, b;

Is the same as…

var a;var b;

The order of variable declaration does not matter.

var a, b, c;

Is the same as…

var b, a, c;

Reserved words – can not be used as variable.

<html><head><title>Calling Variable</title></head><body><script Language="JavaScript">var address="22D Station St. Athens Ohio 45701

USA";document.write(address);</script></body></html>

Output…

<html><head><title>Using Semicolon</title><script Language="JavaScript">var x = "Welcome My Friends!";var y = "It's a good habit adding semicolon in

your script!";document.write(x + "<br/>" + y);</script></head></html>

Output

• The JavaScript model for the HTML document is the Document object.

• The Document object has a method, write and writeln which dynamically creates contente.g., document.write("Answer: " + result + "<br />");

Screen Output & Keyboard Input

Screen Output & Keyboard Input (cont) The model for the browser display window is the

Window object The Window object has three methods for creating

dialog boxes:1. Alert2. Confirm3. Prompt

Dialogs Useful to display information in windows that “pop up”

on the screen to grab the user’s attention Typically used to display important messages to the

user browsing the web page

Browser’s window object uses method alert to display an alert dialog

•Method alert requires as its argument the string to be displayed.•Opens a dialog box which displays the parameter string and an OK button•It waits for the user to press the OK button

window.alert(“The sum is: 42");

Alert Box

Confirm Box•Opens a dialog box and displays the parameter and two buttons, OK and Cancel

•Returns a Boolean value, depending on which button was pressed (it waits for one)

window.confirm("Do you want to continue this download?");

Prompt BoxThe window object’s prompt method displays a dialog into which the user can type a value.

•The first argument is a message (called a prompt) that directs the user to take a specific action. •The optional second argument is the default string to display in the text field.

window.prompt("What is your name?", "");

Checkpoint: Write a statement to accomplish each of the following tasks:

1. Prompt the user to enter the first value, read the value from the user and store it in the variable xVal.

ANS: xVal = window.prompt( "Enter first integer:", "0" );

2. Prompt the user to enter the second value, read the value from the user and store it in the variable yVal.

ANS: yVal = window.prompt( "Enter second integer:", "0" );

3. Prompt the user to enter the third value, read the value from the user and store it in the variable zVal.

ANS: zVal = window.prompt( "Enter third integer:", "0" );

4. Convert xVal to an integer, and store the result in the variable x.ANS: x = parseInt( xVal );

5. Convert yVal to an integer, and store the result in the variable y.ANS: y = parseInt( yVal );

6. Convert zVal to an integer, and store the result in the variable z.ANS: z = parseInt( zVal );

Primitive / data types• Strings • Numbers – numeric literals• Booleans – True and False• Undefined - undefined• Null - null

Strings• Sequence of characters

Eg. “CS_170”

• Use single quotes ‘ ’ or double “ ”Eg. var name; name = “katty”;

• Double quoted strings can contain single quotes and vice versa.

eg. ‘ “We can leave now”, she said.’Or “CS 170’s assignment”

Assignment statement<variable> <assignment symbol> <expression>

• Variable : declared variable• Assignment symbol : notation for assign. operation

(the equal to sign)• Expression : tell comp how to compute new value

• Eg.var Area; Area = pi * r * r;

Essential points about assign.

• All three components required• Value on RHS assigned to variable on LHS• Value of variable on right is the value of

variable at the start of the execution of assignment

Eg. final = 0;final = final + 5;

The value on LHS will be 5 while RHS will be 0.

Operators & Expressions

o Arithmetic / * + - %o Relational < > <= == != >=o Logical AND OR NOTo Unary, Binary operators.

Arithmetic operators

• Symbols of basic arithmetic

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 x ÷ y or x y x / y

Remainder % r mod s r % s

<Script Language="JavaScript">var two = 2;var ten = 10;var linebreak = "<br />“;

document.write("two plus ten = ");result = two + ten;document.write(result);document.write(linebreak);

document.write("ten * ten = ");result = ten * ten;document.write(result);document.write(linebreak);

document.write("ten / two = ");result = ten / two;document.write(result);</Script>

Output

Relational Operators• Make comparison between two values

• Returns Boolean value - either true or false

a < b Is a less than ba <= b Is a less than or equal to ba == b Is a equal to ba != b Is a not equal to ba >= b Is a greater than or equal to ba > b Is a greater than b

Eg. salary > 1000age >= 18

course == cs170

Logical Operators

• test two or more relationships together

• AND • OR• NOT

Logical AND operator • &&

• exp1 && exp 2 outcome is true if the outcome for both exp1 and

exp2 are true

course == cs170 and semester <8

in JavaScript

course == cs170 && semester <8

Logical OR operator• ||

• exp1 || exp 2 outcome is true if the outcome for either exp1 and

exp2 are true

level 3 || level 6

Logical NOT operator• !

• Unary operator• !(expression)

Outcome is the opposite of the value of operand

• !(marks <= 3 && marks >= 5)

True for 4

Unary/binary operators

• All of the below are binary operatorsa*b , a+b, a/b, a-b

a and b are known as operands

• Unary operators involve one operandEg. (-) -a, -4

- Similar to C, Java, and C++

-Compound statements are delimited by braces { }(Group a number of statements together and execute like a single statement)

1. Primitive values

- If it is a string, it is true unless it is empty or "0"

- If it is a number, it is true unless it is zero

2. Relational Expressions

- The usual six: ==, !=, <, >, <=, >=

3. Compound Expressions

- The usual operators: &&, ||, and !

Control Statements

Control Statements (continued)

if (condition){ … commands to execute if condition is true} else { … commands to execute if condition is false}

4. if..else

<Script Language="JavaScript">var age = prompt("Please enter your age : ","");

if (age < 18) { alert("Under 18, No Smoking!");}else {alert("Smoking is no good for your health!");}</Script>

Control Statements (continued)

5. Switch

switch (expression) { case value_1: // value_1 statements case value_2: // value_2 statements … [default: // default statements] }

- The statements can be either statement sequences or compound statements

6. Loop statements

while (control_expression) statement or compound

for (init; control; increment) statement or compound - init can have declarations, but the scope of such variables is the whole script

do statement or compound while (control_expression)

Control Statements (continued)

• An array is a special variable, which can hold more than one value, at a time.

•If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:

cars1=“Proton";cars2="Volvo";cars3="BMW";

•An array can hold all your variable values under a single name. And you can access the values by referring to the array name.

•Each element in the array has its own ID so that it can be easily accessed.

Arrays

An array can be defined in three ways.

The following code creates an Array object called myCars:

1. var myCars=new Array(); // regular array myCars[0]=“Proton";       // argument to control array's size)

myCars[1]="Volvo"; myCars[2]="BMW";

2. var myCars=new Array(“Proton","Volvo","BMW"); // condensed array

3. var myCars=[“Proton","Volvo","BMW"]; // literal array

Create an Array

Access an Array You can refer to a particular element in an array by referring to the name of

the array and the index number.

The index number starts at 0.

The following code line:document.write(myCars[0]);//will result in the following output:Proton

Modify Values in an Array

To modify a value in an existing array, just add a new value to the array with a specified index number:

myCars[0]="Opel"; document.write(myCars[0]); //will result in the following output:Opel

FunctionFunction A function is a block of one or more JavaScript

statements with a specific purpose, which can be run when needed.

function function_name() { ... JavaScript statements …}

59

Using FunctionsUsing Functions

function showAlert()

{

alert("Please click OK to continue.");

}

60

//Calling the Function

showAlert();

//Defining the Function

61

JavaScript: Objects

Document Object Model Document Object Model (DOM)(DOM)

A portion of the DOM is shown at the left.

Defines every object and element on a web page

Hierarchical structure

Accesses page elements and apply styles to page elements

62

ObjectObject

An object is a thing or entity. Browser window Submit button Web page document

63

PropertyProperty A property is a characteristic or attribute of an

object.

The background color of a web page documentdocument.bgcolor

The date the web page file was last modifieddocument.lastmodified

The src file of an image objectimage1.src

64

MethodMethod

A method is an action (a verb)

Writing text to a web page document document.write()

Submitting a formform1.submit()

65

66

Introduction to Object TechnologyJavaScript uses objects to perform many

tasks It is referred to as an object-based

programming languageObjects have attributes and exhibit

behaviors

67

Introduction to Object Technology (Cont.)Objects have the property of information hiding

Objects may know how to communicate with one another across well-defined interfaces, but normally they are not allowed to know how other objects are implemented

Web browsers Contain a set of objects that encapsulate an XHTML

document’s elements The objects expose to a JavaScript programmer the attributes

and behaviors that enable a JavaScript program to interact with (or script) those elements (objects)

68

Introduction to Object Technology (Cont.)An object’s methods are called by writing

the name of the object followed by a dot operator (.) and the name of the method

In parentheses following the method name is the argument (or a comma-separated list of arguments) to the method

69

Math object methods.

Method Description Examples

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

min( 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

70

Properties of the Math object.

Constant 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

71

Some String object methods (Part 1 of 2).

Method Description

charAt( index ) Returns a string containing the character at the specified index. If there is no character at the index, charAt returns an empty string. The first character is located at index 0.

charCodeAt( index ) Returns the Unicode value of the character at the specified index, or NaN (not a number) if there is no character at that index.

concat( string ) Concatenates its argument to the end of the string that invokes the method. The string invoking this method is not modified; instead a new String is returned. This method is the same as adding two strings with the string-concatenation operator + (e.g., s1.concat(s2) is the same as s1 + s2).

fromCharCode( value1, value2, )

Converts a list of Unicode values into a string containing the corresponding characters.

indexOf( substring, index )

Searches for the first occurrence of substring starting from position index in the string that invokes the method. The method returns the starting index of substring in the source string or –1 if substring is not found. If the index argument is not provided, the method begins searching from index 0 in the source string.

lastIndexOf( substring, index )

Searches for the last occurrence of substring starting from position index and searching toward the beginning of the string that invokes the method. The method returns the starting index of substring in the source string or –1 if substring is not found. If the index argument is not provided, the method begins searching from the end of the source string.

replace( searchString, replaceString )

Searches for the substring searchString, and replaces the first occurrence with replaceString and returns the modified string, or the original string if no replacement was made.

72

Some String object methods (Part 2 of 2).

slice( start, end ) Returns a string containing the portion of the string from index start through index end. If the end index is not specified, the method returns a string from the start index to the end of the source string. A negative end index specifies an offset from the end of the string, starting from a position one past the end of the last character (so –1 indicates the last character position in the string).

split( string ) Splits the source string into an array of strings (tokens), where its string argument specifies the delimiter (i.e., the characters that indicate the end of each token in the source string).

substr( start, length )

Returns a string containing length characters starting from index start in the source string. If length is not specified, a string containing characters from start to the end of the source string is returned.

substring( start, end )

Returns a string containing the characters from index start up to but not including index end in the source string.

toLowerCase() Returns a string in which all uppercase letters are converted to lowercase letters. Nonletter characters are not changed.

toUpperCase() Returns a string in which all lowercase letters are converted to uppercase letters. Nonletter characters are not changed.

Methods that generate XHTML tags

anchor( name ) Wraps the source string in an anchor element (<a></a>) with name as the anchor name.

fixed() Wraps the source string in a <tt></tt> element (same as <pre></pre>).

link( url ) Wraps the source string in an anchor element (<a></a>) with url as the hyperlink location.

strike() Wraps the source string in a <strike></strike> element.

sub() Wraps the source string in a <sub></sub> element.

sup() Wraps the source string in a <sup></sup> element.

73

Date object methods (Part 1 of 2).

Method Description

getDate() getUTCDate()

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

getDay() getUTCDay()

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

getFullYear() getUTCFullYear()

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

getHours() getUTCHours()

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

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.

getMonth() getUTCMonth()

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

getSeconds() getUTCSeconds()

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

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 (Coordinated Universal Time).

setDate( val ) setUTCDate( val )

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

74

Date object methods (Part 2 of 2).

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

Sets the year in local time or UTC. 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. 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.

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

Sets the minute in local time or UTC. 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. 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. The second argument, representing the milliseconds, is optional. If this argument is not specified, the current millisecond value in the Date object is used.

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, 2007, at 3:42:22 PM is represented as 09/13/07 15:47:22 in the United States and 13/09/07 15:47:22 in Europe.

toUTCString() Returns a string representation of the date and time in the form: 15 Sep 2007 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 17 15:47:22 EDT 2007 in the United States).

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

75

Boolean object methods.

Method 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.

76

Number object methods and properties.

Method 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 5.00E–324.

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.

77

Important document object methods and properties. Method or property Description

getElementById( id ) Returns the DOM node representing the XHTML element whose id attribute matches id.

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.

cookie A string containing the values of all the cookies stored on the user’s computer for the current document. See Section 11.9, Using Cookies.

lastModified The date and time that this document was last modified.

78

Important window object methods and properties.

Method 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 to refer to it in the script, 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.

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

blur() This method takes focus away from the window (i.e., puts the window in the background).

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.

79

Events and Event Handling

JavaScript and JavaScript and EventsEvents

Events: actions taken by the Web page visitor

clicking (onclick), placing the mouse on an element

(onmouseover), removing the mouse from an element

(onmouseout), loading the page (onload), unloading the page (onunload), etc.

80

Events Events Event Event Handler

click onclick

load onload

mouseover onmouseover

mouseout onmouseout

submit onsubmit

unload onunload

81

JavaScript and JavaScript and EventsEvents

JavaScript can be configured to perform actions when events occur. The event name is coded as an attribute of an

XHTML tag The value of the event attribute contains the

JavaScript code

Example: Display an alert box when the mouse is placed over a hyperlink.

82

<a href="home.htm" onmouseover="alert('Click to go home')">Home</a>

83

Introduction

JavaScript events allow scripts to respond to user interactions

and modify the page accordinglyEvents and event handling

help make web applications more responsive, dynamic and interactive

The process of connecting an event handler to an event is called registration

84

Event Description

onabort Fires when image transfer has been interrupted by user.

onchange Fires when a new choice is made in a select element, or when a text input is changed and the element loses focus.

onclick Fires when the user clicks using the mouse.

ondblclick Fires when the mouse is double clicked.

onfocus Fires when a form element gains focus.

onkeydown Fires when the user pushes down a key.

onkeypress Fires when the user presses then releases a key.

onkeyup Fires when the user releases a key.

onload Fires when an element and all its children have loaded.

onsubmit Fires when a form is submitted.

onunload Fires when a page is about to unload.

Cross-browser events. (Part 1 of 2.)

85

Event Description

onmousedown Fires when a mouse button is pressed down. onmousemove Fires when the mouse moves.

onmouseout Fires when the mouse leaves an element.

onmouseover Fires when the mouse enters an element.

onmouseup Fires when a mouse button is released.

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).

onselect Fires when a text selection begins (applies to input or textarea).

onsubmit Fires when a form is submitted.

onunload Fires when a page is about to unload.

Cross-browser events. (Part 2 of 2.)

Dynamic HTML (DHTML) Use DHTML to create interesting and

complex visual effects. DHTML technology integrates JavaScript,

CSS and HTML to create striking effects that are not otherwise possible.

Examples of DHTML Positioning Elements Moving Elements Element Visibility Changing Colors and Fonts Dynamic Content Stacking Elements Locating the Mouse Cursor Reacting to a Mouse Click Slow Movement of Elements Dragging and Dropping an Element

Display of mover.html (before pressing the Move It button)

Display of mover.html (after pressing the Move It button)

Display of dynLink.html with the cursor not over the link

Display of dynLink.html with the mouse cursor over the link

JavaScript Debugging(1)JavaScript Debugging(1)

Check the syntax of the statements Pay very close attention to upper and lower case letters,

spaces, and quotations

Verify that you have saved the page with your most recent changes

Verify that you are testing the most recent version of the page (refresh or reload the page)

If you get an error message, use the error messages that are displayed by the browser In Firefox: Select Tools >Web Developer> Error Console

92

JavaScript JavaScript Debugging(2)Debugging(2)

Use the Firefox browser: Select Tools > Error Console from the Menu

The Error Console will indicate an issue and the line number This may not be exactly where the problem is Sometimes the error is a one or two lines above the

indicated line number.

93

JavaScript & JavaScript & AccessibilityAccessibility

Don’t expect JavaScript to always function for every visitor Some may have JavaScript disabled Some may be physically unable to click a mouse

Provide a way for your site to be used if JavaScript is not functioning Plain text links E-mail contact info

94

JavaScript ResourcesJavaScript Resources

JavaScript Tutorialshttp://www.w3schools.com/JS

JavaScript Tutorial for the Total Non-Programmer http://www.webteacher.com/javascript/

More Beginning JavaScript Tutorials http://echoecho.com/javascript.htm

Core JavaScript 1.5 Reference Manual http://www.webreference.com/javascript/reference/core_ref

Creating Accessible JavaScripthttp://www.webaim.org/techniques/javascript

95