Update: Tracking outbound clicks with Google Analytics and jQuery
A while back I wrote a post about tracking outbound clicks with Google Analytics; way back then (about 6 months ago), the only event that Google Analytics could track was a pageview. Now that they've introduced the _trackEvent method of the pageTracker object, events that aren't pageviews don't need to count as pageviews anymore; instead, they can be counted as "events," and they can be categorized and labeled. Here's an updated example of how to track outbound clicks using Google Analytics and jQuery. You'll of course need to be including the "new" analytics code (ga.js, not urchin.js) for this to work, as well as the jQuery library.
$('a').click(function() {
var $a = $(this);
var href = $a.attr('href');
// see if the link is external
if ( (href.match(/^http/)) && (! href.match(document.domain)) ) {
// if so, register an event
var category = 'outgoing'; // set this to whatever you want
var event = 'click'; // set this to whatever you want
var label = href; // set this to whatever you want
pageTracker._trackEvent(category, event, href);
}
});var fileTypes = ['doc','xls','pdf','mp3'];
$('a').click(function() {
var $a = $(this);
var href = $a.attr('href');
var hrefArray = href.split('.');
var extension = hrefArray[hrefArray.length - 1];
if ($.inArray(extension,fileTypes) != -1) {
pageTracker._trackEvent('download', extension, href);
}
});8 comments
$('a').bind('click keypress', function(event) { [...]
instead of
$('a').click(function() { [...]
A small upgrade: users may have javascript but, via the magic of the MVP hosts file, (which I highly recommend) Urchin may not load. Therefore, to be clean, I added the following just inside the click callback.
if (typeof(pagetracker) !== "function") {return;}
For reference: Blocking Unwanted Parasites with a Hosts File http://www.mvps.org/winhelp2002/hosts.htm
This file is frequently updated. Don't be fooled by the "2002" in the URL. Don't let family and friends surf the web without it.
If using jQuery at all, it would make sense to want to call pageTracker within a domready, like so:
$(document).ready(function() {
var gaTrackCode = "UA-****";
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
$.getScript(gaJsHost + "google-analytics.com/ga.js", function() {
try
{
pageTracker = _gat._getTracker(gaTrackCode);
pageTracker._trackPageview();
// THIS LINE I will discuss below
}
catch(err)
{
if(window.console) console.log('Failed to load Google Analytics:' + err);
}
}); // end getScript
}); // end ready
Doing that much will get GA to start counting your pages, and will not block the DOM from rendering while GA gets going.
The problem I ran into with calling GA this way was that the "pageTracker" variable is basically undefined outside of that domready callback function.
Even if you try to make pageTracker a global variable inside the domready so that you could try to use it in other functions, or in other domreadys, it will always be "undefined" because of the asynchronous way that the ga.js script is obtained. That is, other functions and other subsequent domreadys will begin executing BEFORE that first domready that is trying to create pageTracker finishes.
This is a problem because you might want to conditionally inject some javascript into the page with server side programming, but dont want to mess up a nice, neat standard original domready.
The solution for me was to use server side programming to create additional javascript functions that can do more stuff to pageTracker (but might not be present on every page of the site), and call that function from inside the getScript callback.
Right at the spot in the above code that says:
// THIS LINE I will discuss below
I would put:
if(typeof gaTransaction == 'function') gaTransaction(pageTracker);
and then stick the following JS anywhere else on the page (either within the same Domready, outside it, in another one, bottom of the page, wherever:
function gaTransaction(pageTracker)
{
try
{
pageTracker._addTrans('order_id',
'affiliate',
'total_amount',
'tax_amount',
'shipping_amount',
'city',
'State',
'country');
pageTracker._addItem('order_id',
'sku',
'product_name',
'category',
'price',
'quantity');
pageTracker._trackTrans();
} catch(err)
{
if(window.console) console.log('Failed to send GA transaction:' + err);
}
} // end function gaTransaction()
Doing that allows me to have a tidy original domready that initiates the standard page tracking cleanly, while still allowing other operations and functions to use the asyncronously obtained "pageTracker" object.
The annoying part is that you do have to keep adding "typof" conditions to the original domready for every new function where you want to do something else with the pageTracker.
Does anyone have any better ideas on how to initialize GA inside jQuery's document.ready function while still allowing use of "pageTracker" in isolated blocks of JS code that might be generated at different points in backend code, for example from different template files?