Google Analytics and jQuery, happy together

Google Analytics is great out of the box already, but you can do much more than just registering your page loads. Especially with all these “Web 2.0” sites it can be convenient to not register page loads, but events! In this blog post I’ll show you how you can use jQuery in combination with Google Analytics to get a great insight on what actually happens on your website while you’re not looking!

Tracking Events

With Google Analytics you can track custom events if you like. This gives you the power to register f.e.:

  • Who’s been hovering over my “Buy” button?
  • Who’s been clicking the “Download” link?
  • Who’s been clicking the jQuery.UI.Tab?
  • Who’s been clicking the advertisements?
  • Who’s been clicking on which external links?

The Google Analytics method to register these events is:

pageTracker._trackEvent(category, eventType, optional_label, optional_value) 

optional_label is useful for filtering and optional_value is somewhat special. If you pass an integer to the value parameter, Google analytics will aggregate the value for you. So if you have an ad campaign, you can keep track of how many people clicked the advertisements AND you can see right away how much money you’ve earned with that.

There’s a nice explanation on the _trackEvent method over here: http://code.google.com/apis/analytics/docs/tracking/eventTrackerGuide.html

jQuery Plugin

It’s quit cumbersome however to attach an event handler to all these items on your page. So I’ve created a jQuery plugin to make life easier for you and in it’s simplest form you can use it like this:

$("selector").trackEvent(optional_options);

What this does is that it will call _trackEvent if someone clicks the selected elements once per element. It will use the element nodeName as category variable and the href, value, id or text (first non empty in that order) as label variable. For the value variable it uses 1.

So if my html looks like this:

<script type="text/javascript">
$(function(){
  $("a").trackEvent();
});
</script>

<a href="http://www.virtuelekassa.net">
     ASP.Net iDeal library</a>
<a href="http://www.virtuelekassa.net/downloads/library.zip">
     Download Library</a>

Than if someone clicks the first hyperlink, the event gets tracked like this:

pageTracker._trackEvent("A",
                        "click",
                        "http://www.virtuelekassa.net",
                         1);

If someone clicks the second link, it will be tracked like this:

pageTracker._trackEvent("A",
                        "click",
                        "http://www.virtuelekassa.net/downloads/library.zip",
                         1);

These events will be tracked only once per element click per page load.

External links

This of course can be very helpful in registering how many people navigate away from your web site through external links. So I’ve added an extra filter expression to select all external links on the page. You can use it like this:

$(function(){
    $("a:external").trackEvent();
});

With this in place, all hyperlinks on your web site that point to external web sites get the event tracking behavior.

Flexible

Although the defaults are fine for me, they might not be for you, so the plugin is flexible enough to adjust it to your likings. The optional options variable looks like this:

var settings = {
    eventType : string,
    once      : bool,
    category  : string or function,
    action    : string or function,
    label     : string or function,
    value     : int or function,
};
Example 1

Lets say you would like to track every click on your jQuery.UI.Tab, with:

  • “Tab” as the category value
  • The text of the tab as label value

Your jQuery load function would look somewhat like this:

var eventTrackingOptions = {
    once    : false,
    category: "Tab",
    label   : function(event){ return $(this).text(); }
};

$(function(){
    $("#tabContainer li").trackEvent(eventTrackingOptions)
});
Example 2

Lets say you have a nice picture of your boy- or girlfriend on your page and would like to track every mouseenter AND click on this lovely picture.

Your jQuery load function would look somewhat like this:

var eventTrackingOptions = {
    eventType: "mouseenter click",
    once     : false,
    category : "Predators",
    label    : "My sweet hearth"
};

$(function(){
    $("img.myLoverPic").trackEvent(eventTrackingOptions)
});
Example 3

Lets say you have some advertisements on your page, and you get payed 2 cents on each click. You can now keep track yourself on how much much money you are making like this.

<script type="text/javascript">
var eventTrackingOptions = {
    category: "Advertisements",
    label   : function(event){ return $(this).attr("rel"); },
    value   : 0.02
};

$(function(){
    $(".advertisementLink").trackEvent(eventTrackingOptions)
});
</script>

<!-- some html -->
<ul>
    <li>
        <a class="advertisementLink"
           rel="CompanyOne"
           href="http://companyone.com">Buy here!</a></li>
    <li>
        <a class="advertisementLink"
           rel="CompanyTwo"
           href="http://companytwo.com">Or here!</a></li>
</ul>

The Source

I guess you’re all bored by now and curious about the source… so here it is:

 /** 
  * Version 1.0
  * March 27, 2010
  *
  * Copyright (c) 2010 Wesley Bakker
  * Licensed under the GPL licenses.
  * http://www.gnu.org/licenses/gpl.txt
  **/
(function($) {
    var methods = {
        getOptionValue: function(value, elem, event) {
            if ($.isFunction(value)) {
                value = value.call(elem, event);
            }

            return value;
        },
        getCategory: function() {
            return this.nodeName;
        },
        getAction: function(event) {
            return event.type;
        },
        getLabel: function() {
            var self = $(this);
            if (self.is("a")) {
                return self.attr("href");
            }
            else if (self.is("input")) {
                return self.val();
            }
            else if (self.attr("id")) {
                return self.attr("id");
            }
            else {
                return self.text();
            }
        }
    };

    $.expr[':'].external = function(elem) {
        return (elem.host && elem.host !== location.host) === true;
    };

    $.fn.trackEvent = function(options) {
        var settings = {
            eventType : "click",
            once      : true,
            category  : methods.getCategory,
            action    : methods.getAction,
            label     : methods.getLabel,
            value     : 1
        };

        if (options) $.extend(settings, options);

        this.each(function(i) {
            var eventHandler = function(event) {
                var category = methods.getOptionValue(settings.category, this, event);
                var action   = methods.getOptionValue(settings.action  , this, event);
                var label    = methods.getOptionValue(settings.label   , this, event);
                var value    = methods.getOptionValue(settings.value   , this, event);

                //alert(category + "||" + action + "||" + label + "||" + value);
                pageTracker._trackEvent(category, action, label, value);
            };

            if (settings.once) {
                $(this).one(settings.eventType, eventHandler);
            }
            else {
                $(this).bind(settings.eventType, eventHandler);
            }
        });

        return this;
    };
})(jQuery);

Conclusion

With this straight forward jQuery plugin it’s a piece of cake to keep track of what’s happening on your page while you’re not there.

Cheers,

Wes

No Comments