Chapter 3 Slideshow - Web Development at LCSC

advertisement
Chapter 3
How to work with
objects, functions,
and events
Murach's JavaScript and jQuery, C3
© 2012, Mike Murach & Associates, Inc.
Slide 1
Objectives
Applied
1. Given the specifications for a JavaScript application that requires
only the skills presented in chapters 2 and 3, code, test, and debug
the application.
Knowledge
1. Describe the way Number, String, and Date objects are created.
2. Given the name of one of the methods or properties that are
presented in this chapter for window, document, Textbox,
Number, Date, and String objects, describe the use of the method
or property.
3. Describe the use of the Document Object Model in JavaScript
applications.
Murach's JavaScript and jQuery, C3
© 2012, Mike Murach & Associates, Inc.
Slide 2
Objectives (continued)
4. Describe the use of the JavaScript firstChild and nodeValue
properties for working with the DOM.
5. Describe the creation and use of both anonymous and named
functions.
6. Distinguish between local and global variables.
7. Describe the creation and use of event handlers, including an event
handler for the load event of the window object.
Murach's JavaScript and jQuery, C3
© 2012, Mike Murach & Associates, Inc.
Slide 3
Methods of the window object
A method that confirms an action
confirm(string)
Two methods for working with numbers
parseInt(string)
parseFloat(string)
Examples
confirm("Are you sure you want to delete it?");
var entryA =
prompt("Enter any value", 12345.6789);
entryA = parseInt(entryA);
// entryA = 12345
var entryB =
prompt("Enter any value", 12345.6789);
entryB = parseFloat(entryB);
// entryB = 12345.6789
Murach's JavaScript and jQuery, C3
© 2012, Mike Murach & Associates, Inc.
Slide 4
Three methods of the document object
getElementById(id)
write(string)
writeln(string)
Examples
// returns the object for the HTML element
var rateBox = document.getElementById("rate");
// writes a line into the document
document.writeln("Today is " + today.toDateString());
Murach's JavaScript and jQuery, C3
© 2012, Mike Murach & Associates, Inc.
Slide 5
Members of the Textbox object
One method
focus()
Two properties
value
disabled
Murach's JavaScript and jQuery, C3
© 2012, Mike Murach & Associates, Inc.
Slide 6
One method of the Number object
toFixed(digits)
Murach's JavaScript and jQuery, C3
© 2012, Mike Murach & Associates, Inc.
Slide 7
How to get a string value from a text box
HTML tags that define two text boxes
<input type="text" id="first_name">
<input type="text" id="sales_amount">
JavaScript without chaining
var firstName = document.getElementById("first_name");
firstName = firstName.value;
JavaScript with chaining
var firstName =
document.getElementById("first_name").value;
Murach's JavaScript and jQuery, C3
© 2012, Mike Murach & Associates, Inc.
Slide 8
How to get a number value from a text box
Without chaining
var salesAmount = document.getElementById("sales_amount");
salesAmount = salesAmount.value;
salesAmount = parseFloat(salesAmount);
With chaining
var salesAmount =
parseFloat(document.getElementById("sales_amount").value);
Murach's JavaScript and jQuery, C3
© 2012, Mike Murach & Associates, Inc.
Slide 9
Other examples of chaining
var salesAmount =
parseFloat(document.getElementById(
"sales_amount").value).toFixed(2);
document.getElementById("first_name").value = "";
document.getElementById("first_name").focus();
Murach's JavaScript and jQuery, C3
© 2012, Mike Murach & Associates, Inc.
Slide 10
Terms
 window object
 global object
 document object
 Document Object Model (DOM)
 NaN
 chaining
Murach's JavaScript and jQuery, C3
© 2012, Mike Murach & Associates, Inc.
Slide 11
How to create a JavaScript object
The syntax for creating an object
new ObjectType();
A statement that creates a Date object
var today = new Date();
Murach's JavaScript and jQuery, C3
© 2012, Mike Murach & Associates, Inc.
Slide 12
A few methods of a Date object
toDateString()
getFullYear()
getDate()
getMonth()
Examples that use a Date object
var today = new Date();
alert ( today.toDateString() );
alert ( today.getFullYear() );
alert ( today.getDate() );
alert ( today.getMonth() );
Murach's JavaScript and jQuery, C3
© 2012, Mike Murach & Associates, Inc.
Slide 13
Properties and methods of a String object
One property
length
Four of the many methods
indexOf(search,position)
substr(start,length)
toLowerCase()
toUpperCase()
Examples that use a String object
var
var
var
var
var
name = "Ray Harris";
nameUpper = name.toUpperCase();
nameLength = name.length;
// nameLength = 10
index = name.indexOf(" "); // index = 3
firstName = name.substr(0, index);
Murach's JavaScript and jQuery, C3
© 2012, Mike Murach & Associates, Inc.
Slide 14
The code for a web page
<!DOCTYPE html>
<html>
<head>
<title>Join Email List</title>
</head>
<body>
<h1>Please join our email list</h1>
<form id="email_form" name="email_form"
action="join.html" method="get">
<label for="email_address">Email Address:</label>
<input type="text" id="email_address">
<span id="email_address_error">*</span><br>
<label> </label>
<input type="button" id="join_list"
value="Join our List">
</form>
</body>
</html>
Murach's JavaScript and jQuery, C3
© 2012, Mike Murach & Associates, Inc.
Slide 15
The DOM for the web page
html
head
body
title
h1
text
text
form
label
input
text
Murach's JavaScript and jQuery, C3
© 2012, Mike Murach & Associates, Inc.
span
label
text
text
input
Slide 16
The syntax for changing a text node
elementObject.firstChild.nodeValue =
"The text for the element";
An example that puts a message
in the span element
document.getElementById(
"email_address_error").firstChild.nodeValue =
"This entry is required";
Murach's JavaScript and jQuery, C3
© 2012, Mike Murach & Associates, Inc.
Slide 17
The syntax for an anonymous function
var variableName = function(parameters) {
// statements that run when the function is executed
}
An anonymous function with no parameters
that doesn’t return a value
var showYear = function() {
var today = new Date();
alert( "The year is " + today.getFullYear() );
}
How to call the function
showYear();
Murach's JavaScript and jQuery, C3
© 2012, Mike Murach & Associates, Inc.
Slide 18
An anonymous function (the $ function) with
one parameter that returns a DOM element
var $ = function (id) {
return document.getElementById(id);
}
How to call the function
var emailAddress1 = $("email_address1").value;
Murach's JavaScript and jQuery, C3
© 2012, Mike Murach & Associates, Inc.
Slide 19
An anonymous 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 the function
var subtotal = 85.00;
var taxRate = 0.05;
var salesTax = calculateTax( subtotal, taxRate );
alert(salesTax);
Murach's JavaScript and jQuery, C3
© 2012, Mike Murach & Associates, Inc.
Slide 20
The syntax for a named function
function functionName (parameters) {
// statements that run when the function is executed
}
A named function with no parameters
that doesn’t return a value
function showYear() {
var today = new Date();
alert( "The year is " + today.getFullYear() );
}
How to call the function
showYear();
Murach's JavaScript and jQuery, C3
© 2012, Mike Murach & Associates, Inc.
Slide 21
A named function with two parameters
that returns a value
function calculateTax ( subtotal, taxRate ) {
var tax = subtotal * taxRate;
tax = parseFloat( tax.toFixed(2) );
return tax;
}
How to call the function
var subtotal = 85.00;
var taxRate = 0.05;
var salesTax = calculateTax( subtotal, taxRate );
alert(salesTax);
Murach's JavaScript and jQuery, C3
© 2012, Mike Murach & Associates, Inc.
Slide 22
Terms
 function
 call a function
 parameter
 argument
 return statement
 anonymous function
 named function
Murach's JavaScript and jQuery, C3
© 2012, Mike Murach & Associates, Inc.
Slide 23
A function that uses a local variable named tax
var calculateTax = function ( subtotal, taxRate ) {
var tax = subtotal * taxRate;
// tax is local
tax = parseFloat( tax.toFixed(2) );
return tax;
}
Referring to a local variable from outside the function
causes an error
alert("Tax is " + tax);
Murach's JavaScript and jQuery, C3
© 2012, Mike Murach & Associates, Inc.
Slide 24
A function that uses a global variable named tax
var tax;
// tax is global
var calculateTax = function ( subtotal, taxRate ) {
tax = subtotal * taxRate;
tax = parseFloat( tax.toFixed(2) );
}
Referring to a global variable from outside the function
doesn’t cause an error
alert("Tax is " + tax);
Murach's JavaScript and jQuery, C3
// will not cause error
© 2012, Mike Murach & Associates, Inc.
Slide 25
A function that inadvertently uses
a global variable named tax
var calculateTax = function ( subtotal, taxRate ) {
tax = subtotal * taxRate;
// tax is global
tax = parseFloat( tax.toFixed(2) );
}
Referring to the tax variable from outside the function
doesn’t cause an error...but it should!
alert("Tax is " + tax);
Murach's JavaScript and jQuery, C3
// will not cause error
© 2012, Mike Murach & Associates, Inc.
Slide 26
Best coding practices
 Use local variables whenever possible.
 Always use the var keyword to declare a new variable
before the variable is referred to by other statements.
Murach's JavaScript and jQuery, C3
© 2012, Mike Murach & Associates, Inc.
Slide 27
Terms
 scope
 local variable
 local scope
 global variable
 global scope
Murach's JavaScript and jQuery, C3
© 2012, Mike Murach & Associates, Inc.
Slide 28
Common events
Object
window
button
control or link
control
element
Murach's JavaScript and jQuery, C3
Event
load
click
focus
blur
change
select
click
dblclick
mouseover
mousein
mouseout
© 2012, Mike Murach & Associates, Inc.
Slide 29
The syntax for attaching an event handler
objectVariable.oneventName = eventHandlerName;
An event handler named joinList
var joinList = function() {
alert("The statements for the function go here");
}
How to attach the event handler
to the click event of a button
document.getElementById("submit_button").onclick =
joinList;
How to attach the event handler
to the double-click event of a text box
document.getElementById("text_box_1").ondblclick =
joinList;
Murach's JavaScript and jQuery, C3
© 2012, Mike Murach & Associates, Inc.
Slide 30
Terms
 event handler
 attach an event handler
 trigger an event
Murach's JavaScript and jQuery, C3
© 2012, Mike Murach & Associates, Inc.
Slide 31
The HTML for a page
<h1>Please join our email list</h1>
<label for="email_address">Email Address:</label>
<input type="text" id="email_address"
name="email_address"><br>
<label> </label>
<input type="button" id="join_list"
value="Join our List"><br>
Murach's JavaScript and jQuery, C3
© 2012, Mike Murach & Associates, Inc.
Slide 32
The JavaScript that attaches two event handlers
in the onload event handler
// the $ function
var $ = function (id) {
return document.getElementById(id);
}
// the handler for the click event of the button
var joinList = function () {
alert("The joinList function is being run.");
}
// the handler for the onchange event of the text box
var changeValue = function () {
alert("The changeValue function is being run.");
}
// the handler for the onload event
window.onload = function () {
$("join_list").onclick = joinList;
$("email_address").onchange = changeValue;
Murach's JavaScript and jQuery, C3
© 2012, Mike Murach & Associates, Inc.
//}
Slide 33
The web browser after the Email Address
has been changed
Murach's JavaScript and jQuery, C3
© 2012, Mike Murach & Associates, Inc.
Slide 34
The Miles Per Gallon application in a browser
Murach's JavaScript and jQuery, C3
© 2012, Mike Murach & Associates, Inc.
Slide 35
The HTML and JavaScript for the application
<!DOCTYPE html>
<html>
<head>
<title>Calculate MPG</title>
<link rel="stylesheet" href="mpg.css">
<script>
var $ = function (id) {
return document.getElementById(id);
}
var calculateMpg = function () {
var miles = parseFloat($("miles").value);
var gallons = parseFloat($("gallons").value);
if (isNaN(miles) || isNaN(gallons)) {
alert("Both entries must be numeric");
}
else {
var mpg = miles / gallons;
$("mpg").value = mpg.toFixed(1);
}
}
Murach's JavaScript and jQuery, C3
© 2012, Mike Murach & Associates, Inc.
Slide 36
The HTML and JavaScript (continued)
window.onload = function () {
$("calculate").onclick = calculateMpg;
$("miles").focus();
}
</script>
</head>
<body>
<section>
<h1>Calculate Miles Per Gallon</h1>
<label for="miles">Miles Driven:</label>
<input type="text" id="miles"><br>
<label for="gallons">Gallons of Gas Used:</label>
<input type="text" id="gallons"><br>
<label for="mpg">Miles Per Gallon</label>
<input type="text" id="mpg" disabled><br>
<label> </label>
<input type="button" id="calculate"
value="Calculate MPG">
</section>
</body>
</html>
Murach's JavaScript and jQuery, C3
© 2012, Mike Murach & Associates, Inc.
Slide 37
The Email List application in a web browser
Murach's JavaScript and jQuery, C3
© 2012, Mike Murach & Associates, Inc.
Slide 38
The HTML file for the page
<!DOCTYPE html>
<html>
<head>
<title>Join Email List</title>
<link rel="stylesheet" href="email_list.css">
<script src="email_list.js"></script>
</head>
<body>
<section>
<h1>Please join our email list</h1>
<form id="email_form" name="email_form"
action="join.html" method="get">
<label for="email_address1">
Email Address:</label>
<input type="text" id="email_address1
name="email_address1">
<span id="email_address1_error">*</span><br>
Murach's JavaScript and jQuery, C3
© 2012, Mike Murach & Associates, Inc.
Slide 39
The HTML file for the page (continued)
<label for="email_address2">
Re-enter Email Address:</label>
<input type="text" id="email_address2"
name="email_address2">
<span id="email_address2_error">*</span><br>
<label for="first_name">First Name</label>
<input type="text" id="first_name"
name="first_name">
<span id="first_name_error">*</span><br>
<label> </label>
<input type="button" id="join_list"
value="Join our List">
</form>
</section>
</body>
</html>
Murach's JavaScript and jQuery, C3
© 2012, Mike Murach & Associates, Inc.
Slide 40
The JavaScript for the Email List application
var $ = function (id) {
return document.getElementById(id);
}
var joinList = function () {
var emailAddress1 = $("email_address1").value;
var emailAddress2 = $("email_address2").value;
var isValid = true;
// validate the first entry
if (emailAddress1 == "") {
$("email_address1_error").firstChild.nodeValue =
"This field is required.";
isValid = false;
} else {
$("email_address1_error").firstChild.nodeValue = "";
}
Murach's JavaScript and jQuery, C3
© 2012, Mike Murach & Associates, Inc.
Slide 41
The JavaScript (continued)
// validate the second entry
if (emailAddress2 == "") {
$("email_address2_error").firstChild.nodeValue =
"This field is required.";
isValid = false;
} else if (emailAddress1 !== emailAddress2) {
$("email_address2_error").firstChild.nodeValue =
"This entry must equal first entry.";
isValid = false;
} else {
$("email_address2_error").firstChild.nodeValue =
"";
}
Murach's JavaScript and jQuery, C3
© 2012, Mike Murach & Associates, Inc.
Slide 42
The JavaScript (continued)
// validate the third entry
if ($("first_name").value == "") {
$("first_name_error").firstChild.nodeValue =
"This field is required.";
isValid = false;
} else {
$("first_name_error").firstChild.nodeValue = "";
}
if (isValid) {
// submit the form
$("email_form").submit();
}
}
window.onload = function () {
$("join_list").onclick = joinList;
$("email_address1").focus();
}
Murach's JavaScript and jQuery, C3
© 2012, Mike Murach & Associates, Inc.
Slide 43
Exercise 3-2: Develop a Future Value application
Murach's JavaScript and jQuery, C3
© 2012, Mike Murach & Associates, Inc.
Slide 44
Extra 3-1: Develop the Sales Tax Calculator
Murach's JavaScript and jQuery, C3
© 2012, Mike Murach & Associates, Inc.
Slide 45
Extra 3-2: Develop the Change Calculator
Murach's JavaScript and jQuery, C3
© 2012, Mike Murach & Associates, Inc.
Slide 46
Extra 3-3: Develop the Income Tax Calculator
2012 federal income tax table for individuals
Taxable Income
Less than $8,700
$8,700 – $35,350
$35,350 – $85,650
$85,650 – $178,650
$178,650 – $388,350
More than $388,350
Murach's JavaScript and jQuery, C3
Tax Percent
10%
15%
25%
28%
33%
35%
© 2012, Mike Murach & Associates, Inc.
Slide 47
Short 3-1: Enhance a Future Value application
(20-30 minutes)
Enhancements
 Clear the Rate text box if the user double-clicks in it.
 Change the FV calculation so interest is compounded monthly.
 Display the error messages for data validation to the right of the
text boxes.
Murach's JavaScript and jQuery, C3
© 2012, Mike Murach & Associates, Inc.
Slide 48
Download