jookyboi of Team Cacher
7/3/2018 - 1:03 PM

A/B Testing with Javascript

A/B Testing with Javascript

These are code snippets used to A/B test marketing site changes with Alephbet and Mixpanel. They can be used on any page over which you have control over HTML, CSS and Javascript.

HTML

<span data-variant="download" data-block>
  <button>Download for Mac OS</button>
</span>
<span data-variant="visit_web" data-block>
  <button>Get Started</button>
</span>

SCSS

*[data-variant] {
  display: none;

  &.variant-visible {
    display: inline-block;

    &[data-block] {
      display: block;
    }

    &[data-inline] {
      display: inline;
    }
  }
}

Javascript

The following assumes your page uses jQuery and lodash.

For experiments

function newExperiment(name, variants) {
  var args = {
    name: name,
    variants: {}
  };
  
  _.each(_.keys(variants), function(variant) {
    args.variants[variant] = {
      activate: function() {
        $('*[data-variant="' + variant + '"]').addClass("variant-visible");
      },
      weight: variants[variant]
    };
  });
  
  new AlephBet.Experiment(args);
}

$(function() {
  newExperiment("homepage", {
    download: 50,
    visit_web: 50
  });
});

For tracking events

function testingStore() {
  var store = localStorage.getItem('alephbet');
  if (store) {
    return JSON.parse(store);
  } else {
    return null;
  }
}

function mixpanelTrack(event, data) {
  data = data || {};
  var store = this.testingStore();
  
  if (store) {
    _.each(_.keys(store), function(key) {
      if (key.indexOf("variant") >= 0) {
        var tokens = key.split(":");
        data["experiment:" + tokens[0]] = store[key];
      }
    });
  }
  
  mixpanel.track(event, data);
}