Skip to content

Instantly share code, notes, and snippets.

@JacobDorman
Last active April 22, 2019 09:55
Show Gist options
  • Save JacobDorman/f8a9b3411c875287d9df to your computer and use it in GitHub Desktop.
Save JacobDorman/f8a9b3411c875287d9df to your computer and use it in GitHub Desktop.
jQuery plugin to track links using google universal analytics events
// Google Analytics Event Tracking
(function ($) {
$.fn.trackLinkEvent = function (options) {
var settings = $.extend({
category: '',
action: $(this).attr('href'),
label: document.location.pathname + document.location.search
}, options);
this.click(function (ev) {
var href = $(this).attr("href");
var target = $(this).attr("target");
var afterSend = null;
if (!target || target.match(/^_(self|parent|top)$/i)) {
// register safety net timeout
var t = setTimeout('window.open("' + href + '", "' + (!target ? "_self" : target) + '")', 250);
afterSend = function () {
// clear timer and open link
clearTimeout(t);
window.open(href, (!target ? "_self" : target));
};
ev.preventDefault ? ev.preventDefault() : ev.returnValue = !1;
}
// send data to GA
ga('send', {
'hitType': 'event',
'eventCategory': settings.category,
'eventAction': settings.action,
'eventLabel': settings.label,
'hitCallback': afterSend
}
);
});
return this;
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment