Skip to content

Instantly share code, notes, and snippets.

@meteormanaged
Created April 8, 2016 20:18
Show Gist options
  • Save meteormanaged/12f59400936e490515710de1aae22db0 to your computer and use it in GitHub Desktop.
Save meteormanaged/12f59400936e490515710de1aae22db0 to your computer and use it in GitHub Desktop.
Simple filtering for Google tags.
var filterClasses = function(ev) {
'use strict';
// Get the classNames associated with the clicked elements and split them into an array at whitespace.
var classes = ev.toElement.className.split(' ');
// Filter those classes for a class containing with 'gtm-'
var filteredClasses = classes.filter(function(thisClass) {
if (thisClass.indexOf('gtm-') !== -1) return thisClass;
else return false;
});
//If it was a match, return the matching classname as a string, otherwise, return false.
if (filteredClasses.length > 0) return filteredClasses[0];
else return false;
};
var gaSend = function(className) {
'use strict';
//Send with the gtm-className as the label.
ga('send', {
hitType: 'event',
eventCategory: 'Links',
eventAction: 'click',
eventLabel: className
});
};
//When the doc is ready.
$(document).ready(function() {
'use strict';
//Watch the document for clicks on body a's (fix in case elements/links are generated later.)
$(document).on('click', 'body a', function(ev) {
//Get the className
var className = filterClasses(ev);
//If it's not false, send it.
if (className) gaSend(className);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment