Created
August 10, 2011 10:01
-
-
Save smcllns/1136488 to your computer and use it in GitHub Desktop.
Tracking outbound links with Google Analytics
This file contains hidden or 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
< 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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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) {