Link Tracking in Mixpanel - Mixpanel
Blog Post

Link Tracking in Mixpanel

Last edited: Aug 29, 2022 Published: Oct 8, 2012
Mixpanel Team

To ensure we do not adversely impact the performance of your website Mixpanel uses asynchronous Javascript. This means you’ll never see a browser hang while waiting for Mixpanel.com. However, because our code is non-blocking, track commands which would go in the click handler, like the one below, don’t work.

$("#MyLink").click(function(){
    mixpanel.track("Clicked Link");
})

On the surface, there is nothing wrong with this code. It is very intuitive to add a track event to a click handler. Because the Mixpanel.track call is asynchronous, it begins to execute, but does not block execution of further code. The browser, after dispatching the track continues to follow it’s next instruction, which usually is to follow the href element of the link and change the page. Very often the page will change before the mixpanel.track call has a chance to resolve. The result: No event is tracked.

There are two ways to overcome this. The hard way would be to, within the click event, preventDefault on the click and use the third argument of mixpanel.track (the callback function) to change the page using the window.location object. What a pain! That is why we created a function in our library, mixpanel.track_links, which does this hard work for you. Importantly track_links should not be added to the click handler for a link, but should be called either in document.ready or at least somewhere in your code after link being tracked has been processed.

It would look something like this:

mixpanel.track_links("#MyLink","Clicked Link");

The first argument is a css-style selector for the link you want to track, the second argument is the name of the event. You can even add a third argument for the properties, and this is all documented in the full track_links documentation.

Get the latest from Mixpanel
This field is required.