Skip to content

Instantly share code, notes, and snippets.

@kevinblake
Last active May 29, 2021 08:24
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save kevinblake/4353977 to your computer and use it in GitHub Desktop.
Save kevinblake/4353977 to your computer and use it in GitHub Desktop.
Fire Google Analytics Events using data attributes for label, action and category fields
var googleDataEvents = {
pageTracker: null,
init: function (document) {
document.find("a[data-ga-label],area[data-ga-label]").click(this.trackLink);
},
trackLink: function (e) {
if (_gaq) {
e.preventDefault();
var l = $(this);
var label = l.attr("data-ga-label");
var action = l.attr("data-ga-action");
var category = l.attr("data-ga-category");
_gaq.push(['_trackEvent', category, action, label]);
if (l.attr("data-ga-nofollow") != "true") {
if (l.attr("target") && l.attr("target") != "") {
window.open(l.attr("href"), l.attr("target"));
} else {
setTimeout("document.location = '" + l.attr("href") + "'", 100);
}
}
}
}
};
$(document).ready(function () { googleDataEvents.init($("html")); });
<a href="http://www.google.com" data-ga-category="My Category" data-ga-action="My Action" data-ga-label="My Label">Link text</a>
<a href="http://www.google.com" data-ga-category="My Category" data-ga-action="My Action" data-ga-label="My Label" data-da-nofollow="true">Link text (don't redirect to the href)</a>
<a href="http://www.google.com" target="_blank" data-ga-category="My Category" data-ga-action="My Action" data-ga-label="My Label">Link text (new window)</a>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment