Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
murachs
JavaScript
and
DOM Scripting
(Chapter 3)
Thanks for downloading this chapter from Murachs JavaScript and DOM Scripting. We hope it will show you how easy it is to learn from any Murach book, with its paired-pages presentation, its how-to headings, its practical coding examples, and its clear, concise style. To view the full table of contents for this book, you can go to our website. From there, you can read more about this book, you can find out about any additional downloads that are available, and you can review our other books on web development. Thanks for your interest in our books!
iii
Contents
Introduction Section 1 Introduction to JavaScript programming Chapter 1 Chapter 2 Chapter 3 Chapter 4 Chapter 5 Introduction to web development and JavaScript How to code a JavaScript application How to test and debug a JavaScript application A crash course in XHTML A crash course in CSS 3 43 89 121 169 xiv
Section 2 JavaScript essentials Chapter 6 Chapter 7 Chapter 8 Chapter 9 Chapter 10 Chapter 11 Chapter 12 How to get input and display output How to work with numbers, strings, and dates How to code control statements How to create and use arrays How to create and use functions How to create and use objects How to use regular expressions, handle exceptions, and validate data 223 249 275 301 327 355 385
Section 3 DOM scripting Chapter 13 Chapter 14 Chapter 15 Chapter 16 Chapter 17 Chapter 18 Basic DOM scripting Advanced event handling Advanced DOM manipulation How to script CSS How to script tables and forms Animation with DOM scripting 421 469 523 555 591 633
Section 4 Other JavaScript skills Chapter 19 Chapter 20 How to control the web browser How to use JavaScript libraries 663 701
Reference Aids Appendix A Index How to set up your computer for this book 745 753
Chapter 3
89
3
How to test and debug a JavaScript application
As you build a JavaScript application, you need to test it to make sure that it performs as expected. Then, if there are any problems, you need to debug your application to correct any problems. This chapter shows you how to do both. Since JavaScript runs in a web browser, you can only use the testing and debugging tools that are provided by the browser. But, as you will see, these tools are limited when compared to the tools that are provided by an integrated development environment like Visual Studio or NetBeans.
An introduction to testing and debugging ........................ 90
Typical test phases for a JavaScript application ........................................... 90 The three types of errors that can occur ....................................................... 90 Common JavaScript errors ........................................................................... 92 How to get error messages with Firefox ...................................................... 94 A simple way to trace the execution of your JavaScript code ...................... 96
90
Section 1
Chapter 3
91
Description
To test a JavaScript application, you run it to make sure that it works properly no matter what combinations of valid or invalid data you enter or what sequence of controls you use. When you debug an application, you find and fix all of the errors (bugs) that you find when you test the application.
An introduction to testing and debugging
Figure 3-1
92
Section 1
Chapter 3
93
Figure 3-2
94
Section 1
Chapter 3
95
The source code thats displayed when you click on the link
Description
The Error Console in Firefox is used to display errors, warnings, and messages generated by web pages. That includes messages caused by errors in JavaScript code. The buttons at the top of the Error Console let you display all errors, just fatal errors, just warnings, or just messages. The Clear button removes all errors from the console. If you click the link to the file in the Error Console, Firefox will display the code and highlight the line at which the error occurred. You will not, however, be able to edit the file.
Figure 3-3
96
Section 1
Chapter 3
97
JavaScript with alert statements that trace the execution of the code
var calculate_click = function () { var investment = parseFloat( $("investment").value ); var annualRate = parseFloat( $("rate").value ); var years = parseInt( $("years").value ); $("futureValue").value = ""; var monthlyRate = annualRate / 12 / 100; alert("Monthly Rate = " + monthlyRate); var months = years * 12; alert("Months = " + months); var futureValue = 0; for ( i = 1; i <= months; i++ ) { futureValue = ( futureValue + investment ) * (1 + monthlyRate); alert("Month = " + i + "\nFuture Value = " + futureValue); } }
The alert dialog box the fifth time through the loop
Description
A simple way to trace the execution of a JavaScript application is to insert alert statements at key points in the code. The messages in the alert dialog boxes can display the values of variables or display messages that indicate what portion of the code is being executed. When you see an incorrect value displayed, there is a good chance that you have a logic error between the current alert statement and the previous one.
Figure 3-4
98
Section 1
Chapter 3
99
Firebug in Firefox
Firebug panel
Firebug tabs
Close button
Firebug icon
Description
Firebug is an extension for Firefox that adds debugging facilities to Firefox. To install the Firebug extension, see appendix A. Firebug has six tabs that are enabled by default that let you interact with a web page. The Console, Script, and Net tabs are disabled for all websites by default as a security precaution. You can enable these tabs for individual web sites or for all web sites. For more information about Firebug, you can go to http://www.getfirebug.com.
Figure 3-5
100
Section 1
methods in an expandable tree view. It starts with the global object. You can edit the values of object properties to see the effect on the web page. The Net tab displays information about each request sent to the web browser. It shows download times, the server used, the HTTP request headers, the HTTP response headers, the HTTP response entity body, and local caching information.
Chapter 3
101
A profile of the functions that were called and a collapsed command line
Description
One of the uses of the Firebug Console tab is to display error messages like those that are displayed by the Error Console. If you click on the code link, the Script tab is opened and the line that caused the error is highlighted. A stack trace shows the functions that were called prior to the error with the most recent call at the top of the trace. To display a stack trace when an error message is displayed in the Console tab, click on the error message link or the plus sign before the link.
Figure 3-6
102
Section 1
Chapter 3
103
Description
In the Script tab, the code is displayed in black and white. If you want to enhance this so color is used to highlight specific coding elements, you can install the Rainbow extension for Firebug, as shown in appendix A. Although you can use the features of the Script tab to find errors, you cant change the code. You still need to use your text editor to make the changes.
Figure 3-7
104
Section 1
Chapter 3
105
Description
You can set a breakpoint on any line except a blank line. When the JavaScript engine encounters a breakpoint, it stops before it executes the statement that contains the breakpoint. To see a stack trace when youre stepping through an application, click on the Stack tab.
How to set breakpoints and step through the execution of your code
Figure 3-8
106
Section 1
This code should be near the start of the JavaScript code so its easy to find. Next, you modify any wrapper code so it checks the value of the debug flag before using any of the console methods. For instance, the code in this figure would be expanded to look like this:
if ( debug && typeof console == "object" && console.log ) { console.log ("Function complete."); }
Now, if you set the debug flag to true and the console object is present, this code will call the console.log method. But if you set the debug variable to false, this code wont call the log method even if the console object is present.
Chapter 3
107
Description
Displays a message in the console. It takes one or more objects as parameters to display. Displays a message in the console and includes a link to the source of the message. It takes one or more objects as parameters to display. Displays a message with an information icon in the console and includes a link to the source of the message. It takes one or more objects as parameters to display. Displays a message with a warning icon in the console and includes a link to the source of the message. It takes one or more objects as parameters to display. Displays a message with an error icon in the console and includes a link to the source of the message. It takes one or more objects as parameters to display. Displays an error message in the console and throws an exception if the boolean expression in its first parameter is false. It takes a Boolean expression as its first parameter and optional objects to display in the console if the assertion fails. Displays an interactive list of the objects properties. It takes one object as a parameter. Turns on the Firebug profiler which times every function call. It takes one optional parameter which is a string to display in the console. Turns off the Firebug profiler and displays the report in the console.
How to test for the presence of the console object and the log method
if (typeof console == "object" && console.log) { console.log ("Function complete."); }
Description
The methods of the console object give you many ways to track and report what your program is doing. If the console object isnt available, youll get a runtime error if you try to use it. To avoid that, you can use the code above, which tests to see whether the console object and the log method are available. Go to http://getfirebug.com/console.html for a complete list of the methods of the console object.
Figure 3-9
108
Section 1
Chapter 3
109
The JavaScript file for the Future Value application with execution tracing
var $log = function () { if (typeof console == "object" && console.log ) { console.log.apply(console, arguments); } } var $ = function (id) { return document.getElementById(id); } var calculate_click = function () { var investment = parseFloat( $("investment").value ); var annualRate = parseFloat( $("rate").value ); var years = parseInt( $("years").value ); $log("investment", investment); $log("annualRate", annualRate); $log("years", years); $("futureValue").value = ""; var monthlyRate = annualRate / 12 / 100; var months = years * 12; var futureValue = 0; $log("monthlyRate", monthlyRate); $log("months", months); for ( i = 1; i <= months; i++ ) { futureValue = ( futureValue + investment ) * (1 + monthlyRate); $log("month " + i + " futureValue", futureValue); } }
Description
The log method of Firebugs console object writes data to the Console tab. The $log function at the start of the code wraps the console.log method so calls to it wont cause a runtime error if Firebug isnt installed or enabled. The effect is that the $log function executes the console.log method.
Figure 3-10
110
Section 1
Chapter 3
111
Description
The error message feature of Internet Explorer doesnt let you jump to the statement that caused the error the way Firefox does. Internet Explorer 8 provides Developer Tools as a separate download. These tools support breakpoints, stack traces, and the display of variables while youre stepping through an application in a way thats similar to Firebug. To access the Developer Tools after youve downloaded and installed them, press F12.
Figure 3-11
112
Section 1
Chapter 3
113
Description
To get messages in the Safari console, you must open the console before loading the web page you want to run. To see the JavaScript code for an error message, click on the URL in the message. To view your current web page in another browser, use the Develop Open Page With command, and then select the browser you want to use. Safari doesnt support breakpoints, stack traces, or watch expressions.
Figure 3-12
114
Section 1
Chapter 3
115
Description
The error console shows all error messages, and the error messages are followed by a stack trace. To view the source code where an error occurred, click the pencil icon to the right of an error message. Opera provides developer tools that support breakpoints, stack traces, and the display of variables while youre stepping through an application in a way thats similar to Firefox.
Figure 3-13
116
Section 1
Chapter 3
117
Description
The JavaScript console lists the error messages. Then, you can click the link for an error message to highlight the error in the JavaScript code thats shown in the Resources tab. In the left pane of the Resources tab, you can click on any file thats listed to display its contents in the right pane.
How to get error messages with Chrome
Figure 3-14
118
Section 1
Perspective
All too often, JavaScript applications are put into production before they have been thoroughly tested and debugged. In the early days of JavaScript programming, that was understandable because the tools for testing and debugging were limited. Today, however, Firefox and its Firebug extension give you the tools you need for finding all the bugs before an application is put into production. As a result, theres no longer a good excuse for inadequate testing and debugging.
Terms
test debug syntax error runtime error logic error bug trace stack stack trace profiler profile static script eval script event script breakpoint conditional breakpoint debug flag backtrace
Exercise 3-1
In this exercise, youll use Firefox and the Firebug extension to find and fix four syntax errors in the Future Value application.
2.
3.
5.
Chapter 3
119
6.
Once the application is working, get a profile of the functions that it uses. To do that, start the profiler, run the application twice with two sets of input values, stop the profiler, and review the profile in the Console tab.
Exercise 3-2
In this exercise, youll use alert methods to trace the execution of the Future Value application. 1. Open the html file in the chapter_03\future_value_alert folder for exercises. The related JavaScript file named future_value_alert.js includes the alert methods shown in figure 3-4. Run the application to see how the alert methods work.
2.
Exercise 3-3
In this exercise, youll use Firefox and its Firebug extension to set a breakpoint and step through the Future Value application. 1. 2. Open the html file in the chapter_03\future_value folder for exercises. Use the drop-down list above the Script tab to display the code for the future_value.js file. Then, set a breakpoint on the return statement in the $ function (the second line of code in the file). Enter valid values in the input boxes for the application, and click the Calculate button. The application should stop at the breakpoint. Experiment with the Step Into, Step Over, and Step Out buttons as you step through the code of the application. At each step, notice the values that are displayed in the Watch tab. Also, hover the mouse over a variable in the Script tab to see what its value is. When youre through experimenting, remove the breakpoint.
3. 4.
5.
Exercise 3-4
In this exercise, youll use Firefox, its Firebug extension, and the console.log method to trace the execution of the Future Value application. 1. Open the html file in the chapter_03\future_value_trace folder for exercises. The related JavaScript file named future_value_trace.js includes the tracing statements shown in figure 3-10. Review the tracing statements that the JavaScript file contains. Next, run the application twice with two sets of input data. Then, review the tracing data in the Console tab of the Firebug panel.
2.
To get your copy, you can order online at www.murach.com or call us at 1-800-221-5528 (toll-free in the U.S. and Canada). And remember, when you order directly from us, this book comes with my personal guarantee:
100% Guarantee
You must be satisfied. Each book you buy directly from us must outperform any competing book or course youve ever tried, or send it back within 90 days for a full refundno questions asked.