|
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.
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.
if(!window.console) console = {log: function(s) {alert(s);}};
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.