Tracking Outbound Links Using Google Analytics

Having just set up a new site, called Typography Links on tumblr, I wanted to know how many people actually click on the links to the sites that I post.

Having used tumblr for the first time, I didn’t know of any way to track this, and although I could use a URL shortening service like bit.ly, i’ve never been a huge fan, as they mask the location you are being directed to.

So what I came up with was an amalgamation of two pieces of JavaScript, that seems to have done the trick:


function recordOutboundLink(link, category, action) {
try{
var pageTracker = _gat._getTracker("UA-XXXXXXXX-X");
pageTracker._trackEvent(category, action);
setTimeout('document.location = "' + link.href + '"', 100)
} catch(err) {}
}

$(document).ready(function() {
$('a').each(function() {
var a = new RegExp('/' + window.location.host + '/');
if(!a.test(this.href)) {
$(this).click(function(event) {
recordOutboundLink(this, 'Outbound Links', this.text);
return false;
});
}
});
});

So in short, this code checks through the webpage for any outbound links (you could narrow this down to particular items simply by altering the jQuery selector) and posts an event to Google Analytics, before then forwarding the user on.

My two code sources came from an analytics help article How do I manually track clicks on outbound links? and Open External Links In New Window.

Now, I know that these can be optimised, but to be honest, it seems to work, and I didn’t want to spend too much time developing the code for this tumblr site.

These events then appear in analytics under events, and are marked as ‘Outbound Links’ as that what it was called in the JS.

I’ve certainly found it useful, and I hope that you might too.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>