Skip to content

Instantly share code, notes, and snippets.

@wellcaffeinated
Created October 25, 2012 21:06
Show Gist options
  • Save wellcaffeinated/3955403 to your computer and use it in GitHub Desktop.
Save wellcaffeinated/3955403 to your computer and use it in GitHub Desktop.
One-step outbound link tracking with google analytics
(function($, window, document){
$(document).on('click', 'a[href^=http]', function(e){
var $this = $(this)
,url = $this.attr('href')
,newtab = ($this.attr('target') === '_blank' || e.metaKey || e.ctrlKey)
;
window._gaq = window._gaq || [];
try {
window._gaq.push(['_trackEvent', 'Outbound Links', e.currentTarget.host, url, 0]);
if (!newtab) {
e.preventDefault();
setTimeout(function(){
document.location = url;
}, 100);
}
} catch (err){}
});
})(jQuery, this, this.document);
@wellcaffeinated
Copy link
Author

if you aren't using relative paths for internal links, consider adding a class="external" to the external links and use that as the selector

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment