Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
This is so you can use the latest Google Analytics set-up code to track outbound links from your site. Requires jQuery.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXX-X']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<script type="text/javascript">
// record the event
function record_ga(link, category, action, label) {
try {
_gaq.push(['_trackEvent', category, action, label]);
setTimeout('document.location = "' + link + '"', 100);
}catch(err){}
}
// add google analytics to all links with http
function add_ga() {
$("a[href^='http']").each(function() {
var href = $(this).attr('href');
var exp = /:\/\/(.[^\/]+)/;
// make sure not to record links to same domain if they contain http unless data-ga attr is there
if (!href.match(document.domain) || (href.match(document.domain) && $(this).attr('data-ga'))) {
if (matches = exp.exec(href)) {
var domain = matches[1];
if ($(this).attr('data-aud')) {
$(this).click(function(){
record_ga(href,"Outbound Traffic - " + $(this).attr('data-aud'),domain,href);
return false;
});
} else {
$(this).click(function(){
record_ga(href,"Outbound Traffic",domain,href);
return false;
});
}
}
}
});
}
// add google analytics event tracking to outbound links when document is ready
$(document).ready(function() {
add_ga();
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.