Using MooTools and Google Analytics to track outbound links

by keif on October 14, 2008

This seems to be something that people always want to do at some point – are people clicking on my outbound links?

How Google recommends external tracking

They currently recommend you tag your links like:

<a href="" onClick="javascript: pageTracker._trackPageview("/G1/");">

Just as a point of reference – the /G1/ is purely symbolic – you can use the artificial pagename as the Goal URL in your analytics, as google shows:



Kind of tedious, wouldn’t you say? Do you really want to run through your site and specifically tag each link that goes somewhere else? I’ve seen functions attached that basically duplicate this functionality – but if you’re moving the “onclick” into a function, it seems pretty much a moot effort.

So, boom goes the dynamite, and in comes javascript.

Add outbound tracking javascript

This code from Jamie Huskisson accomplishes it simply:
[sourcecode language=’javascript’]
if (document.getElementsByTagName){
var ahrefs = document.getElementsByTagName(‘a’);
for(var i=0;i if(ahrefs[i].href.indexOf('') == -1 && !ahrefs[i].onclick){
ahrefs[i].onclick = function(){
var track = this.href + "pageTracker._trackPageview('/outgoing/'"+track.substring(7));
Nice and succint, as code should be. In this example, it checks to see if we can grab tags - grabs all anchors, and then we check to see if they reference my site and there is no onclick event, and if so - assign the onclick! Technically, you don't necessarilly need the track.substring(7) - you can call it something else if you like.

Do the same – but with MooTools!
As I’m sure you’ve figured it out, I’m a fan of mootools – one of the many well done javascript frameworks. The above code is just as easilly executed:
[sourcecode language=’javascript’]
if ($$(‘a’)){
var href = anchor.get(‘href’);
if(href.indexOf(‘’) == -1 && href.indexOf(‘/’) !== 0) {
anchor.addEvent(‘click’, function(e){
var track = this.href +”pageTracker._trackPageview(‘/outgoing/'” + track.substring(7);
[Edit: It just so happens that David Walsh hit the same topic!]

Comments on this entry are closed.

Previous post:

Next post: