Sei sulla pagina 1di 34

TRAINING & REFERENCE

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!

MIKE MURACH & ASSOCIATES, INC.


1-800-221-5528 (559) 440-9071 Fax: (559) 440-0963 murachbooks@murach.com www.murach.com
Copyright 2009 Mike Murach & Associates. All rights reserved.

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

How to test and debug a JavaScript application

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

How to debug with the Firebug extension of Firefox ....... 98


How to install and enable the Firebug extension ......................................... 98 How to get information in the Console tab ................................................ 100 How to review your code in the Script tab ................................................. 102 How to use breakpoints and step through code .......................................... 104

How to use the Firebug console object ........................... 106


The methods of the console object ............................................................. 106 How to trace an application with Firebugs console.log method ............... 108

How to test and debug with other browsers ................... 110


How to get error messages with Internet Explorer ..................................... 110 How to get error messages with Safari ....................................................... 112 How to get error messages with Opera ...................................................... 114 How to get error messages with Chrome ................................................... 116

Perspective ........................................................................ 118

90

Section 1

Introduction to JavaScript programming

An introduction to testing and debugging


When you test an application, you run it to make sure that it works correctly. As you test the application, you try every possible combination of input data and user actions to be certain that the application works in every case. In other words, the goal of testing is to make an application fail. When you debug an application, you fix the errors (bugs) that you discover during testing. Each time you fix a bug, you test again to make sure that the change that you made didnt affect any other aspect of the application.

Typical test phases for a JavaScript application


When you test an application, you typically do so in phases, like the three that are summarized in figure 3-1. In the first phase, as you test the user interface, you should visually check the controls to make sure theyre displayed properly with the correct text. Then, you should make sure that all the keys and controls work correctly. For instance, you should test the Tab key and Enter key as well as the operation of check boxes and drop-down lists. In the second phase, you should test the application with valid data. To start, you can enter data that you would expect a user to enter. Before youre done, though, you should enter valid data that tests all of the limits of the application. In the third phase, you go all out to make the application fail by testing every combination of invalid data and user action that you can think of. That should include random actions like pressing the Enter key or clicking the mouse at the wrong time.

The three types of errors that can occur


As you test an application, there are three types of errors that can occur: These errors are described in figure 3-1. Because syntax errors prevent your application from running, they are the easiest to find and fix. As you will see, a typical web browser provides error messages that help you do that. Although runtime errors dont violate the syntax rules, they do throw exceptions that stop the execution of an application. Unlike other languages, though, JavaScript doesnt throw many of the traditional exceptions. For instance, if you divide a number by zero, JavaScript returns infinity instead of throwing an exception. As a result, most JavaScript exceptions involve problems with the use of identifiers. Logic errors can come from many places, and they are often the most difficult to find and correct. A mistake in a calculation, events not being triggered in the order you expect them to, and working with incorrect values are just a few of the ways that logic errors can creep into your applications. The Sales Tax application in this figure has a logic error. Can you tell what it is?

Chapter 3

How to test and debug a JavaScript application

91

The Sales Tax application with a logic error

The goal of testing


To find all errors before the application is put into production.

The goal of debugging


To fix all errors before the application is put into production.

Three test phases


Check the user interface to make sure that it works correctly. Test the application with valid input data to make sure the results are correct. Test the application with invalid data or unexpected user actions. Try everything you can think of to make the application fail.

The three types of errors that can occur


Syntax errors violate the rules for how JavaScript statements must be written. These errors are caught by the web browser. Runtime errors dont violate the syntax rules, but they throw exceptions that stop the execution of the application. Logic errors are statements that dont cause syntax or runtime errors, but produce the wrong results.

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

Introduction to JavaScript programming

Common JavaScript errors


