View
216
Download
3
Category
Preview:
Citation preview
How to code a JavaScript application
Objectives
Applied
Using a text editor like Notepad++ or TextWrangler, enter and edit
XHTML, CSS, and JavaScript files.
Using Firefox as your web browser, display any error messages in
the Error Console when you test a JavaScript application.
Given the specifications for a JavaScript application that requires
only the skills and language elements presented in this chapter,
code, test, and debug the application.
Objectives (continued)
Knowledge
Describe the use of the two types of JavaScript comments.
Describe the type of error that can occur if you split a JavaScript
statement in the wrong place.
List the primary rules for creating a JavaScript identifier.
Describe the three primitive data types used in JavaScript.
Describe the use of the \n escape sequence in a string literal.
Describe the rules for evaluating an arithmetic expression,
including order of precedence and the use of parentheses.
Describe the use of variable declarations and assignment
statements.
Describe the use of objects, properties, methods, and object
chaining.
Objectives (continued)
Describe the ways that number, string, Boolean, and Date objects
are created.
Given the name of a common method for a window, document,
Number, String, Boolean, or Textbox object, describe the function
of the method.
Describe the rules for evaluating a conditional expression,
including the use of the isNan function, the order of precedence for
logical operators, and the use of parentheses.
Describe the flow of control for an if, while, or for statement.
Describe the creation and use of functions.
Describe the creation and use of event handlers for the click event
of a button element and the load event of the window object.
Notepad++ with an auto-completion list
Basic skills for using Notepad++
How to open, save, close, and start files
How to change the style for comments
How to use the auto-completion feature
How to let Notepad++ know which language you’re working with
Note
These skills are presented in figure 2-1.
The Sales Tax application in the Firefox browser
How to test a web page
Open the web page in your browser.
Enter the required input data, and run the application.
How to retest a web page
after you change the source code
To reload the edited file for the page, click the Reload or Refresh
button.
If the Reload or Refresh button
doesn’t clear browser memory…
you may need to close the browser window and reopen the
application.
If the application doesn’t do anything when you
test it…
it either has syntax errors or other types of coding errors.
The Firefox Error Console with an error displayed
How to display the Firefox Error Console
Use the ToolsError Console command or press Ctrl+Shift+J.
How to display the source code
Click on the link in the Error Console.
The source code that’s displayed
when you click on the link
How to load JavaScript from an external file <script type="text/javascript" src="sales_tax.js"></script>
How to embed JavaScript
in the head of an XHTML document <head>
...
<script type="text/javascript">
var $ =
function (id) { return document.getElementById(id); }
</script>
...
</head>
How to embed JavaScript
in the body of an HTML document <p>©
<script type="text/javascript">
var today = new Date();
document.writeln( today.getFullYear() ); </script>
Mike's Bait and Tackle Shop</p>
How to load a script from a different web server <script type="text/javascript"
src="http://www.google-analytics.com/urchin.js">
</script>
How to use the noscript tag
in the body of an XHTML document <script type="text/javascript">
var today = new Date();
document.writeln( today.getFullYear() );
</script>
<noscript>2009</noscript>
The basic syntax rules for JavaScript
JavaScript is case-sensitive.
JavaScript statements end with a semicolon.
JavaScript ignores extra whitespace in statements.
Single-line comments begin with two forward slashes.
Multi-line comments begin with /* and end with */.
A single-line comment nextYear = thisYear + 1; // Add 1 to this year
A multi-line comment /* The following line determines what the
next year is by adding 1 to the current year
*/
nextYear = thisYear + 1;
How to split a statement across multiple lines
Split a statement after an arithmetic or relational operator such as:
+, -, *, /, =, ==, >, or <.
Split a statement after an opening brace ( { ), bracket ( [ ), or
parenthesis.
Split a statement after a closing brace ( } ).
Do not split a statement after an identifier, a value, or the return
keyword.
Do not split a statement after a closing bracket ( ] ) or parenthesis.
A split statement that results in an error return
"Hello";
A split statement that works correctly nextYear =
thisYear + 1;
Rules for creating identifiers in JavaScript
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.
Avoid using names that are similar to reserved words, global
properties, or global methods.
Valid identifiers in JavaScript subtotal
index_1
$
taxRate
calculate_click
$log
Examples of number values 15 // an integer
-21 // a negative integer
21.5 // a floating-point value
-124.82 // a negative floating-point value
-3.7e-9 // a floating-point value
// equivalent to -0.0000000037
The primitive data types
Number
String
Boolean
Terms
integer
floating-point value
exponent
empty string
escape sequence
Boolean value
Examples of string values "JavaScript" // a string with double quotes
'String Data' // a string with single quotes
"" // an empty string
How the \n escape sequence can be used
to start a new line in a string "A valid variable name\ncannot start with a number."
// represents the string: A valid variable name
// cannot start with a number.
The two Boolean values true // equivalent to true, yes, or on
false // equivalent to false, no, or off
Common arithmetic operators +
-
*
/
%
++
--
The order of precedence
for arithmetic expressions
Order Operators
1 ++
2 --
3 * / %
4 + -
Precedence and the use of parentheses 3 + 4 * 5 // Result is 23
(3 + 4) * 5 // Result is 35
13 % 4 + 9 // Result is 10
13 % (4 + 9) // Result is 0
Terms
arithmetic expression
arithmetic operator
order of precedence
concatenate
concatenation operator
How to declare variables
without assigning values to them var subtotal;
// declares a variable named subtotal
var lastName, state, zipCode;
// declares three variables
The assignment operators =
+=
-=
*=
/=
%=
How to declare variables and assign values var subtotal = 74.95; // subtotal is 74.95
var salesTax = subtotal * .1; // salesTax is 7.495
var isValid = false; // Boolean value is false
var zipCode = "93711", state = "CA"; // two assignments
var firstName = "Ray", lastName = "Harris";
var fullName = lastName + ", " + firstName;
// fullName is "Harris, Ray"
How to code compound assignment statements var subtotal = 24.50;
subtotal += 75.50; // subtotal is 100
subtotal *= .9; // subtotal is 90 (100 * .9)
var firstName = "Ray", lastName = "Harris";
var fullName = lastName; // fullName is "Harris"
fullName += ", "; // fullName is "Harris, "
fullName += firstName; // fullName is "Harris, Ray"
var months = 120, message = "Months: ";
message += months; // message is "Months: 120"
Terms
variable
declare a variable
assignment statement
assignment operator
string literal
numeric literal
The syntax for creating a new object new ObjectType()
Examples that create new objects var today = new Date(); // creates a Date object
var states = new Array(); // creates an Array object
The syntax for accessing a property of an object objectName.propertyName
Examples that access a property of an object alert(window.screenX);
// Displays the width of the user's screen
window.location = "http://www.murach.com";
// Loads the murach.com home page
The syntax for calling a method of an object objectName.methodName(parameters)
Examples that call a method of an object // Stores a reference to the XHTML element
// with the id "rate"
var rateTextbox = document.getElementById("rate");
// Gets the full year and writes it to the web page
document.writeln( today.getFullYear() );
Examples of object chaining // Uses the alert method to display the value property
// of the DOM object that is returned
// by the getElementById method.
alert( document.getElementById("rate").value );
// Uses the alert method to display the location property
// of the current page
// after it has been converted to lowercase letters
// by the toLowerCase method.
alert( window.location.toLowerCase() );
Terms
object
property
method
call a method
parameter (or argument)
object chaining
One property of the window object location
Common methods of the window object alert(message)
prompt(message,default)
parseInt(string)
parseFloat(string)
Examples that use these properties and methods alert("Invalid entry."); // displays "Invalid entry."
var userEntry = prompt(errorMessage,100);
// accepts user entry
parseInt("12345.67"); // returns the integer 12345
parseFloat("12345.67"); // returns the floating point
// value 12345.67
parseFloat("Ray Harris"); // returns NaN
Common methods of the document object getElementById(id)
write(text)
writeln(text)
Examples that use these methods // gets the DOM object that represents
// the XHTML element with "rate" as its id
// and stores it in a variable named rateTextbox
var rateTextbox = document.getElementById("rate");
// writes the string in the message variable to the
document
document.writeln(message);
Notes on using the window and document objects
The window object is the global object when JavaScript is used in a
web browser.
JavaScript lets you omit the object name and period when referring
to the window object.
The document object is the object that allows you to work with the
DOM.
One method of the Number object toFixed(digits)
Examples var balance = 2384.55678;
// creates a number object named balance
alert ( balance.toFixed(2) );
// displays 2384.56
// balance is still 2384.55678
balance = parseFloat( balance.toFixed(2) );
// balance is now 2384.56
Methods of the String object substr(start,length)
toLowerCase()
toUpperCase()
Examples var guest = "Ray Harris";
// creates a string object named guest
alert ( guest.toUpperCase() ); // displays "RAY HARRIS"
alert ( guest.substr(0,3) ); // displays "Ray"
guest = guest.substr(4,6); // guest is now "Harris"
Methods of the Date object toDateString()
getMonth()
getDate()
getFullYear()
Examples var today = new Date();
// creates a Date object named today
// assume the current date is 09/20/2008
alert ( today.toDateString() );
// displays Sat Sep 20 2008
alert ( today.getFullYear() ); // displays 2008
alert ( today.getMonth() );
// displays 8, not 9, for September
Common properties of the Textbox object value
disabled
Two XHTML <input> tags that create text boxes <input type="text" id="rate" />
<input type="text" id="salesTax" disabled="disabled" />
How to get the text box value in two statements // Store a reference to the text box
var rateTextbox = document.getElementById("rate");
// Get the value and convert it to a number
var rate = parseFloat( rateTextbox.value );
How to get the value with with object chaining var rate =
parseFloat(document.getElementById("rate").value);
How to enable a text box document.getElementById("salesTax").disabled = false;
How to display a value in a text box // Assign an empty string to a text box
document.getElementById("salesTax").value = "";
// Assign the value of a variable named salesTax
// to a text box
document.getElementById("salesTax").value =
salesTax.toFixed(2);
One method of the Textbox object focus()
How to move the cursor to a text box document.getElementById("investment").focus();
The relational operators ==
!=
<
<=
>
>=
The syntax of the global isNaN method isNaN(expression)
Examples of the isNaN method isNaN("Harris")
// Returns true since "Harris" is not a number
isNaN("123.45")
// Returns false since "123.45"
// can be converted to a number
The logical operators in order of precedence
Operator Description
! NOT
&& AND
|| OR
How the logical operators work
Both tests with the AND operator must be true for the overall test
to be true.
At least one test with the OR operator must be true for the overall
test to be true.
The NOT operator switches the result of the expression to the
other Boolean value.
Terms to know
conditional expression
relational operator
compound conditional expression
logical operator
One common programming error
Confusing the assignment operator ( = )
with the equality operator ( ==).
An if statement with an else clause if ( age >= 18 ) {
alert ("You may vote.");
} else {
alert ("You are not old enough to vote.");
}
An if statement with else if and else clauses 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 {
alert ("The rate is: " + rate + ".");
}
An if statement
with a compound conditional expression if ( isNaN(userEntry) || userEntry <= 0 ) {
alert ("Please enter a valid number > zero.");
}
An if statement that tests a Boolean value if ( invalidFlag ) {
alert ("All entries must be numeric values > 0.");
}
A nested if statement if ( isNaN(totalMonths) || totalMonths <= 0 ) {
alert ("Please enter a number of months > zero.");
} else {
var years = parseInt ( totalMonths / 12 );
var months = totalMonths % 12;
if ( years == 0 ) {
alert ( "The investment time is "
+ months + " months.");
} else if ( months == 0 ) {
alert ( "The investment time is "
+ years + " years.");
} else {
var message = "The investment time is "
+ years + " years ";
message += "and " + months + " months.";
alert(message);
}
}
A while loop that adds 1 through 5 var sumOfNumbers = 0;
var loops = 5;
var counter = 1;
while (counter <= loops) {
sumOfNumbers += counter;
counter++;
}
alert(sumOfNumbers); // displays 15
A for loop that adds 1 through 5 var sumOfNumbers = 0;
var loops = 5;
for (var counter = 1; counter <= loops; counter++) {
sumOfNumbers += counter;
}
alert(sumOfNumbers); // displays 15
A while loop that gets a user entry userEntry = prompt("Please enter a number:", 100);
while ( isNaN( userEntry ) ) {
alert( "You did not enter a number.");
userEntry = prompt("Please enter a number:", 100);
}
A for loop that calculates the future value
of a monthly investment var monthlyInvestment = 100; // investment is $100
var monthlyRate = .01; // interest rate is 12%
var months = 120; // 120 months is 10 years
var futureValue = 0; // futureValue starts at 0
for ( i = 1; i <= months; i++ ) {
futureValue = ( futureValue + monthlyInvestment ) *
(1 + monthlyRate);
}
A function with no parameters var showYear = function () {
var today = new Date();
alert( today.getFullYear() );
}
How to call a function that doesn’t return a value showYear(); // displays the current year
A function with one parameter that returns a value var $ = function ( id ) {
return document.getElementById( id );
}
How to call a function that returns a value var taxRate = $("taxRate");
A function with two parameters
that doesn’t return a value var displayEmail = function ( username, domain ) {
document.write( username + "@" + domain);
}
How to call a function with two parameters
that doesn’t return a value displayEmail( "mike", "murach.com");
A function with two parameters
that returns a value var calculateTax = function ( subtotal, taxRate ) {
var tax = subtotal * taxRate;
tax = parseFloat( tax.toFixed(2) );
return tax;
}
How to call a function with two parameters
that returns a value var subtotal = 74.95;
var taxRate = 0.07;
var salesTax = calculateTax( subtotal, taxRate );
// returns 5.25
Terms to know
function
return statement
call a function
return undefined
Common events
Object Event
button onclick
window onload
An application with an onclick event handler <head>
<script type="text/javascript">
// This function receives an id and returns an XHTML
object.
var $ = function ( id ) {
return document.getElementById( id );
}
// This is the onclick event handler named display_click.
var display_click = function () {
alert( "You clicked the button.");
}
// This is the onload event handler that assigns the
// display_click handler to the click event of the button.
window.onload = function () {
$("btnDisplay").onclick = display_click;
}
</script>
</head>
<body>
<p><input type="button" value="Display Message"
id="btnDisplay" /></p>
The web browser
after the Display Message button is clicked
The Future Value application in a web browser
The XHTML for the Future Value application <head>
<title>Future Value Calculator</title>
<link rel="stylesheet" type="text/css"
href="future_value.css" />
<script type="text/javascript"
src="future_value.js"></script>
</head>
The XHTML (continued) <body>
<h1>Future Value Calculator</h1>
<p>Enter the values below and click "Calculate".</p>
<label for="investment">Monthly Investment:</label>
<input type="text" id="investment" /><br />
<label for="rate">Annual Interest Rate:</label>
<input type="text" id="rate" />%<br />
<label for="years">Number of Years:</label>
<input type="text" id="years" /><br />
<label for="futureValue">Future Value:</label>
<input type="text" id="futureValue"
disabled="disabled" /><br />
<label> </label>
<input type="button" id="calculate"
value="Calculate" /><br />
</body>
The JavaScript for the Future Value application var $ = function (id) {
return document.getElementById(id);
}
window.onload = function () {
$("calculate").onclick = calculate_click;
$("investment").focus();
}
The JavaScript (continued) var calculate_click = function () {
// Get the user entries from the first three text boxes.
var investment = parseFloat( $("investment").value );
var annualRate = parseFloat( $("rate").value );
var years = parseInt( $("years").value );
// Set the value of the fourth text box.
$("futureValue").value = "";
// Test the three input values for validity.
if (isNaN(investment) || investment <= 0) {
alert("Investment must be a valid number\nand
greater than zero.");
} else if(isNaN(annualRate) || annualRate <= 0) {
alert("Annual rate must be a valid number\nand
greater than zero.");
} else if(isNaN(years) || years <= 0) {
alert("Years must be a valid number\nand
greater than zero.");
The JavaScript (continued) // If all input values are valid, calculate future value.
} else {
var monthlyRate = annualRate / 12 / 100;
var months = years * 12;
var futureValue = 0;
for ( i = 1; i <= months; i++ ) {
futureValue = ( futureValue + investment ) *
(1 + monthlyRate);
}
// Set the value of the fourth text box to the future value
$("futureValue").value = futureValue.toFixed(2);
}
}
Recommended