Site icon Search Engine People Blog

How To Track Clicks On #Anchors in Google Analytics

Last week, a question from a client landed in my inbox, about whether or not it was possible to track clicks on anchors/fragments. Good question! While the vanilla out-of-the-box Google Analytics doesn't do this, a little bit of customization with JavaScript can do the trick.

What Are #Anchors?

In case you're not excited yet, let's do a quick #Anchors 101.

Many websites use named anchors (referenced by using a hashtag, #) to quickly link to specific areas on a webpage. Examples of named anchors you may have seen, are those "Back to Top" links, which link to the top of the page you're currently on.

The code to do this is normally <a href="index.htm#top">Back to Top</a>.

In Analytics, this will trigger a pageview for index.htm by default - not for index.htm#top.

Anchors can also be used for simple navigation to lower sections of a page. Here's one that links to the screenshot section of this blog post.

JavaScript Code

The key to capturing the hashtag is to use the location.hash property.

Old traditional tracking code:

var pageTracker = _gat._getTracker("UA-XXXXX-X");
pageTracker._trackPageview(location.pathname + location.search + location.hash);

New asynchronous tracking code:

_gaq.push(['_setAccount', 'UA-XXXXX-X']);
_gaq.push(['_trackPageview', location.pathname + location.search + location.hash]);

#Anchors in Google Analytics

You should now be able to see clicks on named anchors in the Content Drilldown report.

Without the customized code, we would see 33 pageviews for index.htm (18+8+4+3), and no #section anchors anywhere.

Tracking clicks on anchors allows you to: better understand visitor behaviour; see how they interact with your site; and see what content works.