Figure 3-2 presents some of the coding errors that are commonly made as you write a JavaScript application. If you study this figure, youll have a better idea of what to watch out for. And if you did the exercises for the last chapter, youve probably experienced some of these errors already. The code at the top of this figure is the start of the code for the Future Value application but with four errors introduced into the code. The first one is in the second line. The error is that getElementByID should be getElementById. Remember that JavaScript is case-sensitive. Can you spot the other three errors? If not, youll get a chance to find them when you do the exercises for this chapter. Two problems that are peculiar to JavaScript are also discussed in this figure. The first involves floating-point arithmetic. JavaScript uses the IEEE 754 standard for floating-point numbers. Unfortunately, this standard can introduce strange results with even simple calculations. The figure suggests one way of dealing with this issue. The other problem involves the way JavaScript converts values when performing comparisons. The general rule is that when JavaScript compares two values that are of different types, it converts them both to number values. It does this even if one is a string and the other is a Boolean value. So the expression 1 == true will return true because true is converted to 1, and the expression 0 == false will also return true because false will be converted to 0. Testing for equality with the value NaN can also be troublesome because the expression NaN == NaN will return false. But youll learn more about that in chapter 7.

Chapter 3

How to test and debug a JavaScript application

93

JavaScript code that contains errors


var $ = function (id) { return document.getElementByID(id); } var calculate_click = function () { var investment = parseFloat( $("investment").value ); var annualRate = parseFloat( $("rat").value ); var years = parseInt( $("years").value ; $("futureValue").value = ""; }

Common syntax errors


Misspelling keywords. Forgetting an opening or closing parenthesis, bracket, brace, or comment character. Breaking a single line into two valid statements where JavaScript inserts a semicolon. Forgetting to use a semicolon that is essential to the logic of the code. Forgetting an opening or closing quote mark. Not using the same opening and closing quote mark.

Problems with identifiers


Misspelling or incorrectly capitalizing an identifier. Using a reserved word, global property, or global method as an identifier.

Problems with values


Not checking that a value is the right data type before processing it. For example, you expect the user to enter a date, but he enters a name instead. Forgetting to use the parseInt or parseFloat function to convert a user entry into a numeric value. Using one equal sign instead of two when testing for equality.

A problem with floating-point arithmetic


The number data type in JavaScript uses floating-point numbers and that can lead to arithmetic math errors. For example, 0.2 + 0.7 in JavaScript is 0.8999999999999999. One way around this is to round the number to the desired decimal place with the toFixed method and then convert it back to a floating-point number with the parseFloat method.

A problem with comparing values of different data types


When you compare two values that are of different data types, JavaScript will internally convert both values to numbers. In this conversion, an empty string is converted to 0; true is converted to 1; and false is converted to 0. This can lead to unexpected result when using the equality operator. For example, the expression 0 == will evaluate to true since an empty string is converted to 0.
Common JavaScript errors

Figure 3-2

94

Section 1

Introduction to JavaScript programming

How to get error messages with Firefox


When you run the Future Value application with the errors shown in figure 3-2, the interface will still be displayed. When you try to use the application, however, it wont do anything because of the errors. To see the error messages that Firefox produces, open the Error Console as as in figure 3-3. Here, as you learned in chapter 2, the console shows the first error thats detected when the Future Value application is run with the errors of the previous figure. In this case, the arrow under the message points to the character in the line that caused the error. The mistake is that a leading double quotation mark is matched by a single quotation mark, which is invalid. To display the source code for a JavaScript file, you can click on the link in the error message. That opens the source code in a separate window with the error highlighted. You cant use that window to fix the code, though. Instead, you need to use your editor to fix and save the code and then restart the application in Firefox by clicking on the Reload button. Often, the error messages are not as clear as in this example. Instead, an error in one line will be reported as an error somewhere else. Then, you start by looking for the error in the line indicated in the error message, but work your way to related portions of code until you find the error. The tabs at the top of the Error Console let you select which types of messages you want displayed. If you use many extensions or themes or if you have several pages open in tabs, all of their messages, warnings, and errors will be displayed in the same Error Console window. Then, you can show just the errors by clicking the Errors tab. You can also remove all messages from the Error Console by clicking the Clear button. You can also use the Error Console to evaluate JavaScript expressions. To do that, you type the code you want to evaluate in the Code text box and click the Evaluate button. Then, the results will be displayed in the Error Console. Note, however, that you cant use functions or variables in an expression in the Error console. In this figure, the second message in the Error Console, which displays 101, is the result of the expression in the Code text box. Incidentally, the error message in this figure is for the first error thats detected when the code in the previous figure is run, but that error isnt the first one in the code. Thats because the JavaScript engine only detects syntax errors as the page is being loaded, but the first error in the code is a runtime error. The JavaScript engine wont run the application until all of the syntax errors have been corrected. Then, the $ function will be called and its runtime error will be detected.

Chapter 3

How to test and debug a JavaScript application

95

The Firefox Error Console with an error displayed

The source code thats displayed when you click on the link

How to display the Error Console and source code


To display the Error Console, use the Tools Error Console command or press Ctrl+Shift+J. To display the source code with the error highlighted, click on the link in the Error Console.

How to evaluate expressions with the Error Console


Enter the expression in the Code text box and click the Evaluate button. Note, however, that you cant use functions or variables in the expression.

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

How to get error messages with Firefox

96

Section 1

Introduction to JavaScript programming

A simple way to trace the execution of your JavaScript code


When you trace the execution of an application, you add statements to your code that display messages or variable values at key points in the code. This is typically done to help you find the cause of a logic error. If, for example, you cant figure out why the future value thats calculated by the Future Value application is incorrect, you can insert three alert statements into the code for the application as shown in figure 3-4. These functions display dialog boxes that show the values for four of the variables as the code is executed. That should help you determine where the calculation is going wrong. Then, when you find and fix the problem, you can remove the alert statements. When you use this technique, you usually start by adding just a few alert statements to the code. Then, if that doesnt help you solve the problem, you can add more. This works well for simple applications, but has its limitations. Later in this chapter, youll learn other debugging techniques as well as a more sophisticated method of tracing the execution of an application.

Chapter 3

How to test and debug a JavaScript application

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

A simple way to trace the execution of your JavaScript code

98

Section 1

Introduction to JavaScript programming

How to debug with the Firebug extension of Firefox


Of the five major web browsers, Firefox and its Firebug extension provide the best environment for debugging JavaScript code. As a result, you should do most of your testing and debugging in Firefox. Once your code works in Firefox, you can test it in the other browsers to ensure that it still functions as expected.

How to install and enable the Firebug extension


The Firefox web browser lets you install extensions that add new functionality to the browser. Firebug is a free extension that enhances the JavaScript debugging capabilities of Firefox. You can learn how to install Firebug in appendix A. When Firebug is installed, you will see the Firebug icon in the Firefox status bar, as shown in figure 3-5. Then, you can click this icon to open and close the panel. Or, you can press the F12 key to open and close this panel. As you can see in this figure, the Firebug panel is divided into two panes. The left pane is the main pane and has six tabs for viewing information about the current web page, and the right pane displays additional information based on which tab is selected in the left pane. By default, three of the six tabs in the left pane are disabled, but you can enable them by using the techniques in this figure. To adjust the size of the panes, you can drag the divider between them. There is also an Options menu for each of the panes. At the top left of the Firebug panel, there is a Firebug icon that drops down a menu, an Inspect button, and additional buttons that change based on the selected tab. At the top right of the Firebug panel, there is a search box, a button to open Firebug in a separate window, and a button to close the Firebug panel. You can drag the top edge of the Firebug panel to adjust its size. The Console tab displays an enhanced error console. Here, you can view error messages, log messages from your application, execute code, and profile the performance of your application. The HTML tab displays the XHTML code for your web page in an expandable tree view in the left pane. Here, you can browse to an XHTML tag and change its attributes to see the effect on your page. In the right pane, you can use the tabs to view the CSS style information, the layout information, and the DOM elements on the web page. The CSS tab shows you the CSS code for your web page. If there is more than one file containing CSS, you can view a different file by using the dropdown list of file names at the top of the Firebug panel. You can also make changes to the CSS code to see the effect on the web page. The Script tab shows you the JavaScript source code. If there is more than one file containing JavaScript, you can view a different file by using the dropdown list of file names at the top of the Firebug panel. The DOM tab shows the objects in the DOM and their properties and

Chapter 3

How to test and debug a JavaScript application

99

Firebug in Firefox

Firebug panel

Firebug tabs

Close button

Firebug icon

How to access the Firebug panel


Click the Firebug icon, use the View Firebug command, or press F12.

How to enable or disable a tab


1. Click the tab to open it, and click the down arrow next to the tab name. 2. In the menu that appears, select Enabled or Disabled to enable or disable that tab for all websites. Or, select Enable for Local Files or Disable for Local Files to enable or disable that tab for the web site you are currently viewing.

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

How to install and enable the Firebug extension

100

Section 1

Introduction to JavaScript programming

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.

How to get information in the Console tab


The Firebug Console tab replaces and enhances the Firefox Error Console. Any messages that are displayed in the Firefox Error Console are also displayed in the Firebug Console tab. This is illustrated by the first example in figure 3-6. Then, if you click the line of code or file name in the Console tab, Firebug will switch to the Script tab and display the source code. If you click the text of the error message in the Console tab or the plus sign that precedes the message, it will expand to display a stack trace. This is illustrated by the first example in this figure. In programming, the stack is a list of all current function calls and their parameters. For example, in the Future Value application, when the user clicks the Calculate button, the calculate_click function is called, so it is placed on the stack. Inside this function, the $ function is called, so it is placed on the stack. Then, there are two items in the stack. When a function is finished, it is removed from the stack. A stack trace is a display of the current state of the stack. This is useful for determining the state of your program when an error occurs. If, for example, an error occurs in the $ function, it sometimes helps to know whether this function was called from the onload event handler or the calculate_click function. That can speed up the debugging process. Like the Firefox Error Console, the Firebug Console tab lets you execute JavaScript code. To do that, type statements in the command line or command pane as shown in this figure. Unlike the Error Console command line, the Console tab lets you use variables, call functions, and evaluate control structures such as if and while statements. To make entering statements easier, the Console tab has an auto-complete feature. To use it, you type part of a JavaScript identifier, press the Tab key, and Firebug will try to find an identifier that starts with what you typed. If multiple identifiers are found, you can press the Tab key to cycle through them. You can also cycle through the properties of an object by typing the objects name and a period, and then pressing the Tab key. The Firebug Console tab also provides an execution profiler. This keeps track of how many times each function is called and how much time each function call took to execute. To start the profiler, you click the Profile button at the top of the Firebug panel. Then, you run your application. When youre done, click the Profile button again. At that point, the profiler will stop and display its report, or profile, in the Console tab.

Chapter 3

How to test and debug a JavaScript application

101

An error message with a stack trace and an expanded command line

A profile of the functions that were called and a collapsed command line

How to run code in the command line


A collapsed command line is at the bottom of the Console indicated by >>>. To run code in this command line, type the code and press the Enter key. To expand the command line, click the red up arrow at the right side of the command line. The expanded command line is the pane on the right of the panel. To run code in this pane, enter the code and click Run to execute the code. To clear the code, click Clear. To collapse this pane, click the red down arrow at the bottom right of the command pane.

How to get a profile of the functions that were called


To get a profile of the functions that were called, click the Profile button at the top of the Firebug panel to start the profiler. Then, after youve run the application a few times, click the Profile button again to display the profile report in the Console tab. Note: In the profile above, an error in Firebug causes the $ function to be displayed as (?). This indicates an unknown function name and should be corrected in later releases of this extension.

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

How to get information in the Console tab

102

Section 1

Introduction to JavaScript programming

How to review your code in the Script tab


The Script tab displays the JavaScript code for an application. This is illustrated by the Script tab in figure 3-7. This figure also shows you how to use this tab to review the JavaScript code for the current web page. When you use this tab, you can review three types of scripts. A static script is a script in a file. An eval script is code that is dynamically executed by a call to the global eval method. And an event script is a script that is present in an event attribute of an XHTML tag such as the onclick attribute of the input tag. In this book, though, event scripts arent used, and eval methods arent presented because they expose your scripts to security vulnerabilities. If you want the code in the Script tab highlighted with colors, you need to install the Rainbow extension for the Firebug extension. To do that, you must have Firebug version 1.2 or higher and Firefox version 3.0 or higher. If you add this extension to an earlier version of Firebug or Firefox, Firebug will no longer work so please take this as a warning. In that case, you will have to uninstall the Rainbow extension to get Firebug to work again.

Chapter 3

How to test and debug a JavaScript application

103

The Script tab in Firebug

How to switch between JavaScript files


If you have more than one JavaScript file for a web page, use the drop-down list that says futureValue.js in the screen above to switch from one file to another.

How to search through the code or jump to a line number


Type your code in the search box in the upper right of the Firebug panel. Then, press Enter to find the next occurrence of your search term. Or, to jump to a line number in the code, type a pound sign (#) followed by a line number in the search box.

How to display the types of scripts that you want to see


Use the drop-down list that shows all in the screen above. This lets you select combinations of static, eval, and event scripts. Because you probably wont be using eval or event scripts, though, you can leave this setting at all.

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

How to review your JavaScript code in the Script tab

104

Section 1

Introduction to JavaScript programming

How to use breakpoints and step through code


A breakpoint is a point in your code at which the execution of your application will be stopped. Then, you can examine the contents of variables and the execution stack to see if your code is executing as expected. You can also step through the execution of the code from that point on. These techniques can help you solve difficult debugging problems. Figure 3-8 shows you how to set breakpoints, step through the code in a JavaScript application, and view the contents of variables in the Watch pane. In the illustration, you can see that a breakpoint has been set on line 16 of the Future Value application. When you run your application, it will stop at the first breakpoint that it encounters and display a yellow triangle on top of that breakpoint. While your code is stopped, you can hover your mouse over an objects name in the Script tab to display the current value of that object. At a breakpoint, you can also view the current variables in the Watch pane on the right side of the panel. Those are the variables that are used by the function that is being executed. You can also see the value of other variables and expressions by clicking New watch expression and typing the variable or expression you want to watch. (Note that the i variable in the for loop isnt listed in the Watch pane in this figure because it isnt created until the for statement is executed.) To step through the execution of an application after a breakpoint is reached, you can use the Step Into, Step Over, and Step Out buttons. If you repeatedly click the Step Into button, you will execute the code one line at a time and the next line to be executed will be highlighted. After each line of code is executed, you can use the Watch tab to observe any changes in the variables. You can also click the Stack tab to view a stack trace that shows all of the executing functions and the value of their parameters. As you step through an application, you can click the Step Over button if you want to execute any called functions without executing them. Or, you can use the Step Out button to step out of any functions that you dont want to step through. When you want to return to normal execution, you can click the Continue button. Then, the application will run until the next breakpoint is reached. These are powerful debugging features that can help you find the causes of serious debugging problems. Stepping through an application is also a good way to understand how the code in an existing application works. If, for example, you step through the loop in the Future Value application, youll get a better idea of how that loop works.

Chapter 3

How to test and debug a JavaScript application

105

A breakpoint in the Firebug Script tab


Continue, Step Into, Step Over, and Step Out buttons

How to set a breakpoint


If necessary, use the drop-down list above the Script tab to select the right JavaScript file. Then, to set a breakpoint, click in the bar to the left of a statement. The breakpoint is marked by a red dot. To set a conditional breakpoint, right-click on a statement and enter a conditional expression in the resulting dialog box. Then, the application only stops at the breakpoint if the condition is true.

How to step through JavaScript code from a breakpoint


Click the Step Into button to step through the code one line at a time. At each step, the Watch tab displays the values of the current variables. You can also hover the mouse cursor over a variable name to display its current value. Click the Step Over button to execute any called functions without stepping through them. Click the Step Out button to execute the rest of a function without stepping through it. Or, click the Continue button to resume normal execution.

How to set a watch expression


Click New watch expression in the Watch tab and type the variable name or the expression that you want to watch.

How to disable or remove breakpoints


To remove a breakpoint, click on the red breakpoint marker in the Script tab, or click on the close button for the breakpoint in the Breakpoints tab. To disable a breakpoint, click on the check box for it in the Breakpoints tab.

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

Introduction to JavaScript programming

How to use the Firebug console object


For most applications, youll be able to test and debug your applications with the features that have been presented thus far. In some cases, though, you may need to use some of the methods of the Firebug console object to get information. In particular, you can use the console.log method to do an extensive trace of the execution of an application. If youre new to programming, you can skip this topic and come back to it later because it uses some coding techniques that wont be presented until later in this book. If youre an experienced programmer, though, this is worth a quick read.

The methods of the console object


When the Firebug Console tab is enabled, it adds an object to the JavaScript environment called the console object. This object provides many methods for reporting information in the Console tab. The more common methods are summarized in figure 3-9. For instance, the log method can be used to display messages in the Console tab, the profile method turns on the profiler, and the profileEnd method turns off the profiler. If the console object isnt available, though, the use of a console method causes a runtime error. This can happen if the Firebug extension isnt installed or the Firebug Console tab isnt enabled. To prevent errors when the console object isnt available, you can wrap the console methods in if statements or functions that test for the existence of the console object before using one of its methods. This is illustrated by the code in this figure, which tests for the presence of the console object and its log method before using the console.log method. You can also use a debug flag to control console logging even if the console object is available. A debug flag is just a global Boolean variable that indicates whether or not debugging should take place. For instance, the code that follows defines a debug flag and sets it to true:
var debug = true; // Set to false to skip debugging

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

How to test and debug a JavaScript application

107

Common methods of the Firebug console object


Method
log() debug() info() warn() error() assert()

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.

dir() profile() profileEnd()

Examples of the console object methods


// Log the value of the months variable in the console. console.log("Months", months); // Display an error message in the console. console.error("User entered an invalid value for months.");

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

The methods of the Firebug console object

108

Section 1

Introduction to JavaScript programming

How to trace an application with Firebugs console.log method


One of the uses of the console.log method is to trace the execution of an application. This is illustrated by figure 3-10. In this case, the log method is used to display variable names and values at various points in the code. This data will be displayed in the Console tab as the application executes. When the application is finished, you can review this data. This will help you determine where the bug is. Then, youll have more information that will help you determine what the logic error is and how to fix it. Note, however, that the log method isnt used directly in this figure. Instead, its wrapped in the $log function. That will prevent runtime errors from occurring when the console object isnt available. In chapter 10, youll learn how the apply method of a function works, but for now just know that the $log function accepts any number of parameters and uses the log function to display them in the Console tab. Statements that use the $log function are then inserted in strategic places in the code of the Future Value application to trace its execution.

Chapter 3

How to test and debug a JavaScript application

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); } }

The data thats written to the Console tab

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

How to trace an application with Firebugs console.log method

110

Section 1

Introduction to JavaScript programming

How to test and debug with other browsers


Although I recommend that you use Firebug in the Firefox browser to do your primary testing and debugging, you also need to know how to debug JavaScript in the other browsers. In some cases, for example, your code will work in Firefox, but fail in other browsers. Then, you need to know how get any help that those browsers offer. With that in mind, heres a quick tour of the features offered by Internet Explorer, Safari, Opera, and Chrome. In these descriptions, the focus is on getting the error messages from the browser, not on using the debugging features. That will get you started with these browsers. Then, if you need to use their debugging features, you can experiment with them on your own. Note too that these descriptions are for the current releases of these browsers at the time of this writing. But since these browsers are continually being upgraded, some of this information may change.

How to get error messages with Internet Explorer


When Internet Explorer encounters an error, it displays a yellow triangle with an exclamation mark in the lower left corner of the browser window. Then, to view the error message, you double-click this error icon. This is illustrated by figure 3-11. When the message box is displayed for the first time, you may need to click the Show Details button to view the details of the message. Then, if you close the dialog box with the details still displayed, Internet Explorer will show the details the next time the message box is displayed. Like Firefox, the details of the error message show the line number that caused the error, a description of the error, and the URL of the file where the error occurred. Note, however, that the error message in this figure is reported as line 3 of the XHTML file. This is where the script tag is used to load an external JavaScript file. However, the error actually occurs in line 2 of this JavaScript file. That means that when you use Internet Explorer you often have to search for the actual error. Like the Firebug extension of Firefox, Internet Explorer 8 offers Developer Tools that support breakpoints, stack traces, and watch expressions. However, the tools are a separate download. Once youve downloaded and installed them, you can access them by pressing the F12 key.

Chapter 3

How to test and debug a JavaScript application

111

Internet Explorer 6 with an error indicator in the lower left corner

The Internet Explorer message box

How to display an error message


Double-click the error icon in the lower left corner to view the error message. Then, if necessary, click the Show Details button to view the entire message. If you always want the error message to be displayed, you can click the checkbox before closing the message box. Or, you can go to Tools Internet Options, click on the Advanced tab, and check the Display a notification about every script error checkbox.

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

How to get error messages with Internet Explorer

112

Section 1

Introduction to JavaScript programming

How to get error messages with Safari


Like Firefox, Safari doesnt display any indication that an error has occurred in the main web browser window, but it does have a console that displays error messages. To display this console, you can use the technique in figure 312. Unlike Firefox, you must open this console before you load the web page that you want to debug. When an error occurs with the console open, the console displays the error message, the URL of the file that contains the error, and the line number where the error occurred. Like Firefox, the URL and line number identify the JavaScript file and the line number at which the error occurred. But unlike Firefox, Safari doesnt support breakpoints, stack traces, or watch expressions.

Chapter 3

How to test and debug a JavaScript application

113

The Safari console with an error message displayed

The Safari console when you click on the URL in a message

How to display the Safari console


First, display the Develop menu. To do that, use the Edit Preferences command, click the Advanced tab, and check the Show Develop menu in menu bar checkbox. Then, to display the console, use the Develop Show Error Console command.

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

How to get error messages with Safari

114

Section 1

Introduction to JavaScript programming

How to get error messages with Opera


Like Firefox, Opera doesnt display any indication that an error has occurred in the main web browser window, but it does have an Error Console for error messages. To display this console, you can use the technique in figure 3-13. When an error occurs, the Error Console displays the URL of the web page thats being displayed, the error message, and a stack trace called a backtrace. The first entry in the backtrace is where the error occurred. This shows the line number, URL, and source code where the error occurred. Then, if you click the pencil icon to the right of the URL, Opera will display the source code for the file. Like Firefox, Opera supports breakpoints, stack tracing, and watch expressions in a panel called the developer tools. In this panel, the Scripts tab displays information about the Scripts that are loaded. The DOM tab lets you view the document object model. The Error Console tab contains the same information as the Error Console window. And the Environment tab displays the version information for Opera and your operating system.

Chapter 3

How to test and debug a JavaScript application

115

The Opera error console with an error message displayed

The Opera developer tools

How to open the error console and the developer tools


To open the error console, use the Tools Advanced Error Console command. To open the developer tools, use the Tools Advanced Developer Tools command.

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

How to get error messages with Opera

116

Section 1

Introduction to JavaScript programming

How to get error messages with Chrome


Like Firefox, Chrome doesnt display any indication that an error has occurred in the main web browser window, but it does have a JavaScript console for error messages. To display this console, you can use the menu thats shown in figure 3-14. In the JavaScript console, you can click on the file link in the left pane of the the Resources tab to display the source code for a file. Then, when you click on the link in an error message, an error indicator is displayed in the source code below the statement that caused the error.

