Tuesday, May 20, 2008

Inspecting Javascript with Firebug

posted by Alex Grande
1. Go to http://www.alexgrande.com/breakable/ and add the link to your bookmarks.


2. Go to the page you are interested in inspecting and click on the bookmark in your browser called "Inspect JS". That will load breakable.js into the head of the page you are currently using.


3. In firebug go into the scripts tab and view breakable.js.
4. Set a break point on line 7 where it says funct();


5. Find out what the ID is of the element that has the event listener.


6. Click the console tab in firebug. Type in: breakOn("elementID", "eventTrigger"); Example: breakOn("prettyImageOver", "onmouseover"); Example 2: breakOn("ajaxImageChanger","onclick");


7. (1)Initialize the event by mousing over it or whatever you you chose as the event trigger. If the original js author chose a mouse over event then you should also use a mouse over event. Because if you choose an onclick for an onmouseover event then by the time you click it the event has already passed you by..
8. (2)Firebug will transfer over to the breakable.js in the scripts tab at the breakpoint funct(). Step into it by (3)clicking the arrow right in firebug script section.


9. and you will enter into the javascript code of whatever function is called by the event.


I love this! Big thanks to my friend Grady Morgan for writing this short script!

Labels: ,

Thursday, April 10, 2008

Redefining console.log() For Browsers Without Firebug

posted by Jonah Dempcy
Firebug

I use Firebug's console.log() method extensively when developing code. But, when viewing the site in Internet Explorer, Safari, Opera or other browsers that don't have Firebug, console.log() throws an error. Rather than wrap each log statement in a try/catch, I just add this bit of code during development that checks for Firebug and redefines the console.log() method if Firebug isn't installed:

 // When logging messages with console.log()
 // if user doesn't have Firebug, write them to the DOM instead
 if (typeof console == "undefined") {
 
  // Create an unordered list to display log messages
  var logsOutput = document.createElement('ul');
  document.getElementsByTagName('body')[0].appendChild(logsOutput);
  
  // Define console.log() function
  console = {
   log: function(msg) {
    logsOutput.innerHTML += '<li>' + msg + '</li>';
   }
  };
 }

Logging Statements in Production Code

If you don't want to have to remove your console.log() statements in production code, you can set a "development mode" flag that ignores log messages.
var DEVELOPMENT_MODE = true;

// When logging messages with console.log()
// if user doesn't have Firebug, write them to the DOM instead
if (typeof console == "undefined" && DEVELOPMENT_MODE == true) {
 
  // Create an unordered list to display log messages
  var logsOutput = document.createElement('ul');
  document.getElementsByTagName('body')[0].appendChild(logsOutput);
  
  // Define console.log() function
  console = {
    log: function(msg) {
      logsOutput.innerHTML += '<li>' + msg + '</li>';
    }
  };
} else if (DEVELOPMENT_MODE == false) {
  console = {
    log: function() {} // Do nothing
  };
}
I made the flag uppercase since it follows naming conventions for constants. Now you can set the DEVELOPMENT_MODE flag when deploying to production environments and leave your logging messages intact, if you desire.

Take note that this adds unnecessary page-weight from the logging messages, so to fully optimize the code, logging should be removed. But, leaving some amount of logging in the production code is probably acceptable, as long as it doesn't add more than a few kilobytes to the page weight. As long as you're using GZip, minifying your JavaScript and serving it with far future expires headers, a few extra k aren't going to hurt anything.

Redefining All Firebug Methods

If you use other Firebug methods, such as assert(), trace() or error(), then you may want to use the following code, provided by the developers of Firebug as part of the Firebug Lite project.

This code redefines all Firebug methods as empty functions when Firebug isn't installed on the browser:
if (!window.console || !console.firebug) {
  var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
  "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];

  window.console = {};
  for (var i = 0; i < names.length; ++i)
    window.console[names[i]] = function() {}
}

Labels: , ,

Friday, March 21, 2008

Firebug Tutorial: Getting Started

posted by Jonah Dempcy
Firebug is a plugin for Firefox that greatly aids CSS and JavaScript debugging. This guide will walk you through installing Firebug and using some of its functionality, including debugging JavaScript, inspecting the DOM and editing CSS on the fly.

Getting Started

First, make sure you're running Firefox. If you aren't, get Firefox now. You won't be disappointed. Next, install Firebug by following the link and clicking "Install Now." After installing, restart Firefox and continue.

Now you can click the small icon in the bottom right corner of the Firefox window to open Firebug. Go ahead and open it-- the first time running, you may have to choose to enable it for sites on the world wide web.



Using the Console

The first tab that's open in Firebug is the console. The console tab shows JavaScript error messages, as well as having a command line interface (CLI) where you can enter JavaScript and execute it in real time.

Using the CLI, you can call functions, define variables, or even write new functions.

The JavaScript error messages are are also helpful for debugging since they show you which line the error occurred on, as well as a stack trace.

Another interesting feature is the ability to log messages to the console by using the method console.log(). Note that this will throw an error in browsers which don't have Firebug installed, so it's just for development purposes.

Logging messages can be very useful when debugging complex JavaScript applications that have a lot of moving parts. It can also be used for page profiling. Here's an example of how you might use logging to the console to add some rudimentary speed profiling of a JavaScript function:
function doStuff() {
var startTime = new Date().getTime(); // The current time in epoch milliseconds

// Add code here to be profiled

var endTime = new Date().getTime() - startTime;
console.log("The function doStuff() took " + endTime + " milliseconds to complete.");
}
This would result in a message being logged to the console with the amount of milliseconds it took for that code to execute. Nothing fancy, but it gets the job done!

DOM Inspection

Clicking the next tab over in Firebug, to HTML, you'll find a two-paned window that allows you to browse the DOM on the left and edit CSS on the right.

Start opening HTML tags and mousing over them. You'll notice that the HTML element on the screen lights up when you hover over the tag. It's a nice feature that lets you quickly orient yourself in the code.

The highlighted area also shows how much space an element is taking up on the screen. The color blue denotes the element's height and width, while yellow is margin and purple is padding.

Clicking the Inspect button (next to the bug icon in the top left corner of Firebug) will toggle a mode where you can click on HTML elements on the screen and it will go to that tag in the code.

There's another tab for DOM inspection, the aptly-named DOM tab. Here you will find all of the DOM objects created by JavaScript, such as variables and functions, as well as the core DOM API (for example, the window and document objects can be inspected here).

I check this page when I want to view the current state of the page and watch it change as JavaScript executes. For example, say I have a variable that keeps track of how many items are in a shopping cart. I could watch this variable in the DOM tab to make sure that it's incremented when I add an item to the cart.

Editing CSS on the Fly

Going back to the HTML tab, notice that the pane on the right shows CSS styles for whichever element is currently selected. You can choose an element in the left pane (or by clicking Inspect and then clicking the element), and the CSS styles for that element will be displayed. Furthermore, you can edit the properties and even add new ones.

Firebug has a different take on CSS editing than some other debugging programs, namely the Microsoft Web Developer Toolbar, so I'll clarify how it works: In Firebug, when you change a CSS style, it updates it for every element on the page. Conversely, in Microsoft Web Developer Toolbar, changing CSS styles only affects the currently selected element.

By way of example, say you have the CSS rule p {padding: 10px;}. You then select a P tag and change it to padding: 20px; using Firebug. The result is that every P tag will now have 20px padding, unlike other programs where it would only affect the styles of the selected tag.

To add a new style, simply click twice in the whitespace inside of a style block, next to the existing declarations. Firebug even has a convenient auto-complete feature for writing CSS.

In the right page, there are three tabs: Style, Layout and DOM. So far, we've been editing CSS in the Style tab, but make sure to check out the other two as well. The Layout tab offers an alternate view of the box model for the selected element, along with pixel-precise measurements of its dimensions. The DOM tab shows all properties and methods for that element.

Page Profiling and Network Metrics

Nothing's worse than making a great site only to have it suffer from poor front end performance. (OK, well, a lot of things are worse -- but it's still frustrating!). The Firebug Net profiler can help get to the source of that slowness.

Although it is far from robust, the Net tab offers semi-reliable metrics on the download speed of all assets including the HTML document, CSS, JavaScript, images and any other linked files.

You can see which files are being downloaded concurrently and which are blocking (hint: it's the JavaScript), and how many connections are being opened with a given domain.

For more extensive page profiling, be sure to check out YSlow!, a plugin for Firebug (I guess that makes it an extension-of-an-extension) developed by Yahoo.

Labels: ,