Posted by & filed under Programming.

A while back Google added event tracking to Analytics so you could keep track of Javascript and Flash events.  Pretty cool feature.

Being the stat junkie that I wanted to use this to keep track of outgoing clicks on a photography forum of mine.  But I didn’t want to have to go through every link prior to displaying the page.  Seemed like a perfect time for a little bit of Javascript. 

What the code below does is go through every link on the page and checks if it’s a web link and pointing to an external site.  If it is it attaches a pageTracker._trackEvent call to it.  External is used as the event category, the domain name of the link is used for the event, and the page path is used for the label.  That way I can break down stats by each domain, and further break them down by page.

A couple of caveats though…

One, I uploaded this to my forum about 20 minutes ago.  It’s not throwing any errors, but it’ll take until tomorrow to see if Analytics is getting the clicks like I’ve planned.

And two, it requires the PrototypeJS library.  I was already using it on my site so there wasn’t any additional loading needed.  But if you’re not using Prototype is might be worth trying to redo without it.  Probably could do the same with JQuery if you’re using that, although I’ve never used JQuery so am not sure how that would go.

function attachEventTracking() {
var siteHost = location.host.replace(/^http(s?):\/\/(www\.)?/, ”);

var linkList = document.getElementsByTagName(‘a’);

for (i=0; i

Leave a Reply

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