I had the challenge of adding Google Analytics tracking code to all the outbound links on a site I’ve been working on. There are hundreds of these links scattered around the site, so rather than try and edit a bunch of links, manually adding onclick handlers in an error-prone fashion, I decided to get lazy and write some code to handle it for me.

First I was thinking about doing some sort of regular expression search and replace throughout the site and database, but that reminded me of CSS3 selectors and their ability to do simple pattern matching. I’ve seen people apply a special style to outbound links this way, so after a few minutes of monkeying around with things, I now have a chunk of jQuery that will automatically track clicks on all outbound links.

Here it is, in a nutshell:


jQuery(function($){

   // Match all anchor tags in the "maincontent" div with
   // urls that begin with "http" but don't contain the
   // string "yourwebsite.com"
   $('#maincontent a[href^="http"]').not('a[href*="yourwebsite.com"]').click(function(){

     try {

     // Get the href url and toss out the "http://"
     var href = $(this).attr('href');
     if ( href.indexOf("://") > 0 ) {

       // Track the page in Google Analytics as
       // "/tracking/outbound/www.somesite.com/foo"
       var outbound = '/tracking/outbound/' + href.split("://",2)[1];
       pageTracker._trackPageview(outbound);

       }
     } catch( e ) {}
   }
}

With this running, all of my internal pages get tracked as usual, and any external links will appear as pageviews that look like “/tracking/outbound/www.somesite.com/foo”.

If you link out to many different pages on several sites, keeping the full site url in the tracking code and building these deep paths is particularly useful. Google Analytics will allow you to drill down into the tree like it was normal content and quickly pull numbers on how many total outbound clicks you received (/tracking/outbound), how many went to www.somesite.com (/tracking/outbound/www.somesite.com), and how many people clicked out to a particular page on the site.

This saved me quite a bit of time and is immensely more flexible than any other outbound tracking method I’ve used. I hope this helps someone else. Drop me a line in the comments if this works out for you.

Update: it looks like I wasn’t the first to do this. An article by Rebecca Murphey shows how to do something similar, while also adding the referring post title to the tracking code. Pretty cool stuff, I must say.