views:

43

answers:

1

In Google's documentation it is said that an event can be tracked in the following way:

<a onclick="_gaq.push(['_trackEvent', 'category', 'action', 'opt_label', opt_value]);">click me</a> 

or older version:

<a onclick="pageTracker._trackEvent('category', 'action', 'opt_label', opt_value);">click me</a>

I was looking with Firebug to the request that are made when a click on a link and I see there aborted request:

http://www.google-analytics.com/__utm.gif?utmwv=4.7.2&amp;utmn=907737223&amp;....

This happens because browser unload all javascript when user navigates to a new page. How in this case event tracking is performed?

Edit: Since one picture can be worth a thousand words... alt text

When I click a link firebug shows me this sequence of requests (here are shown first four, after follows requests to fill page content)

+3  A: 

The problem is that there isn't enough time for the script to finish running before the user is taken to the next page. What you can do is create a wrapper function for your GA code and in the onclick, call the wrapper function and after the GA code is triggered in your wrapper function, set a time out and update location.href with the link's url. Example:

<a href="somepage.html" onclick="wrapper_function(this,'category', 'action', 'opt_label', 'opt_value');return false;">click me</a>

<script type='text/javascript'>
function wrapper_function(that,category,action,opt_label,opt_value) {
  _gaq.push(['_trackEvent', category, action, opt_label, opt_value]);
  window.setTimeout("window.location.href='" + that.href + "'", 1000);
}
</script>

code will vary a bit based on your link but hopefully you get the idea - basically it waits a little bit before taking the user to the target url to give the script some time to execute.

Crayon Violent
amazing, i just had this problem and googled this answer 58 minutes after it was answered. i love how fast SO is!
Ian
It seems to me very cumbersome. Aren't there other ways to do it?
Jenea
Well you can attach the wrapper function with an event listener instead, to keep js out of the anchor tag itself. But it's still the same principle of putting a bit of a delay in before moving the user along to the next page. This is the best solution I have found so far. Of course I'm willing to hear other solutions.
Crayon Violent