Chapter 3

How to test and debug a JavaScript application

117

The Chrome browser with the Developer menu displayed

The JavaScript console with an error message displayed

How to open the JavaScript console and the debugger


To open the JavaScript console, select the Developer JavaScript Console command from the menu that drops down from the page icon. To open the JavaScript debugger, select the Developer Debug JavaScript command.

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

Introduction to JavaScript programming

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

Fix syntax errors

In this exercise, youll use Firefox and the Firebug extension to find and fix four syntax errors in the Future Value application.

Use the Error Console to fix the first two errors


1. From the Firefox browser, open the file named future_value_errors.html in the chapter_03\future_value_errors folder for exercises. It contains the four errors shown in figure 3-2. Enter valid values in the three input boxes and click the Calculate button. When nothing happens, open the Error Console as shown in figure 3-3. Then, click on the link for the code to display the JavaScript code with the error line highlighted. Use your editor to open the JavaScript file and fix the first error. Next, return to Firefox, click the Reload button, and click the Calculate button to run the application again. Then, find and fix the second error. If you havent already done so, install the Firebug extension as shown in appendix A. Next, enable the Console and Script tabs. Then, run the Future Value application again, which still wont work. Use the techniques in figure 3-6 to find and fix the next two bugs.

2.

3.

Use the Firebug panel to fix the next two errors


4.

5.

Chapter 3

How to debug a JavaScript application

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

Trace with alert methods

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

Step through an application

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

Trace with console.log methods

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.

How to build your JavaScript skills


The easiest way is to let Murachs JavaScript and DOM Scripting be your guide! So if youve enjoyed this chapter, I hope youll get your own copy of the book today. You can use it to: Teach yourself how to use JavaScript and DOM scripting to create web sites that deliver the dynamic user interfaces, fast response times, and special effects that todays users expect Pick up a new skill whenever you want or need to by focusing on material thats new to you Look up coding details or refresh your memory on forgotten details when youre in the middle of developing a web application Loan to your colleagues who are always asking you questions about client-side web programming

Mike Murach, Publisher

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.

Thanks for your interest in Murach books!

Potrebbero piacerti anche