Created
October 25, 2012 21:06
-
-
Save wellcaffeinated/3955403 to your computer and use it in GitHub Desktop.
One-step outbound link tracking with google analytics
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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); |
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
This can be placed anywhere (even outside domready) as long as jquery has loaded