database-driven web sites, second edition1 chapter 3 introduction to client-side scripts

51
Database-Driven Web Sites, Second Edition 1 Chapter 3 INTRODUCTION TO CLIENT- SIDE SCRIPTS

Upload: nathan-bruce

Post on 29-Dec-2015

218 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Database-Driven Web Sites, Second Edition1 Chapter 3 INTRODUCTION TO CLIENT-SIDE SCRIPTS

Database-Driven Web Sites, Second Edition

1

Chapter 3

INTRODUCTION TO CLIENT-SIDE SCRIPTS

Page 2: Database-Driven Web Sites, Second Edition1 Chapter 3 INTRODUCTION TO CLIENT-SIDE SCRIPTS

Database-Driven Web Sites, Second Edition

2

Objectives

In this chapter, you will:

• Learn how to reference objects in HTML documents using the HTML Document Object Model and dot syntax

• Learn how to create and debug client-side scripts that use JavaScript methods, event handlers, and custom functions

• Create and manipulate JavaScript variables

• Create and use JavaScript built-in objects

Page 3: Database-Driven Web Sites, Second Edition1 Chapter 3 INTRODUCTION TO CLIENT-SIDE SCRIPTS

Database-Driven Web Sites, Second Edition

3

Objectives

In this chapter, you will:

• Learn how to use JavaScript global functions to perform data type conversions

• Become familiar with JavaScript decision control and looping structures

• Understand the differences between JavaScript and Java

Page 4: Database-Driven Web Sites, Second Edition1 Chapter 3 INTRODUCTION TO CLIENT-SIDE SCRIPTS

Database-Driven Web Sites, Second Edition

4

Referencing HTML Document Objects

• To enhance Web pages, JavaScript program commands must be able to reference objects on a Web page

• JavaScript commands reference Web page objects using the HTML document object model (DOM)

Page 5: Database-Driven Web Sites, Second Edition1 Chapter 3 INTRODUCTION TO CLIENT-SIDE SCRIPTS

Database-Driven Web Sites, Second Edition

5

Object-Oriented Concepts

• Object: abstract representation of something in the real world, with specific properties and actions

• Object class: defines the properties and actions of similar objects

• Class instance: object that belongs to a class• Event: an action that occurs within an object as a

result of a user action• Event handler: block of program commands that

executes when an event occurs

Page 6: Database-Driven Web Sites, Second Edition1 Chapter 3 INTRODUCTION TO CLIENT-SIDE SCRIPTS

Database-Driven Web Sites, Second Edition

6

The HTML Document Object Model

• The HTML document object model (DOM):– Hierarchical naming system

– Enables a developer to reference and access HTML objects and their properties, methods, and events within JavaScript commands

• Current Netscape and Internet Explorer browsers support the basic DOM, first introduced in Netscape Navigator 2

Page 7: Database-Driven Web Sites, Second Edition1 Chapter 3 INTRODUCTION TO CLIENT-SIDE SCRIPTS

Database-Driven Web Sites, Second Edition

7

The HTML Document Object Model

• In the DOM currently used:– Window: top-level object class; represents a

browser window

– Child object classes within a window: history, document, and location

– A document object contains all of the elements, or child objects, on a Web page

– Primary child objects: link, form, and anchor

Page 8: Database-Driven Web Sites, Second Edition1 Chapter 3 INTRODUCTION TO CLIENT-SIDE SCRIPTS

Database-Driven Web Sites, Second Edition

8

The HTML Document Object Model

Page 9: Database-Driven Web Sites, Second Edition1 Chapter 3 INTRODUCTION TO CLIENT-SIDE SCRIPTS

Database-Driven Web Sites, Second Edition

9

Referencing HTML Objects Using Dot Syntax

• Dot syntax: references an object in an HTML document based on its hierarchical location among the DOM HTML objects

• This hierarchy is called the object path

Page 10: Database-Driven Web Sites, Second Edition1 Chapter 3 INTRODUCTION TO CLIENT-SIDE SCRIPTS

Database-Driven Web Sites, Second Edition

10

Dot Syntax Using Object Names

• An HTML link, form, or anchor object can be referenced using its object name in dot syntax as follows: window.document.object_name  

• To reference a child element within a document form, a dot is placed after the form’s object_name and then the name of the form element is specified

• Once you specify the object path, you can then reference an object’s properties and call its methods

Page 11: Database-Driven Web Sites, Second Edition1 Chapter 3 INTRODUCTION TO CLIENT-SIDE SCRIPTS

