Created
February 24, 2012 00:12
-
-
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
This file contains 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
// 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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.