Skip to content

Instantly share code, notes, and snippets.

@smcllns
Created August 10, 2011 10:01
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smcllns/1136488 to your computer and use it in GitHub Desktop.
Save smcllns/1136488 to your computer and use it in GitHub Desktop.
Tracking outbound links with Google Analytics
< script type = "text/javascript" >
(function($) {
$(function() {
$('a[href^="http"]:not([href*="' + document.domain + '"])').click(function(e) {
// When a user clicks an external link
if ($(this).attr('target') !== '_blank') {
e.preventDefault();
// If the link is not set to target='_blank'
// set a 300ms delay before loading this page
// which allows Google Analytics to register the event
(function(a) {
setTimeout(function() {
document.location = a.attr('href');
},300)
})($(this));
}
// Track URL and nearest element with an ID
// and send to Google Analytics
window.pageTracker ? pageTracker._trackEvent('Outbound', $(this).attr('href'), "#" + $(this).closest('[id!=""]').attr('id')) : _gaq.push(['_trackEvent', 'Outbound', $(this).attr('href'), "#" + $(this).closest('[id!=""]').attr('id')]);
});
})
})(jQuery)
< /script>
@amrtn
Copy link

amrtn commented Feb 21, 2015

This will redirect a user clicking with the middle button and expecting the link to be opened in a new tab/window.

The line
if ($(this).attr('target') !== '_blank') {

should be:
if ($(this).attr('target') !== '_blank' || e.which != 2) {

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