Update: Tracking outbound clicks with Google Analytics and jQuery

Posted

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);
  }
});
You can use the same method to unobtrusively add tracking code to file downloads:
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);
  }

});

Posted

8 comments

Dec 05, 2008
Track outbound clicks with Google Analytics and jQuery | blog.rebeccamurphey.com said...
[...] Update: Tracking outbound clicks with Google Analytics and jQuery [...]
Jan 07, 2009
Demolabo said...
I would recommend using also keypress event to the tracking code as follows :

$('a').bind('click keypress', function(event) { [...]
instead of
$('a').click(function() { [...]

Jan 13, 2009
Steven Black said...
Once again you've created something that's helped me, Rebecca! Thanks.

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.

Jan 21, 2009
A said...
Your code uses jQuery to add tracking to all types of links in the document, but seems to still imply that GA's "pageTracker" is initialized according to Google's standard instructions (straight script before the ending BODY tag) and not also within a jQuery document.ready().

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?

Aug 18, 2009
H. Bulter said...
am gonna try to implement this tomorrow, Rebecca. Thanks!
Aug 26, 2009
8 Tips for Tracking With Google said...
[...] both a goal and an event in analytics. Thanks to  these contributers listed- for this idea — rebeccamurphey , think2loud and [...]
Oct 29, 2009
Vesa Piittinen said...
Wouldn't it be more efficient to match wanted links using a CSS selector?

$('a[href~="http"]').click(function() {}

Noticed that a forum page with hundreds of links got sluggish when matching every single link. After this fix it was back to normal.

Apr 27, 2010
Google Analytics and click-through « Don Zhou's Blog said...
[...] To tweak with JQuery, a post here. [...]

Leave a comment...