track snippets

How to track user actions and custom events with Google Analytics and jQuery

Tagged analytics, google, track, click, jquery  Languages javascript

This is a customization of Rebecca Murphey's script:

$('a').each(function() {
    var $a = $(this);
    var href = $a.attr('href');
    
    if(typeof pageTracker == 'undefined') { return; }

    // Link is external
    if (href.match(/^http/) && !href.match(document.domain)) {
        $a.click(function() {
            pageTracker._trackPageview('/external/' + href);
        });
    } else {
        $a.click(function() {
            pageTracker._trackPageview('/internal' + href);
        });
    }
});

Note that clicks are shown as page views in reports, so you should exclude them from all reports. A future version of Google Analytics will allow you to track events, such as mouse clicks, without affecting page view reporting, see this page on the new event tracking beta feature for more information.

Tracking 404 and 500 with Google Analytics

Tagged 404, 500, analytics, track, google  Languages javascript

New Google Analytics

_gaq.push(['_trackEvent', 'HTTP status', '404', '/xxx/what-a-fish']);

Old Google Analytics

Tracking 404 and 500 errors with Google Analytics is documented here, but I tend to forget so I'm putting the information here:

// 404
pageTracker._trackPageview("/404.html?page=" + document.location.pathname + document.location.search + "&from=" + document.referrer);

// 500
pageTracker._trackPageview("/500.html?page=" + document.location.pathname + document.location.search + "&from=" + document.referrer);

Rails

In Rails use the response status code to track any HTTP errors:

<% if response.status != 200 %>
_gaq.push(['_trackEvent', 'HTTP status', '<%= response.status %>', '<%= request.fullpath %>']);
<% end %>