Why does the Javascript part only work when I have a warning under it?

I have the following block of code that tracks the click of a button and then writes analytics to the mixpanel.

<script type="text/javascript"> $('.buy').click(function() { var myPart = $('#part-name').text(); var myDistributor = $(this).closest('tr').children('.distributor').text(); mixpanel.track("Buy Part Link", {"PartName": myPart, "Distributor": myDistributor}); }); </script> 

By itself, activity is not tracked in MixPanel. However, when I add alert ('added'); under the mixpanel tracking code, it suddenly works great.

Why?

Update: as some people asked, a warning was placed under the mixpanel.track command.

+6
source share
1 answer

I'm going to guess and say maybe because you use the a tag and the page is refreshed before the script can do the job.

The solution for this would be to use event.preventDefault in your function, for example:

 $('.buy').click(function(event) { event.preventDefault(); //the rest of your code }); 

By default, the a tag will usually jump to a new page (based on the href attribute). If href not set, it usually reloads the current page. This is often found by most people who are unaware of the preventDefault function. But adding this line prevents the link from moving anywhere.

As @Esailija said, if all your code in your click function works synchronously, then it will finish the fine before navigating the page, which means that part of it (most similar to calling .track ) works asynchronously - perhaps with a timer or with calling ajax for example.

Typically, when you find that a warning will correct the code, it is most likely because something is running out of time. Therefore, always look for something that would end the script, it is most likely (and in this case) reload / refresh the page.

If this is not a problem, we may need to see some of your HTML to help further.


Due to your comments that you still want to navigate, I did a very quick Google search and the documentation tells you how to handle links. Take a look at this page and scroll down a bit to the mixpanel.track_links function.

+12
source

All Articles