1 / 46

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>.

Download Presentation

Lesson 10 -- Interactive Scripts

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 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>

  2. 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

  3. See source file hello.html (Figure 10.1).

  4. 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!

  5. <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?

  6. 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.

  7. 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>

  8. 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>

  9. Comments are completely ignored by the JavaScript interpreter -- only for human benefit. // single-line comment /* A comment which spills over multiple lines */

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

  11. 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.

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

  13. 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

  14. 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)

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

  16. 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>.

  17. 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;

  18. 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!

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

  20. 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.

  21. 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.

  22. 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

  23. 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?

  24. 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.

  25. 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

  26. 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.)

  27. 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)

  28. 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.

  29. Variable assignment in general.

  30. 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.

  31. 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

  32. More elaborate tracing example: var a,b,c; //can declare multiple variables //with one statement

  33. 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!

  34. String Concatenation: Merriam-Webster Dictionary: to concatenate -- "to link together in a series or chain." Equivalent using 3 strings: var dog = "Scooby"+" "+"Doo";

  35. 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.

  36. 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"

  37. 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!

  38. 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.

  39. 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;

  40. 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

  41. 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

  42. 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

  43. 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.

  44. 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.

  45. 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;

More Related