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="http://www.example.com" onClick="javascript: pageTracker._trackPageview("/G1/example.com");">

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

/G1/example_com

or

http://mysite.com/G1/example_com

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('http://ikeif.net') == -1 && !ahrefs[i].onclick){
ahrefs[i].onclick = function(){
var track = this.href + "pageTracker._trackPageview('/outgoing/'"+track.substring(7));
}
}
}
}
[/sourcecode]
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’]
window.addEvent(‘domready’,function(){
if ($$(‘a’)){
$$(‘a’).each(function(anchor){
var href = anchor.get(‘href’);
if(href.indexOf(‘http://ikeif.net’) == -1 && href.indexOf(‘/’) !== 0) {
anchor.addEvent(‘click’, function(e){
var track = this.href +”pageTracker._trackPageview(‘/outgoing/'” + track.substring(7);
}
}
});
}
});
[/sourcecode]
[Edit: It just so happens that David Walsh hit the same topic!]

Comments on this entry are closed.

Previous post:

Next post: