Wednesday 11 January 2012

Google Analytics: track clicks on #hash anchor links

If on your website you want to treat different page anchors as different pages (e.g. if you load your pages using Ajax), then you need a way to tell GA (Google Analytics) about this. Unfortunately there's no simple settings change you can make in the GA tracking code snippet - you actually have to run some GA code yourself when the event occurs. It turns out this is quite simple:

_gaq.push(['_trackPageview', location.pathname + location.search + location.hash]);

But where do you use this? You could add it to the click event (either in your JavaScript, or in the markup, using the onClick attribute). But if you want a global solution, you need to fire it for all hashchanges. This can be done using the jQuery hashchange plugin:

$(window).hashchange(function() {
    // put any other hashchange magic you might want to do here
    _gaq.push(['_trackPageview', location.pathname + location.search + location.hash]);
});

REFERENCES
http://www.searchenginepeople.com/blog/how-to-track-clicks-on-anchors-in-google-analytics.html

1 comment:

  1. Hello, jackocnr!

    Thank you for showing me that tracking anchor links can be done differently than via events. I have just two questions.

    1)
    My site (www.janfelt.com), on which I want to implement hash tracking,
    runs on WordPress. Is there any way I can make it work with the
    hashchange plug-in? If yes, could you please point me to a guideline for the technically challenged? :-)

    2) Have you tried anchor link tracking for Universal Analytics?

    Thank you very much for your advice!


    Honza

    ReplyDelete