Skip to content

Instantly share code, notes, and snippets.

@bgreater
Created February 24, 2012 00:12
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bgreater/1896003 to your computer and use it in GitHub Desktop.
Save bgreater/1896003 to your computer and use it in GitHub Desktop.
jQuery based automatic Google Analytics event tracking for downloads, off-site links & mailto's
// Dependacies: jQuery, ga.js (Async)
(function($){
$(window).load(function() {
if (this._gat) {
// Set trackers
tks = this._gat._getTrackers();
// Remap for mutliple trackers
ga_track = function(p) {
for (i=0; i < tks.length; i++) {
var n = tks[i]._getName() !== "" ? tks[i]._getName()+"." : "";
a = [];
for (i2=0; i2 < p.length; i2++) {
var b = i2===0 ? n+p[i2] : p[i2];
a.push(b);
}
_gaq.push(a);
}
};
// Set Downloads
$('a').filter(function() {
return this.href.match(/.*\.(zip|mp3|mpeg|pdf|docx*|pptx*|xlsx*|jpeg|png|gif|tiff*)/);
}).click(function(e) {
ga_track(['_trackEvent', 'download', 'click', this.href]);
});
// Set Mailto's
$('a[href^="mailto"]').click(function(e) {
ga_track(['_trackSocial', 'email', 'send', this.href]);
});
// Set Outbound (doesn't include sub domains)
var loc = location.host.split('.');
while (loc.length > 2) { loc.shift(); }
loc = loc.join('.');
// exception urls
var localURLs = [
loc, // domain root
'somedomain.org' // outbound exception
];
$('a[href^="http"]').filter(function() {
for (var i = 0; i < localURLs.length; i++) {
if (this.href.indexOf(localURLs[i]) == -1) return this.href;
}
}).click(function(e) {
ga_track(['_trackEvent', 'outbound', 'click', this.href]);
});
} else {
try {
console.log("no GA tracker set");
}
catch (e) {}
finally {
return;
}
}
});
})(jQuery);
@bgreater
Copy link
Author

I was tired of searching for an auto events script for multiple GA trackers so I created my own. Still need to test in multiple Browser but confirmed working in Webkit & Mozilla.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment