Top Banner
Chapter 7 Chapter 7 JavaScript: JavaScript: Introduction to Introduction to Scripting Scripting
29

Chapter 7 JavaScript: Introduction to Scripting. Outline Simple Programs Objects and Variables Obtaining User Input with prompt Dialogs – –Dynamic Welcome.

Mar 26, 2015

Download

Documents

Brandon Heath
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Chapter 7 JavaScript: Introduction to Scripting. Outline Simple Programs Objects and Variables Obtaining User Input with prompt Dialogs – –Dynamic Welcome.

Chapter 7Chapter 7

JavaScript: Introduction to JavaScript: Introduction to ScriptingScripting

Page 2: Chapter 7 JavaScript: Introduction to Scripting. Outline Simple Programs Objects and Variables Obtaining User Input with prompt Dialogs – –Dynamic Welcome.

OutlineOutline

• Simple Programs

• Objects and Variables

• Obtaining User Input with prompt Dialogs– Dynamic Welcome Page– Adding Integers

• Arithmetic

• Decision Making: Equality and Relational Operators

Page 3: Chapter 7 JavaScript: Introduction to Scripting. Outline Simple Programs Objects and Variables Obtaining User Input with prompt Dialogs – –Dynamic Welcome.

IntroductionIntroduction

• JavaScript is an interpreted, scripted, JavaScript is an interpreted, scripted, programming languageprogramming language– Core syntax resembles C++ and JavaCore syntax resembles C++ and Java– has some “object-oriented capabilities”has some “object-oriented capabilities”

• Web browsers contain a JavaScript Web browsers contain a JavaScript interpreterinterpreter

• Use JavaScript to Use JavaScript to – Enhances functionality and appearanceEnhances functionality and appearance– Makes pages more dynamic and interactive Makes pages more dynamic and interactive – etc…etc…

Page 4: Chapter 7 JavaScript: Introduction to Scripting. Outline Simple Programs Objects and Variables Obtaining User Input with prompt Dialogs – –Dynamic Welcome.

JavaScriptJavaScript

• JavaScript is JavaScript is case sensitivecase sensitive• Statements in JavaScript end in a Statements in JavaScript end in a

semi-colonsemi-colon• JavaScript code is often embedded in JavaScript code is often embedded in

the <head> section of the documentthe <head> section of the document• JavaScript code in the <head> section JavaScript code in the <head> section

is executed before any XHTML code in is executed before any XHTML code in the <body> of the documentthe <body> of the document

Page 5: Chapter 7 JavaScript: Introduction to Scripting. Outline Simple Programs Objects and Variables Obtaining User Input with prompt Dialogs – –Dynamic Welcome.

JavaScriptJavaScript

• Use the <script> element to embed Use the <script> element to embed JavaScript code within your XHTML:JavaScript code within your XHTML:– e.g.e.g.

<script type="text/javascript"><script type="text/javascript">

document.writeln ("<h1>Welcome to COSC 2956 document.writeln ("<h1>Welcome to COSC 2956 </h1>")</h1>")

</script></script>

– typetype attribute attribute• Specifies the type of file and the scripting language useSpecifies the type of file and the scripting language use

– writelnwriteln method method• Write a line in the documentWrite a line in the document

Page 6: Chapter 7 JavaScript: Introduction to Scripting. Outline Simple Programs Objects and Variables Obtaining User Input with prompt Dialogs – –Dynamic Welcome.

JavaScriptJavaScript

• JavaScript code can be shielded with XHTML comments: JavaScript code can be shielded with XHTML comments: – <!-- <!-- and and // -->// -->– needed for proper validationneeded for proper validation

<script type="text/javascript"><script type="text/javascript"><!--<!--//// our first JavaScript code snippet our first JavaScript code snippetdocument.title = "Welcome to COSC 2956";document.title = "Welcome to COSC 2956";// -->// -->

</script></script>• Comments within JavaScript code can be:Comments within JavaScript code can be:

– single-line style: single-line style: //// my single-line commentmy single-line comment– multi-line style: multi-line style: /*/* … … my multi-line commentmy multi-line comment ... ... */*/

Page 7: Chapter 7 JavaScript: Introduction to Scripting. Outline Simple Programs Objects and Variables Obtaining User Input with prompt Dialogs – –Dynamic Welcome.

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>

Page 8: Chapter 7 JavaScript: Introduction to Scripting. Outline Simple Programs Objects and Variables Obtaining User Input with prompt Dialogs – –Dynamic Welcome.

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>

Page 9: Chapter 7 JavaScript: Introduction to Scripting. Outline Simple Programs Objects and Variables Obtaining User Input with prompt Dialogs – –Dynamic Welcome.

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>

Page 10: Chapter 7 JavaScript: Introduction to Scripting. Outline Simple Programs Objects and Variables Obtaining User Input with prompt Dialogs – –Dynamic Welcome.
Page 11: Chapter 7 JavaScript: Introduction to Scripting. Outline Simple Programs Objects and Variables Obtaining User Input with prompt Dialogs – –Dynamic Welcome.

ObjectsObjects

• An object consists of An object consists of – properties (attributes)properties (attributes)– methods (behaviour)methods (behaviour)

• Properties define the characteristics of an Properties define the characteristics of an object object – e.g., a browser document has a 'e.g., a browser document has a 'titletitle' property' property

• Methods define the functions that an object Methods define the functions that an object can performcan perform– e.g., a browser window can be resized e.g., a browser window can be resized

programmatically by using the programmatically by using the resizeTo( ) resizeTo( ) methodmethod

Page 12: Chapter 7 JavaScript: Introduction to Scripting. Outline Simple Programs Objects and Variables Obtaining User Input with prompt Dialogs – –Dynamic Welcome.

ObjectsObjects

• To use a property of an object, use the To use a property of an object, use the following syntax: following syntax: objectName.propertyNameobjectName.propertyName– For example:For example:

document.title = "My title " document.title = "My title " window.defaultStatus = "Everything is A-OK"window.defaultStatus = "Everything is A-OK"

• To use a method of an object, use the To use a method of an object, use the following syntax: following syntax: objectName.methodName( objectName.methodName( <parameters> )<parameters> )– For example, to resize the browser width and For example, to resize the browser width and

height:height:window.resizeTo( 600, 400 )window.resizeTo( 600, 400 )

Page 13: Chapter 7 JavaScript: Introduction to Scripting. Outline Simple Programs Objects and Variables Obtaining User Input with prompt Dialogs – –Dynamic Welcome.

The document ObjectThe document Object

• Every window object has a Every window object has a documentdocument object, that allows object, that allows you to access properties and methods of the document you to access properties and methods of the document currently loaded into the browsercurrently loaded into the browser

• Some Some documentdocument properties: properties:– bgColor, fgColor - background and foreground colour of the bgColor, fgColor - background and foreground colour of the

documentdocument– alinkColor, linkColor, vlinkColor - colours for hypertext linksalinkColor, linkColor, vlinkColor - colours for hypertext links– URL - the URL of the current documentURL - the URL of the current document– referrer - the URL of the document with the link that loaded referrer - the URL of the document with the link that loaded

this documentthis document– title - the title of the documenttitle - the title of the document– lastModified - the modification date of the documentlastModified - the modification date of the document

• Some Some documentdocument methods methods– write( )write( )– writeln( ) writeln( )

Page 14: Chapter 7 JavaScript: Introduction to Scripting. Outline Simple Programs Objects and Variables Obtaining User Input with prompt Dialogs – –Dynamic Welcome.

document.writeln( )document.writeln( )

• Use the Use the document.writeln( )document.writeln( ) method to method to dynamically generate XHTML codedynamically generate XHTML code

• Pass writeln( ) the XHTML code that is to be Pass writeln( ) the XHTML code that is to be rendered, as a quoted string; e.g.,rendered, as a quoted string; e.g.,– document.writeln("<h1>First Heading</h1>");document.writeln("<h1>First Heading</h1>");

• writeln( ) writes a line of XHTML markup and writeln( ) writes a line of XHTML markup and positions the output cursor at the beginning of positions the output cursor at the beginning of the next line (of the code being generated, not the next line (of the code being generated, not the rendered document)the rendered document)

• XHTML validator does not catch errors in HTML XHTML validator does not catch errors in HTML embedded in JavaScriptembedded in JavaScript

Page 15: Chapter 7 JavaScript: Introduction to Scripting. Outline Simple Programs Objects and Variables Obtaining User Input with prompt Dialogs – –Dynamic Welcome.

The window ObjectThe window Object

• Every web browser Every web browser windowwindow is represented by a window is represented by a window objectobject

• A A windowwindow object defines properties and methods that allow object defines properties and methods that allow you to manipulate the web browser windowyou to manipulate the web browser window

• Some window properties:Some window properties:– defaultStatus - text that appears in the status line of the defaultStatus - text that appears in the status line of the

browser browser • Some window methods:Some window methods:

– alert( ), confirm( ), prompt( ) - simple dialog boxesalert( ), confirm( ), prompt( ) - simple dialog boxes– close( ) - close the windowclose( ) - close the window– open( ) - open a new top-level window to display a documentopen( ) - open a new top-level window to display a document– print( ) - print the contents of the windowprint( ) - print the contents of the window– resizeBy( ), resizeTo( ) - resize the windowresizeBy( ), resizeTo( ) - resize the window– moveTo( ) - move the windowmoveTo( ) - move the window

Page 16: Chapter 7 JavaScript: Introduction to Scripting. Outline Simple Programs Objects and Variables Obtaining User Input with prompt Dialogs – –Dynamic Welcome.

VariablesVariables

• Use a variable to store, manipulate and retrieve a value Use a variable to store, manipulate and retrieve a value from memory during program executionfrom memory during program execution

• A variable can hold a variable of any typeA variable can hold a variable of any type– x = 12;x = 12;– x = "123";x = "123";

• Declare variables with the Declare variables with the varvar keyword keywordvar x;var x;var y = "abd";var y = "abd";var myInt = 1, myFloat = 2.4;var myInt = 1, myFloat = 2.4;

• Variables that are declared but not initialized are Variables that are declared but not initialized are undefinedundefined. . Trying to print them produces the string literal "undefined"Trying to print them produces the string literal "undefined"

• Attempting to read the value of a variable that is not Attempting to read the value of a variable that is not declared causes a run-time errordeclared causes a run-time error

Page 17: Chapter 7 JavaScript: Introduction to Scripting. Outline Simple Programs Objects and Variables Obtaining User Input with prompt Dialogs – –Dynamic Welcome.

welcome5.htmlwelcome5.html(1 of 2)(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 <!-- Fig. 7.6: welcome5.html -->

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>

Page 18: Chapter 7 JavaScript: Introduction to Scripting. Outline Simple Programs Objects and Variables Obtaining User Input with prompt Dialogs – –Dynamic Welcome.

23

24 </head>

25

26 <body>

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

28 </body>

29 </html>

Page 19: Chapter 7 JavaScript: Introduction to Scripting. Outline Simple Programs Objects and Variables Obtaining User Input with prompt Dialogs – –Dynamic Welcome.

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

This is the promptto the user.

This is the default value that appears when the dialog opens.

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

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

Page 20: Chapter 7 JavaScript: Introduction to Scripting. Outline Simple Programs Objects and Variables Obtaining User Input with prompt Dialogs – –Dynamic Welcome.

Example: Adding IntegersExample: Adding Integers

• Prompt user for two integers and Prompt user for two integers and calculate the sum (Fig. 7.8)calculate the sum (Fig. 7.8)

• parseIntparseInt– Converts its string argument to an Converts its string argument to an

integerinteger

Page 21: Chapter 7 JavaScript: Introduction to Scripting. Outline Simple Programs Objects and Variables Obtaining User Input with prompt Dialogs – –Dynamic Welcome.

Addition.htmlAddition.html(1 of 2)(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 <!-- Fig. 7.8: 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 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

Page 22: Chapter 7 JavaScript: Introduction to Scripting. Outline Simple Programs Objects and Variables Obtaining User Input with prompt Dialogs – –Dynamic Welcome.

Addition.htmlAddition.html(2 of 2)(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>

Page 23: Chapter 7 JavaScript: Introduction to Scripting. Outline Simple Programs Objects and Variables Obtaining User Input with prompt Dialogs – –Dynamic Welcome.
Page 24: Chapter 7 JavaScript: Introduction to Scripting. Outline Simple Programs Objects and Variables Obtaining User Input with prompt Dialogs – –Dynamic Welcome.

ArithmeticArithmetic

• Many scripts perform arithmetic Many scripts perform arithmetic calculationscalculations– Expressions in JavaScript must be written in Expressions in JavaScript must be written in

straight-line formstraight-line formJavaScript 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

Fig. 7.12 Arithmetic operators.

Page 25: Chapter 7 JavaScript: Introduction to Scripting. Outline Simple Programs Objects and Variables Obtaining User Input with prompt Dialogs – –Dynamic Welcome.

Equality and Relational Equality and Relational OperatorsOperators

• Decision based on the truth or falsity Decision based on the truth or falsity of a conditionof a condition– Equality operatorsEquality operators– 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 Fig. 7.15 Equality and relational operators.

Page 26: Chapter 7 JavaScript: Introduction to Scripting. Outline Simple Programs Objects and Variables Obtaining User Input with prompt Dialogs – –Dynamic Welcome.

welcome6.htmlwelcome6.html(1 of 3)(1 of 3)

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. 7.16: welcome6.html -->

6 <!-- Using Relational Operators -->

7

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

9 <head>

10 <title>Using Relational Operators</title>

11

12 <script type = "text/javascript">

13 <!--

14 var name, // string entered by the user

15 now = new Date(), // current date and time

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

17

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

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

20

21 // determine whether it is morning

22 if ( hour < 12 )

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

24

Page 27: Chapter 7 JavaScript: Introduction to Scripting. Outline Simple Programs Objects and Variables Obtaining User Input with prompt Dialogs – –Dynamic Welcome.

welcome6.htmlwelcome6.html(2 of 3)(2 of 3)

25 // determine whether the time is PM

26 if ( hour >= 12 )

27 {

28 // convert to a 12 hour clock

29 hour = hour - 12;

30

31 // determine whether it is before 6 PM

32 if ( hour < 6 )

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

34

35 // determine whether it is after 6 PM

36 if ( hour >= 6 )

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

38 }

39

40 document.writeln( name +

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

42 // -->

43 </script>

44

45 </head>

46

Page 28: Chapter 7 JavaScript: Introduction to Scripting. Outline Simple Programs Objects and Variables Obtaining User Input with prompt Dialogs – –Dynamic Welcome.

47 <body>

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

49 </body>

50 </html>

Page 29: Chapter 7 JavaScript: Introduction to Scripting. Outline Simple Programs Objects and Variables Obtaining User Input with prompt Dialogs – –Dynamic Welcome.

Operators SummaryOperators Summary

Operators Associativity Type * / % left to right multiplicative + - left to right additive < <= > >= left to right relational == != left to right equality = right to left assignment Fig. 7.17 Precedence and associativity of the

operators discussed so far.