Database-Driven Web Sites, Second Edition

11

Dot Syntax Using Object IDs

• Object ID attribute: – alternate way to reference HTML objects in dot

syntax

– uniquely identifies an element within an HTML document

– can be used instead of the name attribute value when specifying the path to an object

• Any HTML tag can have an ID attribute value

Page 12: Database-Driven Web Sites, Second Edition1 Chapter 3 INTRODUCTION TO CLIENT-SIDE SCRIPTS

Database-Driven Web Sites, Second Edition

12

Using the Visual Studio .NET IDE to Create a Client-Side Script

• IntelliSense lists can be used to provide choices in JavaScript commands

• The IntelliSense information lists available child objects, methods, properties, and events that can be used to complete HTML, dot syntax, and program statements

• Items within the IntelliSense lists have visual icons to specify the item type

Page 13: Database-Driven Web Sites, Second Edition1 Chapter 3 INTRODUCTION TO CLIENT-SIDE SCRIPTS

Database-Driven Web Sites, Second Edition

13

Adding Script Tags to an HTML Document

• Client-side script can be created by enclosing JavaScript commands within the script tag

• JavaScript commands are usually enclosed in HTML comment tags

Page 14: Database-Driven Web Sites, Second Edition1 Chapter 3 INTRODUCTION TO CLIENT-SIDE SCRIPTS

Database-Driven Web Sites, Second Edition

14

Adding Script Tags to an HTML Document

• JavaScript commands:– Are case-sensitive– Can span multiple lines in a text editor and HTML

file– End of each command is designated with a

semicolon (;)– Comment statements can be included

• The line signaling the end of the script must be prefaced by typing the JavaScript comment indicator (/) followed by the closing HTML comment tag (->)

Page 15: Database-Driven Web Sites, Second Edition1 Chapter 3 INTRODUCTION TO CLIENT-SIDE SCRIPTS

Database-Driven Web Sites, Second Edition

15

Adding Script Tags to an HTML Document

• Script tags:– Can be placed almost anywhere in an HTML

document

– Should not be placed within document title tags or within a style tag because the script interpreter does not look for script tags in these locations

• Avoid nesting scripts within additional elements• A document can contain multiple sets of script tags,

however, you should enclose all script commands within a single script tag

Page 16: Database-Driven Web Sites, Second Edition1 Chapter 3 INTRODUCTION TO CLIENT-SIDE SCRIPTS

Database-Driven Web Sites, Second Edition

16

JavaScript Methods

• An object has associated methods that:– Perform specific actions on the object

– Use the object in a way that affects the document or script

• Syntax to call a method:

document.obj_name .method_name(para1,para2,…) • If the method has no associated parameters, use

empty parentheses after the method name

Page 17: Database-Driven Web Sites, Second Edition1 Chapter 3 INTRODUCTION TO CLIENT-SIDE SCRIPTS

Database-Driven Web Sites, Second Edition

17

JavaScript Methods

• The alert method opens a message box that displays a short message

• The text in an alert can reference and display properties of HTML form elements

Page 18: Database-Driven Web Sites, Second Edition1 Chapter 3 INTRODUCTION TO CLIENT-SIDE SCRIPTS

Database-Driven Web Sites, Second Edition

18

JavaScript Methods

• Document methods create dynamic Web pages using client-side scripts

• Examples:– document.clear method clears the contents of the

current document

– document.write method adds new HTML tags and elements dynamically

Page 19: Database-Driven Web Sites, Second Edition1 Chapter 3 INTRODUCTION TO CLIENT-SIDE SCRIPTS

Database-Driven Web Sites, Second Edition

19

JavaScript Functions

• Function: self-contained group of program commands that programmers call within a larger program

• Global functions: built-in functions that can be called from any JavaScript command

• Custom functions: programmers create custom functions to perform program-specific tasks

Page 20: Database-Driven Web Sites, Second Edition1 Chapter 3 INTRODUCTION TO CLIENT-SIDE SCRIPTS

Database-Driven Web Sites, Second Edition

20

JavaScript Functions

• All function code should be placed in the heading section of the HTML document

• The commands that call the functions are placed where they need to be executed in the document body 

• The command that calls a function may pass one or more parameters to the function

• Function commands may perform an action or return a data value to the calling command

Page 21: Database-Driven Web Sites, Second Edition1 Chapter 3 INTRODUCTION TO CLIENT-SIDE SCRIPTS

Database-Driven Web Sites, Second Edition

21

Creating a Custom Function

