Skip to content

@jayb /abtest.js
Last active

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
/*
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
Something went wrong with that request. Please try again.