1 / 35

CSC 3084: Web Development and Programming

CSC 3084: Web Development and Programming. Chapter 2: Getting Started with JavaScript. Chapter Overview. By the end of this chapter, you should be able to : Include JavaScript in the head of an HTML document .

javen
Download Presentation

CSC 3084: Web Development and Programming

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. CSC 3084:Web Development and Programming Chapter 2: Getting Started with JavaScript

  2. Chapter Overview • By the end of this chapter, you should be able to: • Include JavaScript in the head of an HTML document. • Recognize the JavaScript syntax for identifiers, comments, methods calls, conditional expressions • Describe the prompt and alert methods. • Describe the three primitive data types used in JavaScript. • Write basic mathematical and logical expressions in JS. • Declare variables and assign them values. • Describe the parseInt and parseFloatmethods. • Describe the syntax for if, while and for statements.

  3. Loading an External JavaScript File <script src="calculate_mpg.js"></script>

  4. Embedded JavaScript <head> ... <script> alert("The Calculate MPG application"); var miles = prompt("Enter miles driven"); miles = parseFloat(miles); var gallons = prompt("Enter gallons of gas used"); gallons = parseFloat(gallons); var mpg = miles/gallons; mpg = parseInt(mpg); alert("Miles per gallon = " + mpg); </script> </head>

  5. JavaScript in the Body of a Web Page <p> <script> var today = new Date(); document.write("Current date: "); document.write(today.toDateString()); </script> </p> <p>&copy;&nbsp; <script> var today = new Date(); document.write( today.getFullYear() ); </script> , San Joaquin Valley Town Hall </p>

  6. JavaScript in the Body of a Web Page <p> <script> var today = new Date(); document.write("Current date: "); document.write(today.toDateString()); </script> </p> <p>&copy;&nbsp; <script> var today = new Date(); document.write( today.getFullYear() ); </script> , San Joaquin Valley Town Hall </p>

  7. The noscript Element • A noscript element in the body of the HTML: <p>&copy;&nbsp; <script> var today = new Date(); document.write( today.getFullYear() ); </script> <noscript>2012</noscript> , San Joaquin Valley Town Hall </p>

  8. The noscript Element • A noscript element at the start of the HTML: <h2> <noscript> To get the most from this web site, please enable JavaScript. </noscript> </h2>

  9. Basic Syntax Rules for JavaScript • JavaScript is case-sensitive. • JavaScript ignores extra whitespace within statements. • Each JavaScript statement ends with a semicolon. • Split a statement after: • an arithmetic or relational operator • an opening brace, bracket, or parenthesis • a closing brace • Do not split a statement after: • an identifier, a value, or the returnkeyword • a closing bracket or parenthesis

  10. Terms You Should Already Know • statement • whitespace • identifier • camel casing • comment • comment out (i.e., disable code by wrapping it with a comment)

  11. Rules for Creating Identifiers • Identifiers can only contain letters, numbers, the underscore, and the dollar sign. • Identifiers can’t start with a number. • Identifiers are case-sensitive. • Identifiers can be any length. • Identifiers can’t be the same as reserved words. • Avoid using global properties and methods as identifiers. (We’ll learn about these later on.)

  12. Valid identifiers in JavaScript subtotal index_1 $ taxRate calculate_click $log

  13. Camel Casing Versus Underscore Notation taxRatetax_rate calculateClickcalculate_click emailAddressemail_address firstNamefirst_name futureValuefuture_value • Use whichever style you want, but be consistent • Your book uses camel notation for JavaScript identifiers and underscore notation for HTML elements • Pick meaningful identifier names and don’t use cryptic abbreviations

  14. JavaScript Comments • Block comments begin with /* and end with */. • Single-line comments begin with two forward slashes and continue to the end of the line. • HTML comments are written like this:<!-- This is a comment --> • CSS comments are written using the /* */ notation.

  15. The window Object • The window object is a data structure available in all JavaScript applications • It has methods like alert, prompt and print • The methods can be called through the window object (i.e., window.alert()) or without the object (i.e., alert()) because it is a global object

  16. Common Methods of the window Object • alert(string) Displays a dialog box that contains the string argument. • prompt(string, Displays a dialog box containingdefault) the first string argument and the default value as a suggested response to the prompt. • print()Issues a print request to the browser, which displays a message in a box.

  17. Examples of window Methods window.alert("This is a test of the alert method"); varuserEntry= prompt("This is a test of the prompt method", 100);

  18. The location Property • The location property of the window object provides the URL of the current web page • alert(window.location);

  19. Terms Related to Objects You Should Now Know • object • method • call a method • window object • global object • dot operator

  20. Data Types: number, string and Boolean • Examples of number values: 15, -21, 21.5, -124.82, -3.7e-9 • Examples of string values: "JavaScript“, 'String Data‘, "" • The two Boolean values: true, false • If a result is stored in a number data type that is larger or smaller than the data type can store, it will be stored as the value Infinity or –Infinity, respectively

  21. Common Arithmetic Operators Operator Example Result + 5 + 7 12 - 5 - 12 -7 * 6 * 7 42 / 13 / 4 3.25 % 13 % 4 1 ++counter++ adds 1 to counter --counter-- subtracts 1 from counter • All numbers are stored as floats, so there is no integer division in JavaScript • / and % perform floating-point division

  22. Declaring and Using Variables • var subtotal; • var investment, interestRate, years; • var subtotal = 74.00; • varsalesTax = subtotal * .1; • JavaScript also has the compound assignment operators like +=, *=, etc. • += performs addition if the variable stores a number, and performs concatenation if the variable is a string

  23. More on Strings and Booleans • Escape sequences: \n \” \’ • + can be used for concatenation • varfirstName = "Ray", lastName = "Harris"; • varfullName = lastName + ", " + firstName; • If a string and a number are combined with +, the number is converted to a string and concatenation is performed • Boolean variable: varisValid = false;

  24. Methods of the window Object for Converting String Values • parseInt(string)Converts the string argument into an integer. • parseFloat(string)Converts the string argument into a float. • If the conversion process in either case is not successful, the method returns NaN (Not a Number) • You can check if a value is NaN using the isNan(x) method var age = prompt(“Enter your age:”) age = parseInt(age); var age = parseInt(prompt(“Enter your age:”));

  25. The Relational Operators Operator Description Example == EquallastName== "Harris"testScore== 10 != Not equal firstName!= "Ray"months != 0 < Less than age < 18 <= Less than or equal investment <= 0 > Greater than testScore> 100 >= Greater than or equal rate / 100 >= 0.1

  26. The Logical Operators in Order of Precedence Operator Description Example ! NOT!isNaN(age) && ANDage > 17 && score < 70 || ORisNaN(rate) || rate < 0

  27. If-statements if ( isNaN(userEntry) || userEntry <= 0 ) { alert ("Please enter a valid number > zero."); } if ( isNaN(rate) ) { alert ("You did not provide a number for the rate."); } else if ( rate < 0 ) { alert ("The rate may not be less than zero."); } else if ( rate > 12 ) { alert ("The rate may not be greater than 12."); } else { alert ("The rate is: " + rate + "."); }

  28. While-loop Example varsumOfNumbers = 0; varnumberOfLoops = 5; var counter = 1; while (counter <= numberOfLoops) { sumOfNumbers += counter; counter++; } alert(sumOfNumbers);

  29. While-loop Example var total = 0, count = 0, number; number = parseFloat( prompt("Enter a number:") ); while ( !isNaN(number) ) { total += number; count++; number = parseFloat( prompt("Enter another number " + "or click Cancel to stop:") ); } var average = total / count; alert("The average is: " + average);

  30. Do-loop Example varsumOfNumbers = 0; varnumberOfLoops = 5; var counter = 1; do { sumOfNumbers += counter; counter++; } while (counter <= numberOfLoops); alert(sumOfNumbers);

  31. For-loop Example varsumOfNumbers = 0; varnumberOfLoops = 5; for (var counter=1; counter <= numberOfLoops; counter++ ) { sumOfNumbers += counter; } alert(sumOfNumbers);

  32. For-loop Example varinvestment = 10000; varannualRate = 7.0; var years = 10; varfutureValue = investment; for (vari = 1; i <= years; i++) { futureValue += futureValue * annualRate / 100; } alert (futureValue);

  33. MPG Calculator • See JS Textbook Files\book_apps\ch02\mpg.html

  34. Test Average Calculator • See JS Textbook Files\book_apps\ch02\test_scores.html

  35. Error Console • Debugging JavaScript needs to be done through the browser, so the browser’s error console is a helpful tool • In Firefox, hit F12 to open Firebug (or Ctrl+Shift+J to open the built-in console) • In Chrome, hit Ctrl+Shift+I

More Related