Why does a piece of Javascript only work when I have an alert beneath it?

javascript, jquery

Solution

I am going to take a guess and say maybe because you are using an `a` tag and the page is refreshing before the script can do it's job.

The solution for that would be to use `event.preventDefault` in your function like so:

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

By default, an `a` tag will usually navigate to a new page (based on the `href` attribute). If no `href` is set, then it will usually reload the current page. This is a common overlook by most people that are unaware of the `preventDefault` function. But adding this line prevents the link from navigating anywhere.

As @Esailija has said, if all your code within your click function runs synchronously then it would complete fine prior to the page navigation, which suggests that part of it (most like the `.track` call) is running asynchronously - maybe with a timer, or via an ajax call, for example.

Generally, when you find that an alert will fix code, it is likely because something isn't getting enough time to complete. So always look for something that would end the script, this is most likely (and in this case) a page reload/refresh.

If this is not the problem, then 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. Look at this page and scroll down a bit to the `mixpanel.track_links` function.

Problem

I have the following block of code that tracks a click on a button and then records analytics in 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> ``` On its own, activity is NOT being tracked in MixPanel. However, when I add `alert ('added');` beneath the mixpanel tracking code, all of a sudden it works perfectly. Why? Update: since some people asked, the alert was placed beneath the `mixpanel.track` command.

Original source