Hour 2. Debugging jQuery and JavaScript Web Pages


What You’ll Learn in This Hour:

Image Where to find information that is outputted from jQuery and JavaScript scripts

Image How to debug problems with HTML elements

Image Ways to more easily find and fix problems with CSS layout

Image Methods to view and edit the DOM live in the web browser

Image How to quickly find and fix problems in your JavaScript

Image What information is available to analyze network traffic between the browser and the web server


A major challenge when writing JavaScript and jQuery applications is finding and fixing problems in your scripts. Simple syntax problems or invalid values can cause a lot of frustration and wasted time. For that reason, some excellent tools have been created to help you quickly and easily find problems in your scripts. In this hour, you learn some of the basics of debugging JavaScript via Firebug in Mozilla. Although the developer consoles in other browsers are a bit different, most of the principles are the same. Also, don’t be alarmed if you don’t recognize the code element in the examples. They’ll be covered in upcoming hours, but you should be able to debug before you jump into coding heavily.

Viewing the JavaScript Console

One of the first debugging tools that you will want to become familiar with is the JavaScript console. The console is your interface to output from JavaScript scripts. Errors and log messages will be displayed as they occur in the JavaScript console.

For example, when an error in the script results in the browser not being able to parse it, the error will be displayed in the console. In addition to errors, by using the console.log statement, you can also add your own debug statements to be displayed in the JavaScript console.


Note

In addition to console.log, you can use console.error(), console.assert(), and a variety of other statements to log information to the JavaScript console. For more information about how to use the Firebug console log, see

https://getfirebug.com/wiki/index.php/Console_API


Understanding the JavaScript Console

The JavaScript console is a fairly basic and yet powerful tool. The console has two parts: the controls and the list of log entries. Figure 2.1 shows the Firebug JavaScript console.

Image

FIGURE 2.1 The JavaScript console in Firebug displays log messages and errors.

Notice the menu displayed when you click the down arrow in the Console tab. From that menu you can enable the console, as well as select which types of errors and log messages to include in the message list.

The console also provides a toolbar with several options. The options in the console toolbar are toggled by clicking them. The following list describes each of the options in the control bar:

Image Break On Errors—When this is enabled, JavaScript will stop executing if an error is encountered in the script. This is very useful if you want to catch errors and see what the values of things are when they occur.

Image Clear—Clears the messages in the message list.

Image Persist—Retains the messages even if the page is reloaded. If this option is not set, the message list is emptied when the page is reloaded.

Image Profile—Starts and stops the profiler to track time inside code.

Image All—Displays all messages. For the most part, you should leave all messages on unless there are too many and you want to focus on a specific message.

Image Error—Display only error messages.

Image Warnings—Display only warning messages.

Image Debug Info—Display only debug messages.

Image Cookies—Display only cookie-related messages.

Image jQuerify—Modifies the script that loads the jQuery library to include the latest jQuery code. This is part of the FireQuery plug-in.

Notice that in the messages portion in Figure 2.1, there are two types of messages. One is a log statement, and the second is an error. Both show the line number to the right. If you click the line number, you go directly to the code.

Notice in the error message, the top portion of text refers to the error that occurred and the bottom shows the actual JavaScript line. This is useful when debugging because you can often see the problem by looking at the error and the single line of code.

LISTING 2.1 A Very Simple HTML Document with JavaScript Errors


01 <!DOCTYPE html>
02 <html>
03   <head>
04     <meta http-equiv="content-type" content="text/html; charset=utf-8" />
05     <script>
06       fnction loadedFunction(){
07         console.log("Page is Loaded");
08       }
09       function clickIt(){
10         console.log("User Clicked");
11       }
12     </script>
13   </head>
14   <body onload="loadedFunction()">
15     <span onclick="clickItNot()">Click Me</span>
16   </body>
17 </html>


The code in Listing 2.1 is supposed to display the message Page Is Loaded in the console after the page has been loaded in the browser. Another message, User Clicked, is displayed each time the user clicks the Click Me text in the browser. The problem is that the script has several bugs.

With the file now in place, use the following steps to debug the errors using the JavaScript console:

1. Open Firefox and click the Firebug icon.

2. Click the Console tab in Firebug to bring up the JavaScript console shown in Figure 2.2.

Image

FIGURE 2.2 The JavaScript console showing two errors that occurred during the page load.

3. Open the following URL in Firefox to load the newly created web page:

http://localhost/code/hour02/hour0201.html

4. Notice the errors displayed in the console, as shown in Figure 2.2. The first error shows that missing “;” in the definition for loadedFunction(). The second error shows that loadedFunction is not defined. Taking these two errors together indicates that a problem exists with the definition for loadedFunction(). Looking at the failed definition statement, you can see that function is misspelled as fnction.

5. In Aptana, change the word fnction in line 6 to function.

6. Go back to Firefox and refresh the web page. Now in the console you should see Page Is Loaded, the text that is logged in the loadedFunction() function, but no errors.

7. Click the Click Me text. An error is added to the console, as shown in Figure 2.3. The error states that clickItNot is not defined. When you look at the HTML file and search for clickItNot, you can see on line 16 that an onclick event is linked to clickItNot(), but that the JavaScript function is named clickIt().

Image

FIGURE 2.3 The JavaScript console showing one successful log message and one error.

8. In Aptana, change clickItNot in line 15 to clickIt and save the file.

9. Reload the web pages.

10. Click the Click Me Text again. Figure 2.4 shows that both log statements are now displayed correctly and there are no errors. The page has been successfully debugged.

Image

FIGURE 2.4 The JavaScript console showing two successful log messages and no errors.

Debugging HTML Elements

Debugging HTML elements can be a big challenge at times. Simple syntax errors can lead to major problems for the browser when it’s trying to render an HTML document. In addition, HTML elements have property values that are not rendered to the screen but that will affect the behavior of the web page.

The HTML Inspector and the DOM editor help you find and fix problems in your HTML code. The following sections take you through some simple examples of using those tools.

Inspecting HTML Elements

The HTML Inspector enables you to view each of the HTML elements that have been parsed by the browser. This gives you a view of the HTML from the browser’s perspective, which in the case of syntax errors is usually different from the one that was intended, making it more obvious where syntax errors are.

Figure 2.5 shows an example of the Firebug HTML Inspector. With the HTML Inspector, some very useful features are available to you as described next:

Image DOM Tree—This is a simple view into the DOM tree. You can click the + icons to expand parts of the tree and click − icons to collapse parts of the tree.

Image

FIGURE 2.5 The HTML Inspector page in Firebug.

Image Break on Mutate—When this option is enabled, the browser will break into the JavaScript debugger whenever the DOM element is changed dynamically. This helps you catch problems as they are occurring.

Image Edit—When this option is enabled, the tree view changes to a text editor view that allows you to directly edit the HTML code in the browser. The browser changes what is rendered based on the changes you make here. Although this won’t change the code in your project, it is much easier to use this feature to try things out until problems are fixed. Then you can copy the code from the editor and paste it into the actual file in your project.

Image Hover—When you hover over the HTML code in the DOM tree, the element is highlighted in the browser. The hover feature of the HTML Inspector is one of my favorites because it gives a very visual way to see the relationship between the node in the DOM tree and the rendered web page. Notice in Figure 2.5 that as the <h1> element hovered, the heading is highlighted in the web page.


Note

When an element is hovered over in the DOM tree, the element is highlighted on the web page. The hover highlight is color coded, with light blue being the contents, purple being the padding, and yellow being the margin for the HTML element.


Image Bread Crumbs—The bread crumbs show the hierarchy of nodes from the root <html> node down to the one that is currently selected in the tree or edit view. This makes it easy to navigate around, especially in the edit view.

Follow along with these steps to find and fix the HTML syntax problems using the HTML Inspector:

1. Add the code in Listing 2.2 to a new file hour0202.html in the hour02 folder of your project and save the document. You should be familiar with this process by now.

2. Open Firefox and click the Firebug icon to enable Firebug.

3. Open the following URL in Firefox; the web page should look like Figure 2.6.

http://localhost/code/hour02/hour0202.html

4. Click the HTML tab in Firebug and expand the <html>, then <body>, and then <i> tags, as shown in Figure 2.7. Notice that the only element under the <i> tag is a second <i> tag. That isn’t right, so go back to Aptana and look at the <i> tags on line 7 in the HTML. Notice that the / is missing from the closing <i> tag.

Image

FIGURE 2.7 This HTML Inspector shows a second <i> in the DOM.

5. Change the second <i> tag to a closing tag </i> and save the document.

6. Refresh the document in the browser. Notice that the word “Favorite” is now in italic, as it should be, but the bullet point is still missing, as shown in Figure 2.8.

Image

FIGURE 2.8 This web page now has only one problem—no bullet point on the first list item.

7. Go back to the HTML Inspector and expand the <html>, then <body>, then <ul>, then <ll>, as shown in Figure 2.9. Instead of a set of four <li> elements under the <ul> element, there is an <ll> element with the <li> elements underneath. We haven’t covered the HTML tags yet, but if you are familiar with HTML lists, you will recognize that ll is not a valid HTML tag. It should be <li>.

Image

FIGURE 2.9 Viewing the DOM reveals that the browser sees an <ll> tag under the <ul> tag, not a set of <li> tags.

8. Go back to Aptana and change the <ll> tag in line 9 to <li> and save the page.

9. Reload the web page in the browser. It is now displayed properly, as shown in Figure 2.10.

Image

FIGURE 2.10 The properly formatted web page.

Viewing and Editing the DOM

Another important tool when debugging HTML is the DOM inspector. The DOM inspector is extremely powerful. It allows you to view the attributes, properties, functions, children, parents, and everything else about each HTML element in the DOM. The information is displayed in tree form so that you can expand and collapse groups.

The DOM inspector can be found in two places: either by clicking the DOM tab in Firebug or, when you are inspecting HTML, you can click the DOM tab in the HTML Inspector.

Figure 2.11 shows the main DOM inspector. From the main DOM inspector, you have access to a variety of information about the browser environment. For example, in Figure 2.11, the screen attribute of the window object is expanded, revealing the values of the available and actual dimensions of the browser window.

Image

FIGURE 2.11 The main DOM inspector tab in Firebug.

Typically, it’s preferable to use the DOM inspector from the HTML Inspector, as shown in Figure 2.12. When you use the DOM tab in the HTML Inspector, you see only the DOM for that HTML element, which reduces the amount of information that is displayed. It also makes it easy to quickly change attribute values of the HTML element directly in the browser, which makes debugging and developing much easier.

Image

FIGURE 2.12 Editing HTML elements inside the DOM inspector.

Debugging CSS

As part of debugging your dynamic web pages, you also need to be aware of how to debug CSS issues because a lot of the dynamics of web pages deal with modifying CSS layout in the JavaScript.

If your JavaScript or jQuery scripts modify the CSS layout of DOM elements, looking at the code in the web browser will not do you any good. You need to be able to see what CSS the browser has applied to the element. To do this, you need to use a combination of the CSS inspector as well as the layout inspector and style inspector inside the HTML Inspector.

Using the CSS Inspector

The CSS inspector, shown in Figure 2.13, provides access to all the CSS scripts loaded in the web page. There are two drop-down menus at the top of the CSS inspector. The menu on the left allows you to toggle between the following options:

Image Source Edit—Displays the CSS that originally loaded with the web page.

Image Live Edit—Displays the CSS that is currently applied to the HTML elements.

Image

FIGURE 2.13 Editing CSS properties inside the CSS inspector.

The menu on the left provides a list of all the files containing CSS that have been loaded. This enables you to select which CSS document you would like to view and edit.

From the CSS inspector, you also have the capability to edit the CSS. Figure 2.13 shows the editing in process. Notice the disable icon. When you click this icon, that CSS property will be disabled, and the icon will go from red to gray. You can also directly edit the value of the CSS property, as shown in Figure 2.13.

Using the Style Inspector

In addition to editing the entire CSS file, you can view and edit the CSS properties for specific elements from the HTML Inspector. Figure 2.14 shows the Style tab in the HTML Inspector. From the Style inspector, you can view and modify the property values for a specific element.

Image

FIGURE 2.14 Editing CSS properties inside the Style inspector inside the HTML Inspector.

Figure 2.14 also illustrates some important features of the Style inspector. Notice that :hover is selected in the menu. That shows the CSS style that is applied to that element when it is hovered over by the mouse. Also notice that the span:hover selector overrides the background-color setting in the span selector. The entire CSS hierarchy is displayed in the style window so you can see which property values are coming from what CSS selector and which values have been overridden.

Using the Layout Inspector

Another extremely powerful tool when debugging CSS is the Layout inspector in the HTML Inspector. The Layout inspector, shown in Figure 2.15, provides an easy-to-use visual interface to the CSS layout of the selected HTML element.

Image

FIGURE 2.15 Viewing the CSS layout properties inside the Layout inspector inside the HTML Inspector.

From the Layout inspector you can use, view, and modify the following features:

Image Margin—The margin is the outermost box shown in Layout inspector. There is a value on each of the four sides of the margin. You can double-click those values and change the CSS property directly in the Layout inspector.

Image Border—The border is the next box. It also has four values you can change to adjust the CSS border properties of the HTML element.

Image Padding—The padding is the next box. It also has four values you can change to adjust the CSS padding properties of the HTML element.

Image Content—The content is the innermost box in the Layout inspector. It has two values, the length and width, that you change to set the CSS length and width properties of the HTML element.

Image Rulers—The rulers are displayed in the web page to give you a specific size scale to work from.

Image Guidelines—When you select the margin, border, padding, or content box in the Layout inspector, guidelines appear in the web page. The guidelines run horizontally and vertically to show the specific location of the edges of that CSS property. This can be extremely useful when trying to line up elements in your layouts.

Debugging jQuery and JavaScript

You already have learned to look for errors in JavaScript and other scripts in the JavaScript console. What if your script isn’t causing any browser errors, but it just isn’t working the way you want it to? Firebug has a very nice integrated debugger to help you out.

Navigating the JavaScript Debugger

The JavaScript debugger allows you to view the JavaScript scripts that are loaded into the browser with the web page. In addition to viewing the scripts, you can set breakpoints, watch variable values, and view the call stack, just as you would with any other debugger.

Figure 2.21 shows the components of the JavaScript debugger available in Firebug. From the JavaScript debugger, you have access to the following features:

Image JavaScript View—This shows you the actual JavaScript code.

Image

FIGURE 2.21 The Firebug debugger provides code, watch, stack, and breakpoint views.

Image JavaScript Selection Menu—This menu shows a list of the JavaScript scripts loaded with the web page. You can click this menu to select which JavaScript file to load in the view.

Image Break on Next—When this option is selected, the browser will break into the debugger and stop executing the JavaScript on the first line of the next script that is run.

Image Watch—The Watch tab shown in Figure 2.21 gives you a list of functions, variables, properties, and so on that are available at the current execution of the code. This is an extremely valuable window. From here you can see what the values of variables and objects are as the code is executing. In addition, you can add your own expressions to the watch list by typing them in at the top of the watch list. A great feature of the Watch tab is that you can double-click variable values and change the value that is used in execution. This is a great way to test what-if scenarios.

Image Stack—The Stack tab provides a history of the function calls that led up to the currently executing line of code. One of the most valuable aspects of the Stack tab is that you can see the parameter values passed into each function by expanding the function name. You can also click the function name, and that file will be loaded in the JavaScript view and that line of code highlighted.

Image Stack Bread Crumbs—Similar to the Stack tab, these show the stack history and you can click them to load that JavaScript file and function into the JavaScript view.

Image Breakpoints—Breakpoints allow you to specify where to stop when executing JavaScript. When you set a breakpoint, the browser stops executing and breaks into the debugger before it executes that line of code. You set breakpoints by clicking to the left of the line of code in the JavaScript view. They are denoted by a red dot. To remove the breakpoint, click it. The breakpoints tab shows you a list of breakpoints that have been set. You can disable the breakpoint by unchecking the box next to it.

Image Currently Executing Line—The currently executing line of code is denoted by a yellow arrow.

Image Rerun—When you click this icon, the currently executing script is restarted with the same inputs as before.

Image Continue—This allows the script to continue executing normally until hitting another breakpoint if one is encountered.

Image Step Into—When you click this icon, code advances one line. If the line of code is executing another function, you are taken to the first line of code in that function.

Image Step Over—When you click this icon, code advances one line. If the line of code is executing another function, that function is executed and you are taken to the next line of code in the current function. If a breakpoint is encountered when stepping over a function, the browser will stop executing at that location in the script.

Image Step Out—When you click this icon, the current function finishes executing and you are taken to the next line of code in the calling function.

So How Do You Debug jQuery?

A question that comes up frequently, even with people that are experienced with debugging JavaScript, is how to debug jQuery. The answer is simple. jQuery and the numerous plug-ins and versions are just additional JavaScripts. To debug jQuery, download a non-minified version of the jQuery library from the Web and save it in your project. You learn how to do that later in this book.

The reason you download a non-minified version is that the minified is unreadable. Everything is crunched together in one line and doesn’t show up well in the debugger. The non-minified version is formatted in a readable form.


Note

Even if you cannot get a non-minified version of a JavaScript file, you can always open the file in Aptana and select File, Format from the main menu. Aptana will automatically format the file to a pretty, readable form. Most IDEs will have that type of feature.


With the jQuery or any other JavaScript library formatted, you can debug it like any other JavaScript file.

Analyzing the Network Traffic

A very valuable tool available in Firebug that is often used in debugging JavaScript is the network traffic analyzer. The network traffic analyzer, shown in Figure 2.25, is available by clicking the Net tab in Firebug. The traffic analyzer displays information about each request from the browser to the web server. This allows you to get a better understanding about what data is being transferred and if requests are happening at all and in the right order.

Image

FIGURE 2.25 Network traffic required to load amazon.com.

