Anyone who’s ever needed to implement Google Analytics tracking on their website can understand how truly tedious it is having to add the onClick="_gaq.push(["_trackEvent", "[Event Category]","[Event Action]","[Event Label]"])"
to every link you want to track on your site.
Beyond this, remembering to add the onClick=""
event to each new link added to the site could leave important user interaction data out of your Google Analytics reports.
The need to track user interaction on the sites I maintain compounded with the high frequency new content is added to these sites, prompted me to develop the following code snippet.
Here at Local Wisdom we’re always trying to give back to the community so please sound off in the comments below if you find this script helpful or insightful.
One Script to Track Them All
// 1)=> When the document loads, execute the following.
// 2)=> Add the jQ_TrackThis class to every tag.
//You can name the class what ever you like.
// 3)=>Track the click event of ever item w/ the jQ_TrackThis class.
// 4)=>Capture the current page location.
// 5)=>Capture the value of the HREF attribute for the link that was just clicked.
// 6)=>Capture the value of the title attribute for the link that was just clicked.
// 7)=>Capture the value of the id attribute for the link that was just clicked.
// 8)=>Capture the value of the text between the tags for the link that was just clicked.
/* 9)=>The following statement is used to evaluate the position of a specific string in the links HREF attribute. For example, if you wanted to track all the email link clicks on your site the code below would look like this =>
if(t.indexOf("mailto") > -1) {
_gaq.push(["_trackEvent", "Mailto","[Event Action]","[Event Label]"])
};*/
// 10)=> Push the data to Google Analytics.
1)=> $(document).ready(function(){
2)=> $("a").addClass("jQ_TrackThis");
3)=> $(".jQ_TrackThis").click(function(){
4)=> var e = location.href;
5)=> var t = $(this).attr("href");
6)=> var n = $(this).attr("title");
7)=> var r = $(this).attr("id");
8)=> var i = $(this).text();
9)=> if(t.indexOf("[String To Track]") > -1) {
10)=> _gaq.push(["_trackEvent", "[Event Category]","[Event Action]","[Event Label]"])
11)=> };
12)=> });
13)=>});
On line 9, the sting we evaluate the index of can serve as our "[Event Category]"
.
The if(){}
on lines 9, 10 & 11 can be repeated and modified based on how many different Event Categories you wish to create and track on your site.
The beauty of this script is because it’s all jQuery, the [Event Action]
& [Event Label]
parameters don’t need to be static. You could pass variables you define in the script to these parameters if you like.
Download the script here
The post A Global Google Analytics Event Tracking Script appeared first on Local Wisdom.