Google Analytics jQuery plugin
We wanted an easier way to add Google Analytics to our pages and our javascript, so I decided to write a jQuery plugin. We use jQuery all the time so it made sense. For now I have only included the basic functionality I know that we need and a bit more that I think could be useful at some point. This plugin is free to download and use.
First I wanted it to be short and sweet to add the page view call and analytics code to the page. Here it is using the jQuery ready event. Place this just before your closing body tag.
$(document).ready(function(){ // Google Analytics, this would use your id. $.ga("UA-######-#"); });
Now that you have this code in place you have already accomplished goal number 1, logging a page view to Google Analytics. Now the next goal I had in mind is related to working with pages that make heavy use of javascript, either for interactivity or ajax requests. I may want to log some of these as page views and some as events. If I decide to go the page view route, I have 3 options.
Option 1: Add the class name: ‘ga-page’ to the a tag.
<a href="/my/link/" class="ga-page">Click Me</a>
When you add the class name to your a tag, it will automatically send a page view to Google Analytics with the value in your href attribute.
Option 2: Manually send the page view to Google Analytics.
$.galog.pageView('track/path');
You can place this in any javascript you may be using.
Option 3: Pass in a selector to page view path map in the settings for the plugin.
$(document).ready(function(){ // Google Analytics, this would use your id. $.ga("UA-######-#", {selectorMap:{'#clickedId':'homepage/view', 'a.someClass':'homepage/view/project'}}); });
Based on the above example, when the user clicked your element with the id of clickedId, a page view will be sent to Google Analytics with a value of ‘homepage/view’ or if the user clicked on the a tag with the class name ‘someClass’ the value ‘homepage/view/project’ would be sent. Going this route allows you to set up all of your page views in one place.
We also wanted to take advantage of the new event tracking API in Google Analytics, so I also added a method to make these calls. Currently these can only be done manually, but it wouldn’t be much work to give these the same options as the page view calls have. If thats something you would like to see, please let me know. Here is an example of logging an event.
$.galog.event('category', 'action', 'optional_label', 'optional_integer_value');
Events can be easier to organize and view in your Google Analytics account. We use them for things that technically don’t count as a page view. This also helps you make your traffic reports more accurate since everything is not treated as a page view. Again, if you find this useful and would like more, please leave us a comment to let us know. Bug reports are welcome too!
