How To Write Google Event Tracking Codes with JQuery

Google event tracking works via some code inside the onclick attribute of links. Rather than putting the code inside every link, you can write a few lines of jQuery and have the codes go into every link on your page.  You can set the parameters of the code so each link will be uniquely identified.  You can also set it to know which URL you were on when you clicked the link.  This is useful for tracking links on sites which have shared files such as headers, footers, and sidebars.

Here is the format of the google event tracking code:

[code]
onclick = "javascript: pageTracker._trackEvent('category', 'action', 'label');
[/code]

1. category -
The name you supply for the group of objects you want to track.
2. action -
A string that is uniquely paired with each category, and commonly used to define the type of user interaction for the web object.
3. label -
An optional string to provide additional dimensions to the event data.

This jQuery iterates over each link (a element) within the container. It gets the name attribute and page URL as variables. Then it sets the onclick attribute to each link. The onclick attribute forms the google event tracking code, and it sets the last paramter (the only unique parameter) with a combination of the name attribute (this could be anything you want to uniquely identify the link) as well as the current URL (helpful for tracking).

The most difficult part was passing the variables into the string without it just printing the whole thing as a string. The proper way to do it is this:

[code]"'+$set+url+'"[/code]

[code lang="javascript"]
$(function() {

$("#container a").each(function (i) {
var $a = $(this); // 'this' is the element being iterated
var url = window.location.pathname; //gets current url
var $set = $a.attr('name'); // gets name attributes
if($set) {
$a.attr('onclick', 'javascript: pageTracker._trackEvent("PPC_Landing", "CreditCards", "'+$set+url+'");');
} //creates event tracking onclick attribute, and makes the last parameter set as the name attribute of the link, and current url as an identifier

});

});

[/code]

This entry was posted in Uncategorized, jQuery and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>