2001 prentice hall, inc. all rights reserved. 1 chapter 7 - javascript: introduction to scripting...

42
2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 7 - JavaScript: Introduction to Scripting Outline 7.1 Introduction 7.2 Simple Program: Printing a Line of Text in a Web Page 7.3 Another JavaScript Program: Adding Integers 7.4 Memory Concepts 7.5 Arithmetic 7.6 Decision Making: Equality and Relational Operators 7.7 JavaScript Internet and World Wide Web Resources

Upload: buddy-edwards

Post on 29-Dec-2015

218 views

Category:

Documents


1 download

TRANSCRIPT

2001 Prentice Hall, Inc. All rights reserved.

1

Chapter 7 - JavaScript: Introduction to Scripting

Outline7.1 Introduction7.2 Simple Program: Printing a Line of Text in a Web Page7.3 Another JavaScript Program: Adding Integers7.4 Memory Concepts7.5 Arithmetic7.6 Decision Making: Equality and Relational Operators7.7 JavaScript Internet and World Wide Web Resources

2001 Prentice Hall, Inc. All rights reserved.

2

JavaScript scripting language

• JavaScript scripting language– Originally created by Netscape

– Facilitates disciplined approach to designing computer programs

– Enhances functionality and appearance of Web pages

• Jscript– Microsoft’s version of JavaScript

2001 Prentice Hall, Inc. All rights reserved.

3

Browser includes JavaScript Interpreter

• Browser includes JavaScript Interpreter – Processes JavaScript commands

• Whitespace – Blank lines, space characters, tab characters

– Generally ignored by browser

– Used for readability and clarity

• <SCRIPT>…</SCRIPT> tag:– Encloses entire script

– Attribute type = “text/javascript”• Indicates scripting language (JavaScript default in IE5 &

Netscape)

– Attribute LANGUAGE=“JavaScript” is an old style

2001 Prentice Hall, Inc. All rights reserved.

4

• document.writeln( “<H1>string</H1>” );– Case-sensitive, like all JavaScript functions

– Uses the writeln method in the browser’s document object

– Prints the string, which can consist of any text and HTML tags

– String must be surrounded by quotation marks (“…”)

• Correct method call syntax:– object.method( “string”, “[additional arguments]” );

• Statement terminators– All statements must end with semi-colons (;)

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

2001 Prentice Hall, Inc.All rights reserved.

Outline5

welcome.html

Program Output

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

Title o f the XHTML doc ument

Script result

Location and name of the loaded XHTML document

The document object’s writeln method writes a line of XHTML markup in the XHTML document.

The script tag indicates to the browser that the text which follows is part of a script.

2001 Prentice Hall, Inc.All rights reserved.

Outline6

Welcome2.html

Program Output

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

Using the style attribute, the color of the text is changed from black to magenta.

The escape sequence \” places a quote in the string and is not displayed in the browser.

2001 Prentice Hall, Inc. All rights reserved.

7How your browser translates?

JavaScript Interpreter

execute JavaScript

code

Browser renders HTML page

HTML page with JavaScript

page with HTML

code only

Rendered page

2001 Prentice Hall, Inc. All rights reserved.

8

writeln() vs. write()

• Object: document • methods:

– writeln • Positions output cursor on next line when finished

– write • Leaves the output cursor where it is when done executing

– Both begin output where previous statement stopped

– Line breaks inserted in two ways:• document.writeln( “Have a<br>Nice Day!” )• document.writeln( “Have a<p>Nice Day!” )

2001 Prentice Hall, Inc.All rights reserved.

Outline9

Welcome3.html

Program Output

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

Using break tags, the text is displayed as three lines.

2001 Prentice Hall, Inc.All rights reserved.

Outline10

Welcome4.html

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. 7.4: welcome4.html -->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>

The window method alert displays an alert dialog to the user.

When the alert dialog displays, the string passed as its one argument is displayed.

The escape sequence \n is the newline character that places all remaining text on the next line.

2001 Prentice Hall, Inc. All rights reserved.

11

window object

• Methods in window object– Call on-screen windows– window.alert( “argument” );

• Method calls alert window with window text "argument"• Outputs button with text and ‘OK’ button

– window.prompt(“”); • Prompts user for string (discussed later)

• Scripts restart when page reloaded/refreshed

2001 Prentice Hall, Inc. All rights reserved.

12

Reload /Refresh

Scripts restart when page reloaded/refreshed.

2001 Prentice Hall, Inc.All rights reserved.

Outline13

Program OutputThe OK button allows the user to dismiss (or hide) the dialog.

Title barThe dialog is automatically sized to accommodate

the string.

Mouse cursor

2001 Prentice Hall, Inc. All rights reserved.

14

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

Escape sequence Description

\n Newline. Position the screen cursor at the beginning of the next line.

\t Horizontal tab. Move the screen cursor to the next tab stop.

\r Carriage return. Position the screen cursor to the beginning of the current line; do not advance to the next line. Any characters output after the carriage return overwrite the characters previously output on that line.