• The first line of a function contains the function declaration, which defines the function name and specifies the parameters that the function receives from the calling program or command

Page 22: Database-Driven Web Sites, Second Edition1 Chapter 3 INTRODUCTION TO CLIENT-SIDE SCRIPTS

Database-Driven Web Sites, Second Edition

22

Creating a Custom Function

• Function declaration: – Begins with the reserved word function

– Then the name of the function and an optional parameter list is specified

• The function name must begin with a letter, and can contain numbers, letters, and underscores (_)

• Function names cannot contain any other special characters, such as hyphens (-) or pound signs (#)

• Letters within function names are case-sensitive

Page 23: Database-Driven Web Sites, Second Edition1 Chapter 3 INTRODUCTION TO CLIENT-SIDE SCRIPTS

Database-Driven Web Sites, Second Edition

23

Calling a Function

• A JavaScript function can be called from directly within a JavaScript command by specifying:– Name of the function

– List of parameter values that are to be passed to the function

– Syntax:

function_name (param1_value, param2_value, …) 

Page 24: Database-Driven Web Sites, Second Edition1 Chapter 3 INTRODUCTION TO CLIENT-SIDE SCRIPTS

Database-Driven Web Sites, Second Edition

24

Event Handlers

• HTML objects have events that occur as a result of user actions

• Event handlers:– Contain program commands that execute when an

event occurs

– Syntax

<element attributes

event_handler_name ="JavaScript_command ">

Page 25: Database-Driven Web Sites, Second Edition1 Chapter 3 INTRODUCTION TO CLIENT-SIDE SCRIPTS

Database-Driven Web Sites, Second Edition

25

Event Handlers

• It is not a good practice to place JavaScript tags and commands at the end of the body section of an HTML document

• To execute a script when a browser first loads, an onload event handler associated with the HTML document is created, and this event handler calls a function or executes a command

Page 26: Database-Driven Web Sites, Second Edition1 Chapter 3 INTRODUCTION TO CLIENT-SIDE SCRIPTS

Database-Driven Web Sites, Second Edition

26

Displaying Script Error Information In Internet Explorer

• When an error occurs in a client-side script, Internet Explorer displays a default error notification message

• For debugging client-side scripts, script developers usually configure Internet Explorer to display a Script Debugger Error dialog box, providing information about script errors

Page 27: Database-Driven Web Sites, Second Edition1 Chapter 3 INTRODUCTION TO CLIENT-SIDE SCRIPTS

Database-Driven Web Sites, Second Edition

27

Configuring Internet Explorer to Display or Suppress Default Script Error Notification

Messages

Page 28: Database-Driven Web Sites, Second Edition1 Chapter 3 INTRODUCTION TO CLIENT-SIDE SCRIPTS

Database-Driven Web Sites, Second Edition

28

Configuring Internet Explorer to Display or Suppress Default Script Error Notification

Messages

• Defaults on Advanced properties page:– Check the Disable script debugging check box

– Clear Display a notification about every script error

• Browser displays the error notification message and allows the user to retrieve additional information

Page 29: Database-Driven Web Sites, Second Edition1 Chapter 3 INTRODUCTION TO CLIENT-SIDE SCRIPTS

Database-Driven Web Sites, Second Edition

29

Configuring Your Workstation to Display the Script Debugger Error

Message Box

• If the Display a notification about every script error check box is checked, Internet Explorer displays the Script Debugger message box only if Script Debugger is installed on the workstation

Page 30: Database-Driven Web Sites, Second Edition1 Chapter 3 INTRODUCTION TO CLIENT-SIDE SCRIPTS

Database-Driven Web Sites, Second Edition

30

Using Variables in JavaScript Commands

• Programs use variables:– to store numbers, text, dates, and other types of

data that the browser can display and that client-side script commands can manipulate

• Variables have a name and data type that specifies the kind of data that the variable stores

• Data types enable:– Program error checking

– Optimization of memory

Page 31: Database-Driven Web Sites, Second Edition1 Chapter 3 INTRODUCTION TO CLIENT-SIDE SCRIPTS

Database-Driven Web Sites, Second Edition

31

Using Variables in JavaScript Commands

• Strongly typed language: – requires programmer to declare variables and their

data types before they are used in a program command

• JavaScript is loosely typed: programmer does not need to specify the data type when the variable is declared

Page 32: Database-Driven Web Sites, Second Edition1 Chapter 3 INTRODUCTION TO CLIENT-SIDE SCRIPTS

Database-Driven Web Sites, Second Edition

32

Declaring JavaScript Variables and Assigning Values to Variables

• Variable declaration syntax: var variable_name ;

• Variable names must begin with a letter, and can contain numbers, letters, and underscores (_)

• Letters within variable names are case-sensitive• To assign a value to a variable

variable_name = value;

• Can declare and initialize a variablevar variable_name = initial_value ;

Page 33: Database-Driven Web Sites, Second Edition1 Chapter 3 INTRODUCTION TO CLIENT-SIDE SCRIPTS

Database-Driven Web Sites, Second Edition

33

Using JavaScript Operators to Manipulate Variables

• Operators perform arithmetic and string operations on literal and variable values

• Concatenation operator (+): joins two separate string elements into a single string element

• Display string values on multiple lines: use “\n” in a string to break its display into separate lines

Page 34: Database-Driven Web Sites, Second Edition1 Chapter 3 INTRODUCTION TO CLIENT-SIDE SCRIPTS

Database-Driven Web Sites, Second Edition

34

Using JavaScript Operators to Manipulate Variables

• Assignment operators: allow programmers to perform operations and assignments in a single command

• Plus sign:– Is overloaded, which means it can be used for two

different operations

– Can be used for numeric addition and string concatenation

Page 35: Database-Driven Web Sites, Second Edition1 Chapter 3 INTRODUCTION TO CLIENT-SIDE SCRIPTS

Database-Driven Web Sites, Second Edition

35

Specifying the Order of Operations

• Operations are evaluated in a specific order• The interpreter evaluates operations in

parentheses or square brackets first, and then evaluates additional operations in the order listed

• The interpreter evaluates assignment operations last

Page 36: Database-Driven Web Sites, Second Edition1 Chapter 3 INTRODUCTION TO CLIENT-SIDE SCRIPTS

Database-Driven Web Sites, Second Edition

36

Specifying the Order of Operations

• Operations at the same level, such as addition and subtraction, are evaluated from left to right

• Concatenation operations are evaluated from left to right, with operations in parentheses evaluated first

Page 37: Database-Driven Web Sites, Second Edition1 Chapter 3 INTRODUCTION TO CLIENT-SIDE SCRIPTS

Database-Driven Web Sites, Second Edition

37

Using JavaScript Built-In Object Classes

• To perform similar operations in JavaScript, built-in object classes are used

• To use a built-in object, create an instance and assign a value to the new object’s value property

• The object’s methods can then be used to perform tasks on the associated value

• Syntax to create a new object:

var variable_name = new object_type ();

Page 38: Database-Driven Web Sites, Second Edition1 Chapter 3 INTRODUCTION TO CLIENT-SIDE SCRIPTS

Database-Driven Web Sites, Second Edition

38

Using JavaScript Built-In Object Classes

• String Objects– Create a new String object named currentItem and

assign “3-Season Tents” to its value property:

var currentItem = new String();

currentItem.value = "3-Season Tents";

• Math Objects– The Math object class expands the usefulness of

the JavaScript arithmetic operators

– Object instances of the Math class do not need to be created

Page 39: Database-Driven Web Sites, Second Edition1 Chapter 3 INTRODUCTION TO CLIENT-SIDE SCRIPTS

Database-Driven Web Sites, Second Edition

39

Using JavaScript Built-In Object Classes

• Date Objects– Date objects format and manipulate date and time

values and retrieve the date and time on the workstation

– Date value is divided into individual year, month, day, current hour, minute, and second components

• Number Objects

– Number objects format numeric values

Page 40: Database-Driven Web Sites, Second Edition1 Chapter 3 INTRODUCTION TO CLIENT-SIDE SCRIPTS

Database-Driven Web Sites, Second Edition

40

Using Global Functions to Perform Explicit Data Type Conversions

• By default, all data values that users enter into Web page forms are text strings

• To convert text strings to numbers, perform an explicit data type conversion

• To perform a conversion, write a program command to convert a value from one data type to another

• JavaScript provides global functions to perform explicit data type conversions

Page 41: Database-Driven Web Sites, Second Edition1 Chapter 3 INTRODUCTION TO CLIENT-SIDE SCRIPTS

Database-Driven Web Sites, Second Edition

41

Converting Strings to Numbers

• parseInt() global function: – Converts a string representation of a number into a

number representation– Removes any decimal or fractional parts

• parseFloat() global function:– Converts a string representation of a number into a

number representation– Retains the decimal or fractional parts

• The general syntax for these functions is:number_variable = parseInt ("string_number ");number_variable = parseFloat ("string_number ");

Page 42: Database-Driven Web Sites, Second Edition1 Chapter 3 INTRODUCTION TO CLIENT-SIDE SCRIPTS

Database-Driven Web Sites, Second Edition

42

Converting Numbers to Strings

• The easiest way to convert a date or number variable to a string data type is to concatenate the date or number variable to an empty string literal

• An empty string literal:– String value that does not contain any characters

– Consists of two double quotation marks, with no characters inserted in between: “”

Page 43: Database-Driven Web Sites, Second Edition1 Chapter 3 INTRODUCTION TO CLIENT-SIDE SCRIPTS

Database-Driven Web Sites, Second Edition

43

Decision Control Structures

• Decision control structures: execute alternate statements based on true/false conditions

• “if” control structure tests whether a condition is true or false– If the condition is true, the interpreter executes a

set of program statements

– If the condition is false, the interpreter skips the program statements

Page 44: Database-Driven Web Sites, Second Edition1 Chapter 3 INTRODUCTION TO CLIENT-SIDE SCRIPTS

Database-Driven Web Sites, Second Edition

44

Decision Control Structures

• if/else control structure– Tests a condition

– Executes one set of statements if the condition is true, and an alternate set if the condition is false

• if/else if control structure allows the program to test for many unrelated conditions, and execute specific program statements for each true condition 

Page 45: Database-Driven Web Sites, Second Edition1 Chapter 3 INTRODUCTION TO CLIENT-SIDE SCRIPTS

Database-Driven Web Sites, Second Edition

45

Decision Control Structures

• switch control structure: – Program can test multiple conditions that compare

the same variable value

– Executes faster than the equivalent if/else if structure

– Requires fewer program lines

• However, it can only be used when the condition evaluates whether an expression is equal to another expression

Page 46: Database-Driven Web Sites, Second Edition1 Chapter 3 INTRODUCTION TO CLIENT-SIDE SCRIPTS

Database-Driven Web Sites, Second Edition

46

Using the AND and OR Logical Operators in Control Structure

Conditions

• AND operator (&&): overall condition is true if both conditions are true

• OR operator (||): overall condition is true if either condition is true

Page 47: Database-Driven Web Sites, Second Edition1 Chapter 3 INTRODUCTION TO CLIENT-SIDE SCRIPTS

Database-Driven Web Sites, Second Edition

47

Creating Repetition (Looping) Structures

• Loop: – A repetition structure that processes multiple

values the same way– Repeatedly executes a series of program

statements and periodically evaluates an exit condition

• Pretest loop: evaluates the exit condition before any program commands execute

• Posttest loop: one or more program commands execute before the loop evaluates the exit condition the first time

Page 48: Database-Driven Web Sites, Second Edition1 Chapter 3 INTRODUCTION TO CLIENT-SIDE SCRIPTS

Database-Driven Web Sites, Second Edition

48

Creating Repetition (Looping) Structures

• while loop: pretest loop • do while loop: posttest loop• for loop: counting loop

– Programmers declare and control a counter variable from within the loop structure

Page 49: Database-Driven Web Sites, Second Edition1 Chapter 3 INTRODUCTION TO CLIENT-SIDE SCRIPTS

Database-Driven Web Sites, Second Edition

49

Contrasting JavaScript and Java

• Even though both JavaScript and Java use a C-style syntax for common programming tasks, their underlying structures and purposes are very different

• Java is a full-featured object-oriented programming language

• JavaScript is more limited and runs within HTML documents

Page 50: Database-Driven Web Sites, Second Edition1 Chapter 3 INTRODUCTION TO CLIENT-SIDE SCRIPTS

Database-Driven Web Sites, Second Edition

50

Summary

• Programmers use client-side scripts for tasks such as validating user inputs entered on HTML forms, opening new browser windows, and creating cookies

• The HTML document object model (DOM) is a hierarchical naming system that enables scripts to reference browser objects

• DOM objects are accessed and manipulated using dot syntax containing either object name or id attribute values

Page 51: Database-Driven Web Sites, Second Edition1 Chapter 3 INTRODUCTION TO CLIENT-SIDE SCRIPTS

Database-Driven Web Sites, Second Edition

51

Summary

• Events: actions that take place in a document as a result of a user action

• Functions: self-contained groups of program commands that are called within a script

• User-defined functions perform specific tasks • JavaScript is a loosely typed language• Decision control structures are created using if,

if/else, if/else if, and switch statements • Loops include while, do while, and for loops