Track outgoing links in Google Analytics

The magic sauce is in using google's hitCallback function to send the browser on it's way after doing it's job. This assumes you are using the latest google "universal" analytics. If you happen to use their classic ga.js script might I suggest upgrading or using segment.io's analytics.js.

For educational purposes let's assume this is your HTML:

<div class="author-meta">
<a href="http://montanaflynn.me">Website</a>
<a href="http://twitter.com/montanaflynn">Twitter</a>
<a href="http://github.com/montanaflynn">GitHub</a>
</div>

Now we must bind a click handler to the links that prevent will prevent the browser from taking off in a hurry before we can grab some data from the element that was clicked and send that off to google for analysis. We also must be sure to give instructions for once the handoff is over in the form of the callback function mentioned above that will take the user away to the links location.

Or if you speak jQuery...

$(".author-meta").on('click', 'a', function(e) {
e.preventDefault();
var url = $(this).attr('href');
var label = $(this).text();
var event = {
'hitType': 'event',
'eventCategory': 'links',
'eventAction': 'click',
'eventLabel': label,
'eventValue': url,
'hitCallback': function() {
document.location = url;
}
};
ga('send', event);
return false;
});