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&utmn=907737223&....
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...
When I click a link firebug shows me this sequence of requests (here are shown first four, after follows requests to fill page content)
This problem is answered in Google's documentation:
use
or
This more or less the same as the answer from Crayon Violet, but has a nicer method name and is the official solution recommended by Google.
As above, this is due to the page being
unloaded
prior to the Async call returning. If you want to implement a small delay to allowgaq
to sync, I would suggest the following:First add a link and add an extra class or
data
attribute:Then add into your Javascript:
I don't really condone this behavior (e.g. if you are going to another page on your site, try to capture the data on that page), but it is a decent stop-gap. This can be extrapolated not just for
click
events, but also form submits and anything else that would also cause a page unload. Hope this helps!I had the same issue. Try this one, it works for me. Looks like that ga doesnt like numbers as a label value. So, convert it to string.
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:
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.
Update: This answer was posted several years ago and quite a lot has happened since then, yet I continue to get feedback (and upvotes) occasionally, so I thought I'd update this answer with new info. This answer is still doable but if you are using Universal Analytics then there is a hitCallback function available. The
hitCallback
function is also available to their traditional_gaq
(ga.js) but it's not officially documented.