Use jQuery with Google Analytics to Track Clicks on Outgoing Links From Your Site.

So you have a nice site or blog with lots of links to other places. Wouldn’t it be nice to use the power built into Google Analytics to track those links, without having to add the necessary JavaScript to every link? Here is a very easy way: Add outbound link tracking to a new or existing site. Provided that your links to other sites have the REL attribute set, you can track them very easily with some help from jQuery.

1. Download jQuery and install Goolge Analytics.

Go to jQuery.com and get the latest version. Then add the script include into the header of your site.

Now go to Google Analytics. Set up an account and follow the directions to get tracking running. Go ahead, do it now, I’ll wait. You should now have some script on your site that looks like:

var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js'
type='text/javascript'%3E%3C/script%3E"));

var pageTracker = _gat._getTracker("YOUR ACCOUNT NUMBER HERE"); pageTracker._trackPageview();

2. Add the jQuery to start tracking links.

In the head section of your page, you will need to add a few lines of JavaScript. You will need to setup the jQuery .ready function and add the code to that.

$(document).ready(function(){

});

Next use a jQuery selector to select all a tags on the page with a rel=”external”. To do this, pass jQuery the a tag element with the attribute selector option.

$("a[rel*='external']")

with this we add a click function to our jQuery object.

$("a[rel*='external']").click(function(){

});

With the last part we put in the function call to the Google Analytics code and we pass it the href that our a tag is pointing to.

pageTracker._trackPageview('/outgoing/'+ $(this).attr('href'));

This code makes the call to Google Analytics and passes a page path of “/outgoing/” and the url of where the click was headed. In your Google Analytics under content, you will see pages that start with “/outgoing/”. These are clicks that took people off your site. See below for how it looks in Google Analytics.