lesson 10 -- interactive scripts

46
Lesson 10 -- Interactive Scripts • JavaScript statements must go inside a script container, usually placed in the head section of the HTML document, but not always. <script language="JavaScript"> JavaScript statements </script>

Upload: marcello-hilton

Post on 03-Jan-2016

34 views

Category:

Documents


0 download

DESCRIPTION

Lesson 10 -- Interactive Scripts JavaScript statements must go inside a script container, usually placed in the head section of the HTML document, but not always. JavaScript statements . - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Lesson 10 -- Interactive  Scripts

Lesson 10 -- Interactive Scripts

• JavaScript statements must go inside a script container, usually placed in the head section of the HTML document, but not always.

<script language="JavaScript"> JavaScript statements</script>

Page 2: Lesson 10 -- Interactive  Scripts

• A JavaScript statement is an instruction to the JavaScript interpreter.• A statement we will use often:

document.write("Hello!");

• Says "write the string "Hello!" to the HTML document."• All JavaScript statements should be terminated with a semi-colon.

• A string is simply a string of characters delimited with quotes. " xYz " -- 5 character string, including spaces Dog -- How many characters? -- Not well defined as a string

Page 3: Lesson 10 -- Interactive  Scripts

See source file hello.html(Figure 10.1).

Page 4: Lesson 10 -- Interactive  Scripts

• HTML can be written using a document.write statement. See source file scoob.html (Figure 10.2).

document.write("<p align='center'><b>Scooby Doo,</b><br />Where are you?</p>");

Other points to be made• In a long document.write statement, NEVER hit return on the keyboard (adds a line return character to middle of string). Rather, let the statement automatically wrap around in the text editor.• Single quotes must be used on the inside. Otherwise, the browser thinks the string to be written terminates.

document.write("<p align="center"><b>Scooby Doo,

</b><br />Where are you?</p>"); //OOPS!

Page 5: Lesson 10 -- Interactive  Scripts

<script language=”JavaScript”> document.write("Dear Scooby, "); document.write("were you able to elude the werewolf?”);<script> Result in Web page:Dear Scooby, were you able to elude the werewolf? <script language=”JavaScript”> document.write("Dear Scooby,<br />"); document.write("Were you able to elude the werewolf?”);<script>Result in Web page (forced line break):Dear Scooby, were you able to elude the werewolf?

Page 6: Lesson 10 -- Interactive  Scripts

How does a browser deal with both HTML and JavaScript?

• Browser has separate JavaScript and HTML "brains."

• Content generated by JavaScript is first inserted into HTML document (browser's in-memory version of HTML file).

• Effectively, the HTML brain then sees raw HTML after the JavaScript executes.

Page 7: Lesson 10 -- Interactive  Scripts

See again scoob.html. After the JavaScript executes, the HTML markup engine sees.

<html> <head> <title>Writing HTML Tags</title> </head> <body> <p align=”center”><b>Scooby Doo</b> <br />Where are you?</p> </body></html>

Page 8: Lesson 10 -- Interactive  Scripts

See multiplescripts.html source file

• Three separate scripts in one HTML file. • All content generated in document order -- the top-down order of code in the HTML file.• In the end, the HTML brain sees:

<html> <head> <title>Writing HTML Tags</title> </head> <body>

I'm first man!<br /> OK, buddy.That's fine.<br />Last but not least. </body></html>

Page 9: Lesson 10 -- Interactive  Scripts

Comments are completely ignored by the JavaScript interpreter -- only for human benefit.

// single-line comment

/* A comment which spills overmultiple lines */

Page 10: Lesson 10 -- Interactive  Scripts

Prompting for user input.See source file prompt.html.

Page 11: Lesson 10 -- Interactive  Scripts

Problem: • User input from prompt not stored in memory• Goes into obliveon.Solution: • Store user input into a variablevar x;

• Declares an empty storage location in RAM whose name is x.• Think of a variable as a box, labeled with a name, into which you can store and retrieve data.

Page 12: Lesson 10 -- Interactive  Scripts

A three-line script:• Declare and empty variable• Store the input into the variable• Write the contents of the variable to the HTML document.

Page 13: Lesson 10 -- Interactive  Scripts

Our first complete interactive program.See source file greeting.html (Figure 10.6)

var name;name = prompt("Please enter your name.","");document.write(name);document.write(", welcome to our first interactive page.");

Notes:• You choose the variable name.• Could name the variable x• Descriptive variable names are best for humans• Variable names are given as bare words• document.write("name"); literally would write the string "name", rather than the contents of the variable

Page 14: Lesson 10 -- Interactive  Scripts

Interactive program -- User inputs their age and is told how old they would be in dog years.• A second variable is needed to store the result of the calculation.

The top-down logic for the program:

• Declare a variable to store the age. • Prompt for and store the user's age. • Declare a variable to store the age converted to dog years• Calculate the age in dog years and store it in the second variable • Write the output, retrieving the information stored in the two variables

See source file dogyears.html (Figure 10.7)

Page 15: Lesson 10 -- Interactive  Scripts

How the variables are used. Assume that the age entered by the user is already stored into the age variable.

Page 16: Lesson 10 -- Interactive  Scripts

Interactive program -- User inputs a number and is given the cube of the number.var num;num = prompt("Enter a number to be cubed.","");var numcubed;numcubed = num*num*num;document.write("The cube of your number is <b>");document.write(numcubed);document.write("</b>.");

Sample output (before rendition):The cube of your number is <b>8</b>.

Page 17: Lesson 10 -- Interactive  Scripts

Variable names can only be composed of:• letters (a-z and A-Z)• digits (0-9)• the underscore (_).

• Can't begin with a number.

Examples of legal variable declarations:

var total1;var total2;var grand_total;var dog_age;var dogAge;

Page 18: Lesson 10 -- Interactive  Scripts

Examples of illegal variable declarations:

var grand total; //OOPS!var 1total; //OOPS!var sum&total; //OOPS! var grand-total; //OOPS!

• Would cause an error in program -- won't work at all or not as intended.

• Reserved words can't be used for variable names.

var prompt; //OOPS!

Page 19: Lesson 10 -- Interactive  Scripts

• Variable names ARE case-sensitive. var Total; //two distinctvar total; //storage locations

Page 20: Lesson 10 -- Interactive  Scripts

What can I store into a variable? Any of JavaScript's literal types.

• Examples of string literals.

"hello there""9840 8q08&ag %(&^"" @#$ ""45"

• The last example is no more than a string of two characters.• If you use quotes, the JavaScript interpreter does not view it as a number.

Page 21: Lesson 10 -- Interactive  Scripts

• JavaScript also has a numeric literal type• The literal value is not given in quotes

numeric literal

string literal

• The distinction at first seems mysterious.• JavaScript needs the numerical format in order to perform arithmetic.

Page 22: Lesson 10 -- Interactive  Scripts

JavaScript is loosely typed -- Any of JavaScript's literal types can be stored in a variable.

var num1;var num2;var quotient;

num1 = "6";num2 = "10";quotient= num1/num2;

• The calculation is: "6"/"10"• JavaScript can't do division with strings.• The strings are converted into numbers on the fly.• 6/10• The number .6 is stored into quotient

Page 23: Lesson 10 -- Interactive  Scripts

• But the values stored in the num1 and num2 variables could come from user input.• You never know what you're going to get!

var num1;var num2;var quotient;

num1 = "6";num2 = "hello";quotient= num1/num2;

• The calculation is: "6"/"hello"• Meaningless!• What is the JavaScript interpreter to do?

Page 24: Lesson 10 -- Interactive  Scripts

• Compiled languages like C++ and Java actually guard against that potential problem by requiring variables to be strongly typed.

string x; //only in strongly typed int y; //languages

• These statements declare empty variables which can only contain a string or an integer, respectively.• A type mismatch (like x="45";) would cause a fatal error at compile time.

• Not so in JavaScript which is loosely typed.• There is no compile time -- direct execution of the code by the Web browser.

Page 25: Lesson 10 -- Interactive  Scripts

• JavaScript needs a way to handle type mismatches without causing an error (like crashing the Web browser).• When JavaScript can't reach a numeric answer for a calculation, it uses the special NaN literal value.

quotient = 6/"hello"; document.write("The quotient is ");document.write(quotient);

Result in Web page:

The quotient is NaN

Page 26: Lesson 10 -- Interactive  Scripts

Summary of JavaScript's Literals

Examples:var x; //x contains undefinedx = 6/0; //x contains Infinityx = 6/"the"; //x contains NaN

(Will explore the Boolean literals in Lesson 11.)

Page 27: Lesson 10 -- Interactive  Scripts

Note on number storage: JavaScript chooses the most simple format. num = 2.0; //JavaScript stores 2num = 3.1400; //JavaScript stores 3.14

Note on storing things into variables• If it's not a number, quoted string, special literal value, or the name of a variable, you CAN'T assign it to a variable.

x = hello; //OOPS! bare word (not a variable)x = num; //OK, assigns 3.14 to x since

//num is a variable (from above)

Page 28: Lesson 10 -- Interactive  Scripts

The assignment operator = has nothing to do with equality!

var x;x = 1;x = x + 1;

• The third statement reduces algebraically to 0=1 if the = is interpreted as equality.

• Rather, the right side (x+1) is first evaluated using the current value stored in the variable x.• Then the result is assigned to variable on the left.• The result of all this code is that x contains 2.

Page 29: Lesson 10 -- Interactive  Scripts

Variable assignment in general.

Page 30: Lesson 10 -- Interactive  Scripts

Top-down tracing of variables in a program.

tracing the contents of xvar x; undefinedx = 1; 1x = x + 1; 2document.write(x); contents of x not altered

• Each time x is assigned a new value, its previous contents are replaced with the new value.• Understanding this is crucial.

• Work the variable tracing practice exercises in the review exercises for Lesson 10. The answers are in the back of the book.

Page 31: Lesson 10 -- Interactive  Scripts

• Also critical to remember: variables on the right side of an assignment are not altered.

sum = num1+num2+num3;

• Only the sum variable is changed.

• Only one variable may appear on the left side of an assignment.

x+y = z; //OOPS! syntax violation

Page 32: Lesson 10 -- Interactive  Scripts

More elaborate tracing example:

var a,b,c; //can declare multiple variables //with one statement

Page 33: Lesson 10 -- Interactive  Scripts

Final notes on variable assignment:• Can declare and initialize the variable in one statement.var x = 3.14;var y = prompt("Enter your name.","");

• Don't re-declare the same variable twice.var name = "Raul"; //declaration and

//initialization

name = "Egbert"; //assignment

• That is, don't do this.var name = "Raul"; //declaration and

//initialization

var name = "Egbert"; //OOPS!

Page 34: Lesson 10 -- Interactive  Scripts

String Concatenation:

Merriam-Webster Dictionary: to concatenate -- "to link together in a series or chain."

Equivalent using 3 strings:

var dog = "Scooby"+" "+"Doo";

Page 35: Lesson 10 -- Interactive  Scripts

• Strings stored in variables can be concatenated.var first = "Scooby";var last = "Doo";var dog = first+" "+last;

• This offers a handy alternative to using multiple document.write statements to generate output.

document.write("You may be "+age+" years old but, if you were a dog, you would be "+dogage+" years old!");

• Remember: do not hit return on the keyboard in the middle of a string. Let the statement soft wrap.

Page 36: Lesson 10 -- Interactive  Scripts

Recall: JavaScript will parse string data into numerical format on the fly in order to perform calculations.

var procuct = "5"*"6"; //parsed into 5*6

Dilema: the + operator is used for both addition and string concatenation.

var procuct = "5"+"6"; //what to do?

The JavaScript interpreter will choose concatenation over addition.Result: product will contain "56"

Page 37: Lesson 10 -- Interactive  Scripts

Why is that a big deal?

• ALL user input is stored as a string of characters.• Keyboard characters are typed, and the browser simply stores a string of characters.• It does not care whether the characters are inherently form a number.• This will also be true when we obtain user input using HTML forms.

• This can foul up arithmetic calculations which make use if user inputted data!

Page 38: Lesson 10 -- Interactive  Scripts

Example: A program which prompts the user for two numbers, and then outputs their average.

var num1 = prompt("Enter the first number.","");var num2 = prompt("Enter the second number.","");var avg = (num1 + num2)/2;document.write("The average of "+num1+" and "+num2+" is "+avg);

See source file averagebad.html.

Page 39: Lesson 10 -- Interactive  Scripts

• Here is how the calculation unfolds.var avg = (num1 + num2)/2;• Suppose the user has already entered the two numbers and they are stored in num1 and num2.

retrieve contents of num1 and num2("50"+"100")/2concatenate the strings("50100")/2convert string to number on the fly50100/2assign the result to ageage = 25050;

Page 40: Lesson 10 -- Interactive  Scripts

The solution:• Parse all user input which is to be used in calculations into numerical format using the parseFloat function.

x = parseFloat(x);

• Parses a string into numerical format.

var num = "3.14";num = parseFloat(num);

• The second statement assigns 3.14 to num• The word float refers to floating point decimal

Page 41: Lesson 10 -- Interactive  Scripts

The top down logic for the version of the averaging program which actually works.

• prompt for first number, store into num1 • parse num1 into numeric format • prompt for first number, store into num2• parse num1 into numeric format• calculate the average, store into avg • write output to document

See source file average.html

Page 42: Lesson 10 -- Interactive  Scripts

• There is almost always more than one way to write a program.• The following top-down logic accomplishes the same thing as that used in the average program.

• prompt for first number, store into num1• prompt for first number, store into num2• parse num1 into numeric format • parse num1 into numeric format• calculate the average, store into avg • write output to document

Page 43: Lesson 10 -- Interactive  Scripts

Understanding JavaScript statements.• Terminate with a semi-colon:

var avg=(num1+num2)/2 // OOPS!, no ;document.write("The average of "+num1+" and "+num2+" is "+avg+".");

• Since the JavaScript interpreter can't determine when the first statement ends, it gets confused and won't even execute the second one.

Page 44: Lesson 10 -- Interactive  Scripts

• A terminating semi-colon is all the JavaScript interpreter needs to know when to terminate a statement.

var avg=(num1+num2)/2;document.write("The average of "+num1+" and "+num2+" is "+avg+".");

• However, humans need to put statements on separate lines in the text file in order easily to be able to read a program.

Page 45: Lesson 10 -- Interactive  Scripts

• If a JavaScript statement makes sense to the JavaScript interpreter, it will also make sense to a human when spoken in English.var x; (Set up an empty variable named x.) x=55; (Put the number 55 into x.)x=x+5; (Evaluate x+5 and put the result into x.)

• These are not viable JavaScript statements.x; // OOPS!x+5; // OOPS!• Suppose x contains the number 5. Then these statements simply look like the following to the JavaScript interpreter.5;10;

Page 46: Lesson 10 -- Interactive  Scripts