November 12, 2010
Did you know you can track custom events with Google Analytics? It’s true; you can. It’s easy. Just take your Google Analytics asynchronous queue object,
_gaq, and push an array onto it:
_trackEvent is the method,
accounts is the category,
signup is the action, and
homepage is the label. There is an additional parameter we can provide,
value, if our event has a numerical value that we’d like to view in aggregate later on.
Typically, you’d set this up to happen upon a certain user action. For example, using jQuery:
When a user submits the signup form, we track the event in Google Analytics.
The stock Google Analytics snippet contains a call to
_trackPageview. On typical web pages we call this function once, for each page the user loads in their browser. On fancy single-page apps that navigate based on the URL hash, we may want to track each hash-based navigation as a pageview. In a Sammy app, for example, we could do this using the
Now we’re tracking navigation within the single-page app: our after function is called each time the user navigates to another route in the Sammy app. Simple!
For more detail, check out Google’s trackEvent reference. Also, be sure to read Mathias Bynens’ excellent post on optimizing Google’s stock analytics snippet. Mathias also does an excellent job demystifying the the
_gaq object. One last thing: check out custom variables. This feature is an excellent way to keep track of different categories of visitors. At Paperless Post, we use custom variables to help us understand the behavior of anonymous visitors versus logged in users.