Monday, June 28, 2010

Tracking outbound links (and downloads) in Google Analytics

The question came up recently on how to track outbound links and downloads in Google Analytics.

A quick search revealed quite a bit of info.

I combined ideas and suggestions from a number of places and came up with some jQuery-based code that suits our requirements.

Please note that the following code was extensively based on code/comments from the following:

Many thanks to the authors of the above blogs for their great work!
Please do visit their sites and check out their work.

So, without further delay, here is the code.

$(document).ready(function()
{
   
trackOutboundLinks();
});

function trackOutboundLinks()
{

    // Only hook  'a' tags that do not have a class of 'noLinkTracking'.
    // This allows us to optionally exclude links from tracking
    $('a').not('noLinkTracking').bind('click keypress', function(event)
    {
        // If GA is not initialised, don't bother going any further
        // UPDATE 31oct2009:

        // instead of 'if (pageTracker)', use this instead
        // as it will also work when pageTracker is not defined

        if (typeof(pageTracker) != undefined)
        {
            var href = $(this).attr('href');

            // only do this for external links
            if (this.hostname && this.hostname !== location.hostname)
            {
                // Register an event and give it some meaningful values 
                //for our GA reports
                pageTracker._trackEvent('extenal', 'link', href);
            }
            // Track downloads of specified filetypes
            var fileTypes = ['doc','xls','pdf'];
           
            // Split the filename into period-separated parts
            var hrefArray = href.split('.');
           
            // look at the last one only
            var extension = hrefArray[hrefArray.length - 1];
            // one of those we want to track?
            if ($.inArray(extension,fileTypes) != -1)
            {
                pageTracker._trackEvent('download', extension, href);
            }
        }
    });
}


ps: Comments and/or links to this article are most welcome!

No comments:

Post a Comment