Shaun Mccran

My digital playground

11
J
A
N
2012

Simple JQuery Google Analytics tracking object

Each time I build a new project I find myself adding in several common objects from a variety of languages. One of those objects is a JavaScript based Google Analytics tracking object.

Rather than embedding individual page tracking or event tracking within each element I prefer to create a JQuery listener to pick up any predefined classes or Id's and action them according to rules contained in the object.

This means I don't have a load of inline analytics code to maintain and I only have one place to create and manage tracking rules.

The object I have evolved over several projects uses a simple JQuery selector to pick up any hyperlinks with a specific identifier ('_tracker'). It then reads the full ID attribute and splits it into a JavaScript Array using a hyphen delimiter.

After that I simply stuff it into a Google Asynchronous analytics call.

view plain print about
1$(document).ready(function(){
2
3    $('a[id|="_tracker"]').click(function() {
4
5        try {
6            var selectedidname = $(this).attr('id');
7
8            var splitelem    = selectedidname.split("-");
9            var category    = splitelem[1];
10            var action    = 'click';
11            var label    = splitelem[2];
12
13                //alert(category);
14                //alert(action);
15                //alert(label);
16            _gaq.push(['_trackEvent', category, action, label]);
17            }
18
19        catch(err)
20            {
21                // any errors?
22                console.log('error = ' + err);
23            }
24
25    });
26
27});

The corresponding hyperlink looks like this.

view plain print about
1<a href="twitter.com/account" id="_tracker-social_links-follow_us_on_twitter">my twitter account</a>

TweetBacks
Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
Tony Miller's Gravatar The one slight problem with this is that console doesn't exist in Internet Explorer 8 and below. The workaround I've seen is:

if(!window.console) console = {log: function(s) {alert(s);}};
# Posted By Tony Miller | 11/01/12 12:04
Shaun McCran's Gravatar Hi Tony,

Good point, the console doesn't exist in most browsers, althought as an aside I found that the console functions now do exist in Internet Explorer 9.
# Posted By Shaun McCran | 12/01/12 01:51
deon34's Gravatar I too do the same thing by embedding with Java Script. Normally Google Analytics comes in Java Script and there is no need to write separate script. Services offers good information about Java Programming. Thanks for posting the good article. Keep posting the good work.
# Posted By deon34 | 07/05/15 22:41
Back to top