James
James

Reputation: 31778

Asyncronous Google Analytics custom variables

I have a webpage with a 'Start test' button, I would like to track the value of an input: <input id="RepeatsInput" type="text" /> every time the button is clicked through Google analytics - bearing in mind I am using Google analytics to track the pageviews (this will have happened already before the user presses the button). What snippet of code should I use for this?

Thanks in advance.

Upvotes: 0

Views: 345

Answers (1)

jk.
jk.

Reputation: 14435

Since it is not known exactly how the HTML is set up, consider this example:

HTML:

<input id="RepeatsInput" type="text" />
<button onclick="setCustomVar();">Start test</button>​

JS:

function setCustomVar() {
   var inputValue = document.getElementById("RepeatsInput").value;
   _gaq.push(['_setCustomVar', 1, 'YOUR-CUSTOM-VAR-NAME', inputValue]);
   _gaq.push(['_trackPageview']);
}

Google's documentation on Custom Variables explains that another _trackPageview will need to be called for custom variables set by user events.

Call the _setCustomVar() function when it can be set prior to a pageview or event GIF request. In certain cases this might not be possible, and you will need to set another _trackPageview() request after setting a custom variable. This is typically only necessary in those situations where the user triggers a session- or visit-level custom var, where it is not possible to bundle that method with a pageview, event, or ecommerce tracking call.

Event tracking may be another way to address this.

Upvotes: 1

Related Questions