Last active
December 15, 2015 18:58
-
-
Save ElliotChong/5307209 to your computer and use it in GitHub Desktop.
Adding Outbound Link Tracking 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
<head> | |
<!-- Rest of the <head> content here --> | |
<!-- Include jQuery --> | |
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> | |
</head> | |
<body> | |
<!-- Rest of the <body> content here --> | |
<script> | |
// Load Google Analytics | |
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ | |
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), | |
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) | |
})(window,document,'script','//www.google-analytics.com/analytics.js','ga'); | |
// Send a pageview event for your domain / GA account | |
ga('create', 'UA-XXXXXXXX-X', 'example.com'); | |
ga('send', 'pageview'); | |
// Listen for clicks from outbound links | |
jQuery("a[href*='http://']:not([href*='" + window.location.hostname + "'])").click(function(e) { | |
// Send a click event with the href as the label | |
try | |
{ | |
ga('send', 'event', 'Outbound Link', 'click', jQuery(this).attr('href')); | |
} | |
catch (err) | |
{} | |
// Delay the page's loading for 100 milliseconds to allow Google time to send the click event | |
setTimeout('document.location = "' + jQuery(this).attr('href') + '"', 100); | |
// Prevent the page from loading | |
e.preventDefault(); | |
}); | |
</script> | |
</body> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment