Question

I'm using jQuery to attach onClick events to certain elements on the site, depending on whether the element exists, example:

$(document).ready(function() {
  if ( $("#webform-client-form-15897").length ) {
    $("#edit-submit")
      .attr("onClick", "_gaq.push(['_trackPageview', '/feedback-submitted'])");
  }
});

This works splendidly for things such as a Submit button on a form, and I'm able to track Goals via the fake pagevisit (Events don't allow this, hence the fake trigger).

Problem is, when I've set similar onClick events to Anchor HTML elements, that take the user out of the site, I'm not seeing anything appear on our analytics, even though using same code to attach for example an alert("foo") event shows its clearly working and I get a popup.

Here is how the actual anchor element looks like after being processed with jQuery:

<a href="http://www.example.com/foo" onclick="_gaq.push(['_trackPageview', '/ad-clicked'])">Anchor text</a>

What am I doing wrong, since I've seen this example used on a few tutorials and the code IS executing as far as I can track it with breakpoint and alert() tests?

Was it helpful?

Solution

The problem is usually always because there is not enough time for the GA code to execute before the user is taken to the next page. This isn't a problem if the link opens a new window (target="_blank") because the original page is still there and the code can finish loading. The common way to handle this is to use settimeout to delay the redirect a little, to give time for the GA script to execute. You can go to the link below for details on implementation.

http://www.google.com/support/analytics/bin/answer.py?hl=en&answer=55527

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top