Shoora
8/11/2014 - 3:39 PM

jQuery plugin to track links using google universal analytics events

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);