Skip to main content

Click Tracking using JavaScript and Google Analytics - The Good and The Bad

Posted in

I ran into an interesting problem recently, I didn't want to change my links to some sort of URL forwarding script ( to track outbound clicks but I still wanted the outbound click data.

I thought it should be possible using JavaScript and the onClick() functionality. My first inclination was to just go to jquery and bind the click to a function that would simply make an ajax call to record the click data and then forward the user.

Upon further research I found out Google Analytics has this functionality and tracking already built in.

You simply include another javascript snippet:

<script type="text/javascript">
function recordOutboundLink(link, category, action) {
try {
var pageTracker=_gat._getTracker("UA-XXXXX-X");
pageTracker._trackEvent(category, action);
setTimeout('document.location = "' + link.href + '"', 100)

And then for any click you want to track you simply add:

onClick="recordOutboundLink(this, 'Outbound Links', '');return false;"

Outbound Links is the label for the link. It all shows up in the Event Tracking reports in Google Analytics. Simple.

Or so it seemed. I tried this method and some users complained that it broke things like middle click (open in new window) functionality. I am also not convinced it actually worked for every click, my click volume didn't seem to match on the links I did have access to stats on the outbound side for.

So I turned it off and canned the idea for now. I guess that's why facebook, twitter and everyone else seems to use link tracking scripts like l.php and