Quick tip: tracking link clicks with javascript post

Posted on

You learn something new everyday. On SoccerBlogs.net, I've always tracked click thrus to gauge which posts represent active stories. Previously, I used to redirect clicks through my own url and then redirect to the final destination. This was a little slower for users, and I think its not super kosher from google's point of view. Using Jquery, it was trivial to send a request to my clickthru listener url via XHttpRequest. First, I added the class "clicktrack" to any a tag to record. The first version of my javascript listener was bound to the click event of each link.

\$(document).ready(function(){\ \$('a.clicktrack').click(function() {\ // tell big brother - 'this' is our url to spy on\ \$.get('/clicktrack/' + this + '/');\ return true;\ }); });

I've simplified a bit, since in my real listener I don't use the url but something more specific. The return true is important to make the browser actually go to the clicked link. Today, I noticed a curious behavior. In Firefox, when I used my middle-click button to open a link in a new tab, the XHttpRequest was never made. Turns out, and it makes sense, that middle-clicking on a link does not trigger the link's Click event. I hypothesize that Firefox must copy the url and open a new tab with it. But there is a solution, because middle clicking does trigger the MouseUp event. Changing one line in our Jquery code makes it all work again:

\$(document).ready(function(){\ \$('a.clicktrack').mouseup(function() {\ // tell big brother - 'this' is our url to spy on\ \$.get('/clicktrack/' + this + '/');\ return true;\ });\ });

Categories: Uncategorized

Tags: Javascript, jQuery