Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to track anchor tags with Google Analytics

I'm trying to track clicks via Google Analytics that do not result in a new request. Specifically, clicks on tabs that are created via the jQuery UI tabs widget. I'm using the older version of the code ('urchin tracker') and trying to log the clicks like so:

$('.ui-tabs-nav li a').click(function() {
    val = "/tab/" + $(this).attr('href');

    // when uncommented, the following line reports, for example:
    //   /tab/#main
    // as expected.
    // console.log(val);

    res = urchinTracker(val);
});

The same method works, in another instance, whose only significant difference, as far as I can tell, is the lack of a hash (#) symbol in the string. Is that character not allowed in a string tracked by urchinTracker(), or could there be some other cause (other than no-one having clicked on the links!)?

like image 256
Bobby Jack Avatar asked Jul 31 '09 09:07

Bobby Jack


2 Answers

By default, Google Analytics disables tracking anchor tags. To enable it for the legacy tracking code, use the following form:

_uanchor = 1;
urchinTracker(val);

Setting a value to variable _uanchor is the equivalent of calling method _setAllowAnchor when using the latest GA code base. (You find a detailed comparison in the Google Analytics Tracking Code Migration Guide - this link is outdated).

The method _setAllowAnchor is described on the Google Reference Site.

like image 131
viam0Zah Avatar answered Sep 27 '22 16:09

viam0Zah


In short, Google Analytics can't track on-page links containing a '#' character. A click on index.html#foo is treated simply as a click on index.html, with everything after the '#' ignored.

You could consider escaping the '#' character:

$('.ui-tabs-nav li a').click(function() {
    val = new String("/tab/" + $(this).attr('href')).replace('#', '&');

    // when uncommented, the following line reports, for example:
    //   /tab/#main
    // as expected.
    // console.log(val);

    res = urchinTracker(val);
});

In your example, this would record a page view for /tab/?main, which should work fine with Google Analytics.

like image 23
Rob Knight Avatar answered Sep 27 '22 16:09

Rob Knight