Skip to content

Instantly share code, notes, and snippets.

@zamber
Created April 9, 2014 15:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zamber/4a162cbccf4b4e9eb641 to your computer and use it in GitHub Desktop.
Save zamber/4a162cbccf4b4e9eb641 to your computer and use it in GitHub Desktop.
Track downloads and external links with ga.js
/*
Track downloads and external links with ga.js
Append to your spagetti object container and then just run
self.Analytics.init() at the end of the global init() function.
*/
Analytics: {
init: function () {
var self = this;
self.initAssets();
self.initOutbound();
},
initAssets: function () {
var self = this;
// Always reuse regex objects
var rMatchExtension = /\.(doc.|xls.|ppt.|txt|jpg|png|svg|pdf|zip|rar|exe|wma|mov|avi|wmv|mp3)($|\&|\?)/i;
var $a = $('a').filter(function (i) {
var url = $(this).attr("href");
return ( rMatchExtension.exec(url) ) ? true : false;
});
self.ieFix($a);
// Bind click logging on links
$a.on('click', function (e) {
var extension = $(this).attr("href").split('.').pop();
self.logClick(e, this, 'Download', extension);
});
},
initOutbound: function () {
// Pretty much the same stuff as above but for outbound links
var self = this;
var $a = $('a').filter(function (i) {
return this.host != window.location.host;
});
self.ieFix($a);
$a.on('click', function (e) {
self.logClick(e, this, 'Outbound', 'Click');
});
},
ieFix: function ($a) {
// Wrap contents in <span> so that click event bubbles to <a> on IE
if ( $('html').hasClass('ie') ) {
$a.each(function () {
$(this).wrapInner('<span></span>');
});
}
},
logClick: function (e, elem, type, value) {
var $elem = $(elem);
var url = $elem.attr('href');
var target = $elem.attr('target');
var isTargetBlank = ( typeof target === 'undefined' ) ? false : ( target.trim() === '_blank' );
// e.which == 2 -> middle mouse click, meta -> cmd
var isNewTab = e.which == 2 || e.metaKey || e.ctrlKey || isTargetBlank;
// console.log('Logging', type, value, url);
_gaq.push(['_trackEvent', type, value, url]);
// Check if it's not a new tab and if GA is loaded (Adblock custom lists fix?)
if ( !isNewTab && window._gat && window._gat._getTracker ) {
e.preventDefault();
// Ghostery surrogate mocks _gat and triggers a redirect only on _link
_gaq.push(['_link', url]);
// Pushing a function to _gaq ensures that it gets opened after logging
_gaq.push(function () {
// console.log('Loading', url);
window.location.href = url;
});
};
}
}, // end Analytics
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment