Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Update: Tracking Outbound Clicks With Google Analytics And jQuery

DZone's Guide to

Update: Tracking Outbound Clicks With Google Analytics And jQuery

· Web Dev Zone ·
Free Resource

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

A while back I wrote a post about tracking outbound clicks with Google Analytics;way back then (about 6 months ago), the only event that GoogleAnalytics could track was a pageview. Now that they've introduced the _trackEventmethod of the pageTracker object, events that aren't pageviews don'tneed to count as pageviews anymore; instead, they can be counted as"events," and they can be categorized and labeled.

Here's an updated example of how to track outbound clicks usingGoogle Analytics and jQuery. You'll of course need to be including the"new" analytics code (ga.js, not urchin.js) for this to work, as wellas the jQuery library.

$('a').click(function() {
var $a = $(this);
var href = $a.attr('href');

// see if the link is external
if ( (href.match(/^http/)) && (! href.match(document.domain)) ) {

// if so, register an event
var category = 'outgoing'; // set this to whatever you want
var event = 'click'; // set this to whatever you want
var label = href; // set this to whatever you want

pageTracker._trackEvent(category, event, href);
}
});

You can use the same method to unobtrusively add tracking code to file downloads:

var fileTypes = ['doc','xls','pdf','mp3'];

$('a').click(function() {
var $a = $(this);
var href = $a.attr('href');
var hrefArray = href.split('.');
var extension = hrefArray[hrefArray.length - 1];

if ($.inArray(extension,fileTypes) != -1) {
pageTracker._trackEvent('download', extension, href);
}

});

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}