\\ Backslash. Used to represent a backslash character in a string.

\" Double quote. Used to represent a double quote character in a string contained in double quotes. For example, window.alert( "\"in quotes\"" );

displays "in quotes" in an alert dialog.

\' Single quote. Used to represent a single quote character in a string. For example, window.alert( '\'in quotes\'' );

displays 'in quotes' in an alert dialog.

Fig. 7.5 Some common escape sequences.

2001 Prentice Hall, Inc. All rights reserved.

15

• Variables – Location in memory where values are stored

– Variable name can be any valid identifier• Identifier = series of characters

– Letters, digits, underscores (‘_’) and dollar signs (‘$’)

– Cannot begin with a digit

• Valid identifiers:

Welcome, $value, _value, m_inputField1, C3PO and R2D2• Invalid identifiers: 7button, Say\Hello and field#5

– Identifiers are case-sensitive

Variables

2001 Prentice Hall, Inc. All rights reserved.

16

Variable name convention

• Variable name convention– Begin with lowercase first letter

– Every following word has first letter capitalized • goRedSox, bostonUniversityRules

• Declarations– var name1, name2

– Indicate that name1 and name2 are program variables

2001 Prentice Hall, Inc. All rights reserved.

17

• Method window.prompt( “arg1”, “arg2” )Calls window that allows user to enter value to use in the

script

arg1 : text that will appear in window

arg2 : text that will initially appear in input line

• firstNumber = window.prompt();Assigns value entered by the user in prompt window to

variable firstNumber

"=" a binary operatorAssigns value of right operand to left operand

window.prompt()

2001 Prentice Hall, Inc. All rights reserved.

18

• Good programmers write many comments– Helps other programmers decode script

– Aids debugging

– Comment Syntax:• One-line comment: // [text]• Multi-line comment: /* [text] */

comments

2001 Prentice Hall, Inc. All rights reserved.

19

• parseInt(); – Function accepts a string and returns an integer value

• Not a method because we do not refer to an object name

number1 = parseInt( firstNumber );– Operates right-to-left (due to the "=" sign)

parseInt()

2001 Prentice Hall, Inc. All rights reserved.

20

• sum = number1 + number2; – Adds number1 and number2

– Assigns result to variable sum

• String concatenation:– Combines string and another data type

• Other data type can be another string

– Example: • If age = 20,

document.writeln( “I am ” + age + “years old!” );

Prints: I am 20 years old!

+ as addition and String concatenation operator

2001 Prentice Hall, Inc.All rights reserved.

Outline21

Addition.html

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. 7.6: Addition.html -->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 user15 secondNumber, // second string entered by user16 number1, // first number to add17 number2, // second number to add18 sum; // sum of number1 and number219 20 // read in first number from user as a string21 firstNumber = 22 window.prompt( "Enter first integer", "0" );23 24 // read in second number from user as a string25 secondNumber = 26 window.prompt( "Enter second integer", "0" );27 28 // convert numbers from strings to integers29 number1 = parseInt( firstNumber ); 30 number2 = parseInt( secondNumber );31 32 // add the numbers33 sum = number1 + number2;34

The window method prompt displays a prompt dialog in the browser with a message and a text field for input.

The first argument passed to method prompt is the message to be displayed.The second argument is the

default value for the text field.

Function parseInt converts its string argument to an integer.

The + operator adds the two numbers input by the user.

2001 Prentice Hall, Inc.All rights reserved.

Outline22

Addition.html

Program Output

35 // display the results36 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>

2001 Prentice Hall, Inc. All rights reserved.

23

7.3 Another JavaScript Program: Adding Integers

When the user clicks OK , the value typed by the user is returned to the program as a string. The program must convert the string to a number.

This is the text field in which the user types the value.

This is the prompt to the user.

This is the default value if the user does not enter a number.

Fig. 7.7 Prompt dialog displayed by the window object’s prompt method.

2001 Prentice Hall, Inc. All rights reserved.

24

7.4 Memory Concepts

number1 45

number1 45

number2 72

Fig. 7.8 Memory location showing the name and value of variable number1.

Fig. 7.9 Memory locations after values for variables number1 and number2 have been input.

2001 Prentice Hall, Inc. All rights reserved.

25

Variables & Memory Concepts

• Variables:– Name corresponds to location in memory

– Have 3 attributes:• Name

• Type

• Value

• Memory– When a value assigned to a variable, it overwrites any previous

value

– Reading values is non-destructive• sum = number1 + number2• Does not change number1 or number2

2001 Prentice Hall, Inc. All rights reserved.

26

7.5 Arithmetic

number1 45

number2 72

sum 117

Fig. 7.10 Memory locations after calculating the sum of number1 and number2.

2001 Prentice Hall, Inc. All rights reserved.

27

• Binary Operators – Used in arithmetic operations

• Modulus operator (%) – Yields remainder after division– Examples:

43 % 5 = 3 8.7 % 3.4 = 1.924 % 6 = 0

Operators

2001 Prentice Hall, Inc. All rights reserved.

28

7.5 ArithmeticJ avaScript operation

Arithmetic operator

Algebraic expression

J avaScript expression

Addition + f + 7 f + 7

Subtraction - p – c p - c Multiplication * bm b * m Division / x / y or <Anchor9> or x y x / y

Modulus % r mod s r % s Fig. 7.11 Arithmetic operators.

2001 Prentice Hall, Inc. All rights reserved.

29

Arithmetic

J avaScript operation

Arithmetic operator

Algebraic expression

J avaScript expression

Addition + f + 7 f + 7

Subtraction - p – c p - c

Multiplication * bm b * m

Division / x / y or x y x / y Modulus % r mod s r % s

2001 Prentice Hall, Inc. All rights reserved.

30

operator precedence

• Arithmetic operations – Operate right to left (like the ‘=’ sign)

• Rules of operator precedence

– Operations execute in a specific order

Operator(s) Operation(s) Order of evaluation (precedence) ( ) Parentheses 1) If the parentheses nested, expression in innermost pair evaluated first. If

several pairs of parentheses “on the same level” (not nested), evaluated left to right.

*, / or % Multiplication, Division, Modulus

2) If more then one, then evaluated left to right.

+ or - Addition, Subtraction 3) If more than one, then evaluated left to right.

2001 Prentice Hall, Inc. All rights reserved.

31

Order of evaluation

y = 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—assignment)

Step 1.

Step 2.

Step 3.

Step 4.

Step 5.

Step 6.

2001 Prentice Hall, Inc. All rights reserved.

32

• if structure:– Program makes decision based on truth or falsity of condition

• If condition met (true) – Statement(s) in body of if structure executed

• If condition not met (false) – Statement(s) in body of if structure skipped

• Format:if (condition) { statement; (additional statements);}• Semi-colon (‘;’)

– Do not place after condition– Place after every statement in body of structure

Decision Making: Equality and Relational Operators

2001 Prentice Hall, Inc. All rights reserved.

33

Equality and Relational Operators

Equality and Relational Operators:

2001 Prentice Hall, Inc. All rights reserved.

34

Operator precedancey = 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.

Fig. 7.13 Order in which a second-degree polynomial is evaluated.

2001 Prentice Hall, Inc. All rights reserved.

35

7.6 Decision Making: Equality and Relational Operators

2001 Prentice Hall, Inc.All rights reserved.

Outline36

Comparison.html

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. 7.14: comparison.html -->6 <!-- Using if statements, relational operators --> 7 <!-- and equality operators -->8 9 <html xmlns = "http://www.w3.org/1999/xhtml">10 <head>11 <title>Performing Comparisons</title>12 13 <script type = "text/javascript">14 <!--15 var first, // first string entered by user16 second, // second string entered by user17 number1, // first number to compare18 number2; // second number to compare19 20 // read first number from user as a string21 first = window.prompt( "Enter first integer:", "0" );22 23 // read second number from user as a string24 second = window.prompt( "Enter second integer:", "0" );25 26 // convert numbers from strings to integers27 number1 = parseInt( first ); 28 number2 = parseInt( second );29 30 document.writeln( "<h1>Comparison Results</h1>" );31 document.writeln( 32 "<table border = \"1\" width = \"100%\">" );33

Two prompt dialogs retrieve user input.

2001 Prentice Hall, Inc.All rights reserved.

Outline37

Comparison.html

34 if ( number1 == number2 )35 document.writeln( "<tr><td>" + number1 + " == " +36 number2 + "</td></tr>" );37 38 if ( number1 != number2 )39 document.writeln( "<tr><td>" + number1 + " != " +40 number2 + "</td></TR>" );41 42 if ( number1 < number2 )43 document.writeln( "<tr><td>" + number1 + " < " +44 number2 + "</td></tr>" );45 46 if ( number1 > number2 )47 document.writeln( "<tr><td>" + number1 + " > " +48 number2 + "</td></tr>" );49 50 if ( number1 <= number2 )51 document.writeln( "<tr><td>" + number1 + " <= " +52 number2 + "</td></tr>" );53 54 if ( number1 >= number2 )55 document.writeln( "<tr><td>" + number1 + " >= " +56 number2 + "</td></tr>" );57 58 // Display results59 document.writeln( "</table>" );60 // -->61 </script>62 63 </head>64 <body>65 <p>Click Refresh (or Reload) to run the script again</p>66 </body>67 </html>

Each if statement uses the equality operators to determine the relationship of the two integers input by the user.

2001 Prentice Hall, Inc. All rights reserved.

38

If: First Integer = 123

Second Integer = 123

If: First Integer = 100

Second Integer = 200

If: First Integer = 200

Second Integer = 100

2001 Prentice Hall, Inc.All rights reserved.

Outline39

Program Output

2001 Prentice Hall, Inc.All rights reserved.

Outline40

Program Output

2001 Prentice Hall, Inc.All rights reserved.

Outline41

Program Output

2001 Prentice Hall, Inc. All rights reserved.

42

7.6 Decision Making: Equality and Relational Operators