Figure 2.25 shows the traffic involved in loading the amazon.com web page. There are numerous requests, each one represented by a single line in the traffic list. For each request, the following is shown in the traffic:

Image URL—The URL of the request can be very useful. You can right-click the URL and copy it, or even open it in another tab or window. This allows you to debug a single request and not the full web page load.

Image Status—I use the status to determine whether the request was successful and whether it is still running. For example, the web page may not look right because an image request failed to load, which is very easy to diagnose from the Net tab in Firebug.

Image Domain—The domain is interesting, especially if you are dealing with cross-domain scripts.

Image Size—The size may also be useful in that it allows you to quickly find requests that require a lot of disk space and network bandwidth.

Image Remote IP—The IP address the request is going to.

Image Timeline—Shows the time in milliseconds the request took. This is very useful in diagnosing slow-responding web pages and other problems related to speed.

With some complex web pages, you may have too much traffic to try to debug all the requests. The filter options in the Net tab allow you to view only certain types of requests, such as HTML, CSS, or JS. The XHR filter stands for XMLHttpRequest, which is the communication used in AJAX. Selecting the XHR filter will show only AJAX communication.

When you expand a request, as shown in Figure 2.26, you get a lot of additional information about the request. What tabs are available in the expanded request depend on the request type and the response type, but here are some of the most useful items:

Image Headers—Displays the HTML request and response headers that were sent. This is very useful if you are accessing a service via AJAX that requires specific headers to be sent.

Image

FIGURE 2.26 Expanding the request provides additional tabs with more information about the request and server response.

Image Response—This will vary, depending on what the response is. For example, if you are downloading a JavaScript file from the web server, this displays the raw JavaScript.

Image Post—This is available in POST requests and shows you the values of the parameters sent in the POST request to the server.

Image Cache—This shows the cache information, such as the size in the cache, the last time the cache was used, and when it will expire. Many of the perceived issues in debugging JavaScript are due to data that has been cached by the browser, so it doesn’t try to retrieve a fresh copy.


Note

If you click the down arrow on the Net tab in Firebug, there is an option to disable browser cache. This option can be very useful when you are updating files on the web server to debug and fix issues. When this option is checked, the browser will always retrieve the latest from the web server.


Image HTML—Shows a rendered version of the HTML document that was included in the response.

Image Cookies—Displays the cookies and values involved in the request.

Image JSON—Displays the JSON code in an expandable tree form that is easy to navigate. This is useful if you are receiving JSON as the response to an AJAX request. You can view the data that was retrieved from the server.

Summary

In this hour, you learned a myriad of ways to debug problems in your dynamic web pages. You learned how to output messages from your scripts to the JavaScript console. You learned how to use the HTML Inspector to see the HTML elements that the browser has built while loading the web page.

You also followed several examples of debugging problems in HTML, CSS, and JavaScript. The methods you learned throughout this hour will be very helpful to you as you finish this book and in future projects because they will save a lot of time and frustration with simple syntax problems that always seem to creep up.

Q&A

Q. Is there a way to debug server-side scripts?

A. Yes, there is. It is really beyond the scope of this book; however, most good languages have a method of remotely debugging problems. If you are trying to debug PHP server-side scripts, look into the capabilities of ZEND at www.zend.com/en/community/pdt. If you are working with Python server-side scripts, check into using PyDev at pydev.org.

Q. Is there a way to debug cookies?

A. As far as debugging cookies, all you need to really know is whether cookies are enabled, which cookies are set in the browser, what the cookie values are, and when they expire. All of that information can be found in the Cookies tab in Firebug. There are similar features with both Chrome and Internet Explorer in their developer consoles.

Workshop

The workshop consists of a set of questions and answers designed to solidify your understanding of the material covered in this hour. Try to answer the questions before looking at the answers.

Quiz

1. Where do you go in Firebug to find what the background-color CSS property value is for a specific <div> tag?

2. Where would you go in Firebug to see the available size of the browser window?

3. How do you get your JavaScript to stop executing on a specific line of code?

4. When JavaScript execution is halted, how do you find the values of a variable?

Quiz Answers

1. The Style tab of the HTML Inspector with that <div> tag selected.

2. The DOM tab and expand the Screen node.

3. Set a breakpoint in the Script debugger tab.

4. Look in the Watch tab of the Script debugger.

Exercises

1. Modify the hour0204.html code to output the value of cnt to the JavaScript console by adding the following code at line 10.

console.log("cnt=%d",cnt);

2. Use the Net traffic as you browse the traffic from some different pages. Expand some of the requests and look at the data represented in some of the tabs. This can help you understand the ebb and flow of browser to web server traffic a bit better.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset