Google Event Tracking with jQuery

As with lots of little bits of code, if they are useful, you may write and re-write them a several times in several projects before you take the time to package them up into a reusable chunk. That finally happened to me around Google Analytics Event tracking.

Almost every project that I’ve been on in the past year has added Google Analytics (simple page tracking) right up front, and then near the end of the work, realized that they also want event/click tracking. On this last project, I decided to make it right, and package it up.

I’ve built a jQuery plugin (https://github.com/rcode5/ga_event_tracker) that makes it easy to setup click tracking all over your site. The event tracker takes 3 parameters: category, action, and label. The plugin will either find these values as attributes on the tracked DOM element (using data-category, data-action and data-label), or use values passed in when the plugin is initialized, or evaluate functions passed in on initialization. This allows for a lot of flexibility. We were able to setup tracking for most pages on a full site with a couple lines of Javascript.

Assuming you add the class ‘trackit’ to every element you want tracked, you can have something like this:

  $('.trackit').gaEventTracker();

And clicking all those elements will get tracked using the values found in the element attributes “data-category”, “data-action”, and “data-label”.

The source is available on Github with a few more examples. A test suite is included, in case you want to add your own extras and submit a pull request.

I hope this saves you a little time down the road, as I’m sure it will for me.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s