Google Analytics and JQuery
Google analytics is fantastic. Add Jquery into the mix and things get even better.
Want a script that will make sure that links to external sites and documents are tracked in analytics? Then look no further!
- All external links (links that begin with http:// or https://) will concatenate the current url + /outgoing/ + link href.
- All document links (mp3,zip,doc etc) will concatenate the current url + /documents/ + link href.
Stick the following function in an external .js file:
jQuery.fn.trackLinks = function(){
var Url = location.pathname;
var arrayUrl = Url.split(".");
var FileExtensionLength = arrayUrl[arrayUrl.length-1].length + 1;
//log links odd filetypes/downloads
$("a[href$='.doc'], a[href$='.xls'], a[href$='.pdf'], a[href$='.zip'], a[href$='.pps'], a[href$='.ppt'], a[href$='.mp3']").bind("click", function(){
if(pageTracker){pageTracker._trackPageview(Url.substr(0,(Url.length-FileExtensionLength)) + ‘/documents’ + $(this).attr(‘href’));}
});
//log links to external sites
$("a[href^='http://'], a[href^='https://']").bind("click", function(){
if(pageTracker){pageTracker._trackPageview(Url.substr(0,(Url.length-FileExtensionLength)) + ‘/outgoing/’ + $(this).attr(‘href’));}
});
};
var Url = location.pathname;
var arrayUrl = Url.split(".");
var FileExtensionLength = arrayUrl[arrayUrl.length-1].length + 1;
//log links odd filetypes/downloads
$("a[href$='.doc'], a[href$='.xls'], a[href$='.pdf'], a[href$='.zip'], a[href$='.pps'], a[href$='.ppt'], a[href$='.mp3']").bind("click", function(){
if(pageTracker){pageTracker._trackPageview(Url.substr(0,(Url.length-FileExtensionLength)) + ‘/documents’ + $(this).attr(‘href’));}
});
//log links to external sites
$("a[href^='http://'], a[href^='https://']").bind("click", function(){
if(pageTracker){pageTracker._trackPageview(Url.substr(0,(Url.length-FileExtensionLength)) + ‘/outgoing/’ + $(this).attr(‘href’));}
});
};
And then reference it on your page as such:
$(document).ready(function() {
$(document).trackLinks();
});
$(document).trackLinks();
});
Developer by day, husband and dad by night and dreaming about sport inbetween.