public
Last active

  • Download Gist
abtest.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
/*
 
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();
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.