Tracking Clicks with jQuery and Google Analytics

My WordPress stats plugin stopped tracking clicks on external links the other day. I have no idea why, all the rest is working correctly. What to do? With Google Analytics it’s possible to manually track clicks by adding an onClick attribute in the anchor tag. As if we would do such a thing when there is jQuery…

At the moment I have the code displayed below just under the tracker insertion code, above the closing body tag:

  var localserver = "";
    $(this).attr("target", "blank");
    var url = $(this).attr("href").replace(/^http\:\/\/(www\.)*/i, "");

Of course you need to remember to set the localserver variable to your own domain name.

Note the use of not(). We begin with selecting all anchors, we then filter out all the ones with the kLink style. The reason for that is that those links are Kontera links and we don’t want to track them.

We continue by filtering out all links that begin with because we don’t want to track internal links. Be aware of the explicit use of http, if you are using https the above will naturally not work.

Every external link will also get the blank as their target attribute. I don’t want people to navigate away from the page by mistake and not find their way back 🙂

Next we throw away the http:// – with an optional www part – from the URL because it’s just redundant information, I don’t want to see that stuff in the Analytics backend. Again we use http, I’m pretty sure I don’t link to a single https site and if I do I can accept the full path in those extremely rare cases.

Finally we call the _trackPageview function. If all this works I’ll be able to track these clicks as page views in some external folder. Google says it will take 24-48 hours before I can see any clicks so I’ll keep you updated on how this works out.

22 Aug 2008, Success!

External clicks in Google Analytics

There it is, the proof in all its glory. The click statistics are now accessed through Content -> Content Drilldown -> /external/.

Related Posts

Tags: , ,