How to use a variable in Google Analytics' Custom Variable

google-analytics, html, javascript, jquery

Solution

It looks like you just need to change the order of a couple of lines--in particular, your Custom Variable must be set before _trackPageview is called.

The trackPageview() call aggregates the analytics data from various sources (cookies, location bar, request headers, DOM ), concatenates it and sends it to the Google Analytics servers in the Request Header (for the _utm.gif). So if your Custom Variable is not set when this function is called, it is not logged by GA.

In this case, the value of your Custom Variable is triggered by an event (e.g. user clicking a button on the page), so just call _setCustomVar() when the event fires. E.g.,

<input type="button" name="National Link", value=[dynamically set], onclick="my_function()", 2>

*my_function() of course, calls _setcustomVar*

Problem

I'm trying to track a particular section of links on my page. I want to know what is clicked, so I'm trying to set up a click handler with jQuery to register a custom variable with Google Analytics, but it's not working. Here's my code: ``` <!--Google Analytics--> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-18698622-1']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); $(function(){ $('a.link-item.bullet').click(function(){ _gaq.push(['_setCustomVar', 1, 'National Link', $(this).text(), 2]); }); }); </script> ``` It's been about 3 or 4 days, and I haven't seen any custom variables register yet. Maybe I can't have include a variable ($(this).text()) in the custom variable? Anyone tried this before?

Original source