Wednesday, March 25, 2009

jQuery and Google Event Tracking

A while back I was doing some looking around the net for a solution to easily add event tracking to our websites. I found a great little script that did just that over at blog.immeria.net.

Now, we use a lot of jQuery, it's a tool that I can't believe I was able to live without in the past. If you are doing any kind of work on the web and have not looked into jQuery, you should do so now.

Back to the issue at hand. I wanted to make a jQuery solution that would have the same functionality (basically) as the tool I found at immeria.net. And now, to give back a little I'm going to post my extension to the gaAddons.js here.

Basically what I did was take what the gaAddons.js script does and wrap it in a nice little jQuery plugin that uses the $() selector functionality to add event tracking to all a tags on the page.

It should be noted that this script will only work with the New Tracking Code (ga.js), and not the Legacy Tracking Code (urchin.js). So if your site is still using the old code you will need to update.

The plugin uses the standard jQuery syntax to call. Say I wanted to take all a tags with the class of "trackable" and attach the google event tracking code.

$("a.trackable").gaAddon();

Simple as that. There are a few options that can be passed in:

  • useEventForOutbound

    • Sets whether to use trackEvent or trackPageview to track the click event for regular page links

    • default is true

  • useEventForDownload

    • Sets whether to use trackEvent or trackPageview to track the click event for downloads

    • default is true

  • fileTypes

    • Regex expression to set which filetypes to track downloads of

    • default is /\.(doc*|xls*|ppt*|exe|zip|pdf|xpi)$/i

  • trackInternal

    • Sets whether to track clicks on internal links as well as outbound links

    • default is false

Now, if i wanted to track ALL link clicks on my site, and use trackEvent, I would need to first include jQuery and the gaAddon.js scripts, then in the activate the gaAddon with something like the following:

$("a").gaAddon({ trackInternal: true });

Have a download and tinker jquery.gaAddon.js

Labels: ,