Last active
March 5, 2017 21:00
-
-
Save jayb/5952170 to your computer and use it in GitHub Desktop.
A/B tests with Google Events -- see http://huffpostdata.tumblr.com/post/55003907576/simple-a-b-tests-with-google-events
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Usage: | |
When generating a page: | |
var abTest = new AbTest('your-test-slug'); | |
if (abTest.variation == 0) | |
$('#thediv').addClass('red'); | |
else if (abTest.variation == 1) | |
$('#thediv').addClass('blue'); | |
When the goal is reached/passed: | |
$("#thediv").click(function() { | |
abTest.pass(); | |
}); | |
slug: A unique identifier for your AbTest | |
numVariations: The number of variations your test has (2 by default) | |
*/ | |
function AbTest (slug, numVariations) { | |
this.load = function() { | |
if (!this.runnable || this.loaded) return; | |
this.loaded = true; | |
_gaq.push(['_trackEvent', 'abtest', this.slug, 'load-' + this.variation]); | |
} | |
this.pass = function(value) { | |
if (!this.runnable || this.passed) return; | |
this.passed = true; | |
_gaq.push(['_trackEvent', 'abtest', this.slug, 'pass-' + this.variation, value, true]); | |
} | |
this.setVariation = function() { | |
var variationKey = "abtest-" + this.slug; | |
if (!this.runnable) return; | |
var pVariation = this.paramVariation(); | |
if (pVariation) { | |
this.variation = parseInt(pVariation); | |
return; | |
} | |
if (localStorage.getItem(variationKey) === null) | |
localStorage.setItem(variationKey, Math.floor(Math.random()*this.numVariations)); | |
this.variation = parseInt(localStorage.getItem(variationKey)); | |
} | |
this.paramVariation = function() { | |
var params = window.location.search.substr(1).split('&'); | |
for (var i = 0; i < params.length; i++) { | |
var p = params[i].split('='); | |
if (p.length == 2 && p[0] == this.slug) | |
return p[1]; | |
} | |
return null; | |
} | |
this.slug = slug; | |
this.numVariations = typeof(numVariations) !== 'undefined' ? numVariations : 2; | |
this.variation = 0; | |
this.runnable = (_gaq && typeof(localStorage) !== 'undefined'); | |
this.loaded = false; | |
this.passed = false; | |
this.setVariation(); | |
this.load(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment