Skip to content

Instantly share code, notes, and snippets.

@chrisle
Created January 23, 2014 22:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisle/8588282 to your computer and use it in GitHub Desktop.
Save chrisle/8588282 to your computer and use it in GitHub Desktop.
TLDR - Google Analytics
/**
* The very simplest explanation of how GA works in JavaScript is that it's simply an array.
* The GA tag (not the new Universal tag) looks similar to this:
*/
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-xxxxxxxx-y']);
_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);
})();
/**
* That puts an array in your page's context called "_gaq". From here,
* you interact with it like any array.
*/
// Track a pageview
_gaq.push(['_trackPageview']);
/**
* You can place this inside functions. For example...
*/
// Your HTML looks like this:
<button id="my-button">Click Me</button>
// Your JS looks like this:
var trackClickEventsAsVirtualPageView = function(pageview) {
_gaq.push(['_trackPageview', pageview]);
}
$('#my-button').on('click', function() {
trackClickEventsAsVirtualPageView('/some-page-view');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment