Debugging JavaScript

Last updated on
15 October 2016

Drupal 7 will no longer be supported after January 5, 2025. Learn more and find resources for Drupal 7 sites

If you don't have an IDE that can debug JavaScript for you, then one alternative is the Firefox add-on called Firebug. Firefox now also has inbuilt developer tools, and Chrome similarly has its own set of developer tools.

Firebug can examine scripts and set breakpoints so that the next time the script is run you can stop execution and manually step through it. In addition, Firebug has a command-line feature that can run bits and pieces of code in the page, using any scripts that have been provided by that page. This can be used to examine the DOM data structures or local script variables, or you can test snippets to see what their output will be.

Not only is Firebug great for debugging JavaScript, but also for examining HTML. Firebug automatically takes convoluted HTML code and straightens it out so that the indentation is correct and tags appear correctly. You can use the "Inspect" feature, which allows you to click on any part of the page and see its HTML representation. And Firebug also performs a little magic with CSS code. When you examine an HTML element, it will show all the CSS that applies to it-- even CSS that was overridden by other CSS! Another tab lets you see the layout of the selected block, visually displaying the borders, margins, and padding.

In addition to Firebug, you may also want to use the Drupal for Firebug module, which adds Drupal-specific features to Firebug. As documented on the project page, you'll need to fetch the Drupal for Firebug add-on separately and install it into Firefox.

There is an annoyance when debugging scripts that use jQuery or any similar JavaScript library. While stepping through your code, Firebug will also step into the library files. This can be a nightmare as jQuery-- even when uncompressed-- is hard to read. So a good rule of thumb is to simply step over the jQuery functions during debugging and save yourself a headache.

Help improve this page

Page status: No known problems

You can: