Skip to content

Instantly share code, notes, and snippets.

@luckyshot
Last active December 12, 2015 12:09
Show Gist options
  • Save luckyshot/4770337 to your computer and use it in GitHub Desktop.
Save luckyshot/4770337 to your computer and use it in GitHub Desktop.
Add target blank and track in Google Analytics to outgoing links
// Add target blank and track outgoing links in Google Analytics
// Method 1 (recommended): Event delegation. Track as Event.
// 'click'
// element and class names (i.e. a.button)
// href value clicked
$('body').on('click', function( e ) {
var target = $(e.target);
if ( target.tag == 'A' )
{
_gaq.push([
'_trackEvent',
'click',
target.tagName + '.' + target.className.replace( ' ', '.' ),
target.getAttribute('href')
]);
}
});
// Method 2a: Inline. Track as Event
$("a").attr('onclick', "javascript:_gaq.push(['_trackEvent', 'Click', $(this).tag+'.'+$(this).className.replace(' ', '.'), $(this).getAttribute('href')]);");
// Method 1b: Inline. Track as Pageview
$("a[href^='http:']").not("[href*='"+document.domain+"']").attr('target','_blank').attr('onclick', "javascript:_gaq.push(['_trackPageview', '/external/'+$(this).attr('href')]);");
// Method 3: Event based (worse performance)
$("a").on('click', function() {
a = attr('href');
if (a.match(/:\/\//)) && a.indexOf(document.domain) !== -1) {
$(this).attr('target', '_blank');
_gaq.push(['_trackPageview', '/external/'+$(this).attr('href')]);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment