Skip to content

Instantly share code, notes, and snippets.

@iso100
Created January 10, 2013 17:46
Show Gist options
  • Save iso100/4504153 to your computer and use it in GitHub Desktop.
Save iso100/4504153 to your computer and use it in GitHub Desktop.
Outbound link tracking with Google Analytics with special support for opening new tabs
// Track outbound links in GA via events
$("a").on('click',function(e){
var url = $(this).attr("href");
var target = $(this).attr("target");
if (e.currentTarget.host !== window.location.host) {
var newtab;
try {
_gaq.push(['_trackEvent', 'Outbound Links', e.currentTarget.host, url, 0]);
} catch(err) {}
if (target || e.metaKey || e.ctrlKey) { // If there's a target specified or if the user is holding down a new tab key
newtab = true;
}
if (newtab) {
e.preventDefault();
window.open(url, '_blank');
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment