Dejay Clayton

RSS
Sep 8

JavaScript for Maniacs: Debugging JavaScript

While developing and executing your JavaScript code, you’ll frequently need to examine the state of JavaScript variables and web page elements in order to ensure proper functionality. There are several ways to get your JavaScript code to communicate with you. This lesson covers the most convenient and effective options available to developers.

Welcome to my series, JavaScript for Maniacs. Here, I’ll lead you through basic and advanced JavaScript features in a concise manner, exploring ways to bend and twist the JavaScript language to accomplish clever and crazy results that most programmers haven’t considered.

Coding from the Address Bar

One of the really neat and useful features of JavaScript is the ability to execute code from the address bar. Type the following code into your browser’s address bar, and press Enter:

javascript:alert ("hello!");

This feature executes JavaScript immediately, and within the context of the current web page, allowing us to quickly debug problems with our own, and even other, web pages.

To execute multiple statements at once, separate them with a semicolon:

javascript:alert ("hello"); alert ("goodbye");

If the JavaScript that is executed from the address bar returns a value, most browsers will replace the content of the current web page with the returned value. For example, type the following JavaScript into the address bar:

javascript:document.body.style.backgroundColor="red"

This JavaScript sets the background color of the current web page to red. However, immediately after, the browser then replaces the current web page with the returned value of the assignment, in this case:

red

This happens so fast that you can’t see the original web page being modified at all. To prevent JavaScript statements from overwriting the current web page with a return value, append “; void 0” as the last statement:

javascript:document.body.style.color="yellow";document.body.style.backgroundColor="red"; void 0

This has the desired effect of preserving the contents of the current web page. Note that using void is not necessary with JavaScript statements that do not return a value, such as the alert method. The current web page will not be overwritten.

For single JavaScript statements, you may also place the statement within the parentheses of the “void” method:

javascript:void (document.body.style.backgroundColor="red")

Inspecting Elements with “getElementsByTagName”

It is often useful to inspect or modify a page’s DOM elements when debugging JavaScript. The method document.getElementsByTagName returns an array of DOM elements that match the specified tag name. For example, to draw a one-pixel solid red border around the first paragraph in a document, use:

javascript:document.getElementsByTagName ("p")[0].style.border="1px solid red"; void 0

Inspecting Elements with “document.getElementById”

Similarly, the method document.getElementById returns the DOM element whose ID attribute matches the specified ID:

javascript:document.getElementById ("mainContent").style.border="1px solid red"; void 0

Remember that according to HTML rules, there must only be one DOM element with a given ID attribute value within a web page.

Bookmark It to Bookmarklet

You can even save javascript: URLs as bookmarks! Bookmarks that contain JavaScript are known as bookmarklets [1], and are incredibly powerful, capable of executing any logic allowed by JavaScript. For example, the following bookmarklet allows the user to edit the text of any web page:

javascript:document.body.contentEditable = 'true'; document.designMode='on'; void 0;

It’s worth noting that several browsers limit the character length for bookmarks; thus, any bookmarklet that you create may be limited likewise.

Marklets.com [2] and squarefree.com [3] both contain a nice collection of handly bookmarklets, including those to facilitate web design and JavaScript development.

JavaScript Statements within a Web Page

A common strategy, although not very modular, is to embed feedback mechanisms directly within the JavaScript source code of a web page. Some web sites only enable JavaScript debugging output within non-production environments used for development and testing, with the corresponding debugging output statements disabled or removed from the code by automated tools when deployed to a production environment.

Getting Feedback with “alert”

One of the simplest methods of displaying output from JavaScript is to use the alert method:

alert ("Text to display");

Note that you can only display one alert at a time, and it can be tedious to dismiss a large number of alerts. This is especially true when iterating through loops, arrays, and objects.

Getting Feedback with “document.write”

JavaScript provides the ability to write text or HTML content to the current window:

document.write ("Text to display");

or:

document.write (
    "<html><head><title>Title</title></head>" +
    "<body>HTML to display</body></html>");

JavaScript also provides the ability to write text or HTML content to a new window:

open (null, "Window Title").document.write (
    "Text to display");

Getting Feedback with “console.log”

The Google Chrome [4] browser, Apple Safari [5] browser, and the Firebug [6] development add-on each support the method console.log, which writes text to the JavaScript console:

console.log ("Text to display");

This is a convenient method for outputting information from your JavaScript code during execution, without resorting to intrusive alerts and such.

Developing with Browser Tools

Nearly all contemporary browsers provide developer tools that offer extensive JavaScript and HTML development and debugging features, such as the ability to inspect HTML page elements and JavaScript code. In both the Google Chrome browser and Microsoft Internet Explorer [7] browser (versions 8 and above), these tools are accessible from the “Tools/Developer Tools” menu item. In the Mozilla Firefox [8] browser, you can install the fully-featured Firebug development add-on, or the simpler but less-featured DOM Inspector [9].

Anyone who has more than a passing interest in JavaScript must learn these tools in order to be an effective web developer. I leave that as an exercise to readers.

References

1. “Bookmarklet”. Wikipedia, The Free Encyclopedia. http://en.wikipedia.org/w/index.php?title=Bookmarklet&oldid=434261056

2. marklets.com. http://www.marklets.com/

3. Jesse’s Bookmarklet Site. http://www.squarefree.com/bookmarklets/

4. Google Chrome. http://www.google.com/chrome/

5. Apple Safari. http://www.apple.com/safari/

6. Firebug. http://getfirebug.com/

7. Microsoft Internet Explorer. http://www.microsoft.com/windows/internet-explorer/default.aspx

8. Mozilla Firefox. http://www.mozilla.org/en-US/firefox/new/

9. DOM Inspector. https://addons.mozilla.org/en-US/firefox/addon/6622