Tracking File Downloads Automatically in Google Analytics with Prototype

I wrote this Javascript after seeing this Google Analytics tip: http://www.google.com/support/googleanalytics/bin/answer.py?answer=55529&topic=11006.

Having onclicks on the anchors in the markup is messy and tedious to maintain. My code dynamically does this. It’s pretty simple. As long as this code is executed after the ‘contentloaded’ event, it will work. Also, the Javascript is dependent on Prototype.

$w(‘mp3 pdf doc txt rtf’).each(function(ext){

  $$(‘a[href$=.’ + ext + ‘]’).each(function(a){

    var pageview = ‘/downloads/’ + a.href.substr(a.href.lastIndexOf(‘/’), a.href.length); /* /downloads/wtf.mp3 */

    a.observe(‘click’, function(){ urchinTracker(pageview); });

  });

});

Leave a Reply