Skip to content

Instantly share code, notes, and snippets.

@pmkhoa
Forked from bgreater/ga-auto-events.js
Created August 4, 2014 17:07
Show Gist options
  • Save pmkhoa/8c29dfe3a419d7877a84 to your computer and use it in GitHub Desktop.
Save pmkhoa/8c29dfe3a419d7877a84 to your computer and use it in GitHub Desktop.
// 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