Skip to content

Instantly share code, notes, and snippets.

@tyre
Created March 4, 2013 06:55
Show Gist options
  • Save tyre/5080506 to your computer and use it in GitHub Desktop.
Save tyre/5080506 to your computer and use it in GitHub Desktop.
// automatically adds JS bindings to attach Google Analytics tracking
//
// defaults
//
// class: ga-track all elements with this class will have
// handlers attached on DOM ready
//
// data-ga-binding: click the binding on which to fire the tracking
//
// data-ga-event: _trackEvent the analytics event send to Google
//
// data-ga-data: the binding a comma-sparated list of properties to
// include with the event
//
// e.g. <a class='ga-track'></a>
//
// This will attach a click handler to the link tag,
// triggering _gaq.push(['_trackEvent','click'])
//
// That's pretty useless, so let's add some more stuff!
//
// <a class='ga-track' data-ga-data='bubbles, billionaire' data-ga-bind='hover'></a>
//
// This will attach a hover handler to the link tag,
// triggering _gaq.push(['_trackEvent','bubbles', 'billionaire'])
//
// Type Checking
//
// The Google Analytics documentation specifies the areguments passed into
// any call to trackEvent:
//
// _trackEvent(category, action, opt_label, opt_value, opt_noninteraction)
//
// category, action, and the optional label are all strings. Since data
// attributes are strings anyway, you don't need to worry about these.
//
// the optional value parameter is an integer, and $.gaTrack will throw an
// error if you try to supply something else.
//
// Similarly, the optional non-interation value (which, if set to true
// indicates that the event hit will not be used in bounce-rate calculation)
// must be a boolean. Pass in anything other that 'true' or 'false' and an
// error will be raised.
//
//
// ================ AJAX ==============
//
// If you are loading elements after DOM-ready, you can add a class to them and call
// dls.gaTrack([array,of,jquery,selectors]) and it will take care of the rest!
//
//
// NOTE: If you are attaching tracking to an element surrounding a link or other element
// which will not propagate events, the tracking will not fire. For example:
//
// <li id='cant-track-this' class='ga-track' data-ga-data='Click, SomewhereElse'>
// <a href='/somewhere-else'>I wish I could be tracked...</a>
// </li>
//
// clicking the a tag will not propagate the click event because it leaves the page
$.fn.gaTrackElement = function(){
var binding = $(this).attr('data-ga-binding') || 'click';
//use on, unless pre jquery 1.7
var trackingFn = $('.ga-track').on ? 'on' : 'bind';
$(this)[trackingFn](binding, function(evnt){
var element = $(this);
var gaEvent = element.attr('data-ga-event') || '_trackEvent';
var gaData = element.attr('data-ga-data');
if(gaData.length){
gaData = gaData.split(/,\s*/);
if(gaData.length > 3){
gaData[3] = stringToInteger(gaData[3]);
if(gaData.length > 4){
gaData[4] = stringToBoolean(gaData[4]);
}
}
} else {
gaData = [binding];
}
gaData.unshift(gaEvent);
_gaq.push(gaData);
});
};
function stringToInteger(str, base) {
base = base || 10;
integer = parseInt(str, base);
if(isNaN(integer)) {
throw new Error('Expected string ' + str + ' to be an integer.');
} else {
return integer;
}
}
function stringToBoolean(str) {
if(str == 'true'){
return true;
} else if(str == 'false') {
return false;
} else {
throw new Error('Expected string ' + str + ' to be true or false.');
}
}
$.gaTrack = function(selectors){
_gaq = _gaq || [];
for (var i = selectors.length - 1; i >= 0; i--) {
var selector = selectors[i];
var trackedElements = $(selector);
for (var j = trackedElements.length - 1; j >= 0; j--) {
var elem = $(trackedElements[j]).gaTrackElement();
}
}
};
dls = dls || {};
$(function(){
dls.gaTrack = $.gaTrack;
dls.gaTrack(['.ga-track']);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment