In one page websites there is.. well, one page. So how do you track user navigation within that single page with Google Analytics?
One option is to use anchors, which can be tracked by Google Analytics by just adding one line of javascript to the tracking code.

But sometimes you also want to track clicks on links that do not navigate to an anchor. For example links that trigger javascript actions, such show/hide of elements

For that, you can use ga’s push function combination with jQuery. Below you’ll find the code for a small jQuery plugin I wrote to track clicks on arbitrary HTML elements:

(function($) {  
  $.fn.ga_track = function() {    
      this.each(function() {
        $(this).click(function() {          
          var pageName = $(this).attr('title') ? $(this).attr('title') : $(this).text();          
          _gaq.push(['_trackPageview', "/" + pageName + ".html"]);
        });
      });
  };  
})(jQuery);

Just copy and paste the code into a javascript file that is included in your HTML.
The plugin can be called within your page with javascript:

$(document).ready(function() {
  $("a[rel='ga']").ga_track();
});

The selector in this example selects all links with the ‘rel’ attribute set to ‘ga’, but you use any jQuery selector. Example use of the rel and title attributes in HTML:

<a href="#contact" title="tracked_page" rel="ga">Click!</a>

For the URL of the virtual page to track, the plugin looks at the value of the ‘title’ attribute of the clicked element. If there is no or an empty title attribute, the inner text of the element is used.

In the example above, a click on the link will show up as a page view of ‘tracked_page.html’ in your Google Analytics reports.

Note that if you want to track outbound links, downloads, etc, you can use event tracking instead. However, you can’t configure goals with events.

3 Responses to “Google Analytics in one page websites”

  1. Hey I’ve implemented this and it’s changed all my url titles to – tracked..”link name”. Can this be edited without sacrificing the tracking?
    I’d like to keep all my original url titles which are keyword enriched.

    1. admin says:

      With the jQuery code above, I guess there are some limitations to the values a title can have. This is because the title is converted into an URL, so if the title already contains an URL, things may go wrong.
      What you can try is to use the javascript escape() function in the _gaq.push line:

      _gaq.push([‘_trackPageview’, “/” + escape(pageName) + “.html”]);

      That way, you can probably use any value in you title.

  1. […] websites A jQuery solution to track clicks on navigational elements in one page websites…. [full post] Gerwert Onderweg Blog javascript / jquerygoogle analyticsjquery 0 0 […]

Leave a Reply





Human Verification