Fire Google Analytics Events using data attributes for label, action and category fields

Home   »   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")); });
Link text

Link text (don't redirect to the href)

Link text (new window)

Leave a Reply

Your email address will not be published. Required fields are marked *