Update: Tracking outbound clicks with Google Analytics and jQuery

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 Google Analytics could track was a pageview. Now that they've introduced the _trackEvent method of the pageTracker object, events that aren't pageviews don't need 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 using Google 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 well as 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);
  }

});

Loading mentions Retweet

Filed under  //  analytics   jquery  
Comments (8)
Posted 1 year ago

Track user clicks on certain links

We recently added a new feature to dailystrength.org, and there was much debate about whether users would use it as we intended. To find out, I wrote a clicktrack ditty that sends some data to the server when a link is clicked. It was somewhat inspired by a post I wrote a while ago about tracking outbound links with Google Analytics and jQuery, but is actually even simpler. I've retooled my clicktrack script to work as a generic, 2.5k plugin, which you can download here.

Usage

To use this plugin, add a distinct classname to all links you would like to track. For example:
this is a link
You can also add additional classes to a link with a distinct prefix — the default prefix is "ct_". These classes will be passed to the server along with other clicktrack data:
this is a link
Then, include the script and a line of code to initialize it in the foot of your page. Note that you must at least pass a URL for the remote (server-side) script that will handle the clicktrack data ("foo.php" in the example below):
type="text/javascript">

$(document).ready(function() { $("a.clicktrack").clicktrack("foo.php"); });
This will pass the following data to a script called "foo.php" on your server:
  • source (string) the URL of the current page
  • target (string) the HREF of the clicked link
  • classes (array) classes on the link that matched the prefix (default prefix is "ct_")

Optional parameters

The only required parameter is the URL of the remote script. However, you can pass a more elaborate configuration object. The options and their defaults are as follows:
var defaults = {
                remote_script: null,
                prefix: 'ct_',
                extraData: null,
                callback: function(){},
                dataType: null,
                sendOnce: true,
                preventDefault: false
        };
  • remote_script the remote script that will handle the clicktrack data. this can be passed as a single, string argument to clicktrack(), or it can be passed as part of the configuration object, but it must be specified
  • prefix the prefix for classnames that should be passed as part of the clicktrack data. defaults to "ct_".
  • extraData additional data that should be passed as part of the clicktrack data.
  • callback function to be executed upon successful execution of the remote script. you'll need to set preventDefault to true for this callback to get executed, and then redirect the user using window.location within the callback as required.
  • dataType type of data you expect to be returned by the remote script. see the jQuery documentation on $.post() for details.
  • sendOnce whether clicktrack data for a given link should be sent just once. defaults to true.
  • preventDefault whether clicks on clicktrack links should be prevented from taking the user to the link destination. defaults to false (links will work as expected by default).

Loading mentions Retweet

Filed under  //  analytics   howto   jquery   plugins  

Showcase related content to keep visitors clicking

I've drummed up a lot of visitors by posting links on dzone and StumbleUpon, but the visitors aren't very sticky -- many will visit the single page I linked to and then move on. Looking at my site exits in Google Analytics, I noticed that my category pages had much lower exit rates than my single post pages. This wasn't exactly a surprise, if I thought about it: a visitor to a single-post might see my list of recent posts, but there was no guarantee that any of them would be related to what they came to the blog to read about. Visitors to category pages, on the other hand, would see a collection of related content. I wanted to give visitors an easy way to see other posts that might interest them, so I just installed the Other Posts from Category plugin. The plugin adds links to posts that are in the same category (or categories) as the main post, and it's very configurable via the Wordpress admin. It didn't make sense to me to just have the list at the end of the post -- visitors might never make it there to discover other items that would interest them. A jQuery one-liner copied the list and put it at the top of the post, too:

$('div.ddop').clone().insertAfter('div.post p.byline');
I'll be watching my pages per visit and site exit metrics to see whether it makes a difference --

Loading mentions Retweet

Filed under  //  analytics   blogging   seo  

Track outbound clicks with Google Analytics and jQuery

Update: Make sure you check out the new _trackEvent method of the Google Analytics pageTracker method. If your analytics account offers event tracking, this is the right way to do it if you don't want your events to count as pageviews. I've written a new post about tracking outbound clicks using the new method. -- Sometimes, you may want to know what outbound links a user is clicking on -- say, if you're linking to an affiliate's site and want to be able to count the clicks you're sending. Google Analytics offers this bit of code to accomplish this:

and says:
Google Analytics provides an easy way to track clicks on links that lead away from your site. Because these links do not lead to a page on your site containing the UTM JavaScript, you will need to tag the link itself. This piece of JavaScript assigns a pageview to any click on a link - the pageview is attributed to the filename you specify.
Two problems here: one, it's Javascript in an onclick tag, which is ugly and bad; two, you've got to add that to every link you want to track. No fun. Progressive enhancement says you should use Javascript to add behaviors that will only work with Javascript. I wanted to add this tracking ability to my blog, to see which outbound links people were clicking on. jQuery to the rescue:
$('a').each(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, add the GA tracking code
    $a.click(function() { 
      pageTracker._trackPageview('/outgoing/' + href);
    });
  }

});
In my case, I wanted to track the post title (if there was one), in addition to the outgoing link's href. So:
$('a').each(function() {
  var $a = $(this);
  var href = $a.attr('href');

  if ( (href.match(/^http/)) && (! href.match(document.domain)) ) {
    $a.click(function() { 
      // get the post title if there is one 
      // and add it to the string for tracking
      var postTitle = $a.parents('div.post').find('h2:first');
      href = href.replace('http://',''); // cleanup for nice GA reports
      href = (postTitle.length > 0) ? postTitle.text() + '/' + href : href;

      pageTracker._trackPageview('/outgoing/' + href);
    });
  }

});
You can use the same method to unobtrusively add tracking code to file downloads:
var fileTypes = ['doc','xls','pdf','mp3'];

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

  if ($.inArray(extension,fileTypes) != -1) {
    $a.click(function() { 
      // get the post title if there is one 
      // and add it to the string for tracking
      pageTracker._trackPageview('/documents/' + href);
    });
  }

});
See Google's help page for more information. Note that this example assumes you're using the new tracking code; you'll have to adjust accordingly if you're using the old tracking code. If you're using the new tracking code, it will look like this:
var pageTracker = _gat._getTracker("UA-XXXXXX-X");
pageTracker._initData();
pageTracker._trackPageview();

Loading mentions Retweet

Filed under  //  analytics   google analytics   howto   jquery   progressive enhancement   seo  

Suspicious StumbleUpon Bounce Rates?

I've been promoting some of my blog posts by submitting them to StumbleUpon, and it's been generating a fair bit of traffic -- my post "How I Learned CSS" has done especially well. I've been watching my site using Google Analytics, and I've noticed that visitors from StumbleUpon have a substantially lower bounce rate than, say, visitors from dzone. So I think, "yay, StumbleUpon" and start submitting anything interesting I write to there. But in poking around in my Google Analytics a bit more, I've also noticed that, on pages that I've promoted through SU, I'm seeing strange navigation patterns: for "How I Learned CSS," 40% of visits to the page came from the page itself (and, as it logically follows, 40% of next pages were the page itself). The page was viewed a total of 4,700 times, but a little more than 2,800 of those pageviews were unique. Since bounce rate basically measures whether a new arrival went to another page before leaving the site, I'm not sure it shouldn't count as a bounce if the second page the user visits is the same as the one they were already on.

I'm not seeing this pattern with pages I don't promote on SU, which makes me curious. SU is clearly driving a ton of traffic to my site; it's just not clear that the traffic is actually resulting in the remarkably low bounce rate that Google Analytics shows. If I took out the 40% of people whose next page was the page they were already on, I'm left with not even 1% of people who went to another, different page on the site before leaving -- and suddenly dzone is looking good again. I did a Google search and didn't come up with much except this, which discusses the importance of bounce rate, and this, which suggests using StumbleUpon to reduce your bounce rate. I'm curious whether anyone else is seeing this, and whether it's actually related to StumbleUpon, Google Analytics, or something else. If I had to guess, I'd imagine that this is a result of people using the StumbleUpon toolbar (since it's not happening in all cases), and maybe the toolbar is pre-visiting the page on the user's behalf to make sure it still exists? Update: See the comments and a more in-depth discussion.

Loading mentions Retweet

Filed under  //  analytics   blogging   bounce rate   google   stumbleupon  

Blog Monitoring 101

I've helped set up a couple of corporate blogs, and -- for corporate bloggers especially -- it can take a little bit of doing to understand your place in the great blog-o-sphere. There is lots of advice out there about how to win friends and influence people with your blog, and I don't purport to know better than everything that's already been written. However, I do have one thing to say to people venturing into the blog waters for the first time: Google is your friend.

Google Blogsearch and Google Reader

To be an active participant in the blogosphere, you need to do more than talk -- you also need to listen. These two tools together provide great insight into what people are saying about topics you care about.
  • Use Google blogsearch to search for terms you care about. Get the URL for the Google Blogsearch feed for each search term (in the left-hand nav of the Google blogsearch page) and add it to Google Reader.
  • See what shows up; pay special attention to contributors who are cited by other contributors.
  • Comment (meaningfully, not gratuitously!) on posts that relate to what you blog about, and include a link back to your blog. If you have a post that's directly related to what someone is writing about, include a link to it.

Google Analytics

I recommend Google Analytics because it provides whole-site metrics, in addition to page-by-page metrics. It's important to understand how visitors arrive at the site as a whole, because visitors can arrive at the same content in countless different ways.
  • Set up a Google Analytics account and add the tracking code to your blog per the instructions.
  • Watch Traffic Sources > Overview to see how traffic arrives at your blog.
  • Watch Traffic Sources > Referring Sites to see which sites are sending traffic to your blog. Consider adding frequent referrers to your blogroll or list of links.
  • Watch Content > Overview to see which posts are doing particularly well or poorly.
  • If you want to make the most of your blogging efforts, monthly metrics reports won't cut it. You'll need to be paying regular attention to analytics information -- especially to referring sites -- to pounce on opportunities and to put out fires.

Loading mentions Retweet

Filed under  //  analytics   blogging   google