How To Track Anchor Tags in Google Analytics

In most cases, installing Google Analytics to track your website’s traffic is as simple as copying and pasting the following tracking code:

(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),

ga(‘create’, ‘UA-XXX-X’, ‘’);
ga(‘send’, ‘pageview’);

The Problem

The above code is a simple example of the Universal Tracking code that Google Analytics uses to track each page view. Each time the page is loaded, the script sends a notification to Google to track the page view along with various other information. This however poses a problem for parallax or single-page websites as the tracking code does not track the users clicks on the anchor tags that they use to scroll through the page.

The Solution

Until Google updates their analytics to take this issue into consideration, we’ll have to hack the code a little. We’ll start by editing the following two lines in the analytics code:


ga('create', 'UA-XXX-X', '');
ga('send', 'pageview');


ga('create', 'UA-XXX-X', {'allowAnchor': true});
ga('send', 'pageview', { 'page': location.pathname + + location.hash});

By adding in the following code, we are telling Google Analytics to track the entire URL including the anchor tag, we can link users directly via an anchor, and it will be added to the statistics. This however does not solve the issue of users clicking on the menu links that scroll through various other content on the page. As mentioned previously, the tracking code is sent to Google once when the page is loaded. To fix this, we simply add the following javascript code to the footer of the page:

<script type="text/javascript">
jQuery(document).ready(function () {
jQuery('.menu a').click(function(){
var match = jQuery(this).attr('href').match(/#\S+/);
ga('send', 'pageview', location.pathname + match[0]);

By doing this, we’re telling the browser that each time a link within the class of “menu” is clicked, send a notification to Google Analytics with the anchor tag.

Google Analtics Anchor Tag

Questions? Comments? Leave a note in the comments below or reach out to us for any of your marketing technology needs. Follow us on LinkedIn and Twitter for more nonprofit marketing tips.