How do I log a MixPanel event when a user clicks a link?

cutwithflourish picture cutwithflourish · Dec 28, 2011 · Viewed 10.3k times · Source

I'm trying to log an event in MixPanel when users click a certain type of link. I'm using JQuery to do it unobtrusively and as far as I understand I need to add a callback function to take the user to URL after the event has been logged.

This is the code I'm using:

<script type="text/javascript">
    $("#more-posts").click(function() {
        event.preventDefault();
            mpq.track("More Posts", function(){
                window.location = $(this).attr("href");
            });
    });
</script> 

Unfortunately this neither takes the user to the page nor logs the event, but I see no errors in the Javascript console in Chrome.

Any ideas what the problem may be?

Update: Also tried this code based on suggestions in the comments:

<script type="text/javascript">
    function go_to_link(link) {
        window.location = link;
    } 
    $("#more-posts").on("click", function(event) {
            event.preventDefault();
            mpq.track("More Posts");
            setTimeout("go_to_link($("#more-posts").attr("href"))", 2000);
    });

</script> 

It now redirects to the correct link, but still doesn't log an event.

Answer

alephzarro picture alephzarro · Apr 5, 2012

Mixpanel has recently added a method mixpanel.track_links that does the job.