Skip to content

Instantly share code, notes, and snippets.

@jayb
Last active March 5, 2017 21:00
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jayb/5952170 to your computer and use it in GitHub Desktop.
Save jayb/5952170 to your computer and use it in GitHub Desktop.
/*
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