Using MooTools and Google Analytics to track outbound links

October 14 2008, 9:46am

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="[removed] 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:

if (document.getElementsByTagName){ var ahrefs = document.getElementsByTagName('a'); for(var i=0;i<ahrefs .length;i++){ if(ahrefs[i].href.indexOf('http://ikeif.net') == -1 &amp;&amp; !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:

window.addEvent('domready',function(){ if ($$('a')){ $$('a').each(function(anchor){ var href = anchor.get('href'); if(href.indexOf('http://ikeif.net') == -1 &amp;&amp; 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!] Copyright © 2008 iKeif - tech and social media geek, mootools fan, and a ton of links. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator, the site you are looking at is guilty of copyright infringement. Please contact legal@ikeif.net so we can take legal action immediately.Plugin by Taragana