460 likes | 545 Views
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>.
E N D
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>
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 delimitedwith quotes. • " xYz " -- 5 character string, including spaces • Dog -- How many characters? • -- Not well defined as a string
See source file hello.html (Figure 10.1).
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!
<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?
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.
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>
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>
Comments are completely ignored by the JavaScript interpreter -- only for human benefit. // single-line comment /* A comment which spills over multiple lines */
Prompting for user input. See source file prompt.html.
Problem: • User input from prompt not stored in memory • Goes into obliveon. • Solution: • Store user input into a variable • var 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.
A three-line script: • Declare and empty variable • Store the input into the variable • Write the contents of the variable to the HTML document.
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
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)
How the variables are used. Assume that the age entered by the user is already stored into the age variable.
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>.
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;
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!
Variable names ARE case-sensitive. • var Total; //two distinct • var total;//storage locations
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.
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.
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
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?
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.
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
Summary of JavaScript's Literals Examples: var x; //x contains undefined x = 6/0; //x contains Infinity x = 6/"the"; //x contains NaN (Will explore the Boolean literals in Lesson 11.)
Note on number storage: JavaScript chooses the most simple format. • num = 2.0; //JavaScript stores 2 • num = 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)
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.
Top-down tracing of variables in a program. tracing the contents of x var x; undefined x = 1; 1 x = x + 1; 2 document.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.
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
More elaborate tracing example: var a,b,c; //can declare multiple variables //with one statement
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. • varname = "Raul"; //declaration and • //initialization • name = "Egbert"; //assignment • That is, don't do this. • varname = "Raul"; //declaration and • //initialization • var name = "Egbert"; //OOPS!
String Concatenation: Merriam-Webster Dictionary: to concatenate -- "to link together in a series or chain." Equivalent using 3 strings: var dog = "Scooby"+" "+"Doo";
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.
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"
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!
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.
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")/2 • concatenate the strings • ("50100")/2 • convert string to number on the fly • 50100/2 • assign the result to age • age = 25050;
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
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
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
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.
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.
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;