Managing the allocation of a variation according to specific criteria

Written by Julie Trenque

Updated on 03/05/2024

2 min

Advanced

Was this content useful?

By default, Kameleoon allocates randomly a variation to a visitor. Here is the function used.

function (experiment)
{
  var registeredVariationId;
  var deviationRandom = experiment.obtainVariationAssignmentRandomNumber();
  var total = 0.0;
  for (var i = 0, l = experiment.variations.length; i < l; ++i)
  {
      total += experiment.variations[i].deviation;
      if (deviationRandom <= total)
      {
          registeredVariationId = experiment.variations[i].id;
          break;
      }
  }
  return registeredVariationId ? registeredVariationId : "none";
}

However, this function can be overloaded in order to change how the variation is selected and displayed to a visitor. For instance, it can be interesting to choose a variation according to a JavaScript variable. Here is an example:

function(experiment)
{
 if(experiment.id == "ID TEST"){ //code for the experiment you would like a specific behavior. It has to be adapted to your use case
 if(typeof versionTest != "undefined") { //versionTest variable has to be available before loading Kameleoon. Otherwise it will not work.
 if(versionTest == 1)
 return 81103; //ID of the variant 1
 else if(versionTest == 2)
 return 81104; //ID of the variant 2
 else if(versionTest == 3)
 return 81105; //ID of the variant 3
 else if(versionTest == 4) //ID of the variant 4
 return 81106;
 }
 }
 else{ //default behavior is applied for all other experiments
 var registeredVariationId;
 var deviationRandom = experiment.obtainVariationAssignmentRandomNumber();
 var total = 0.0;
 for (var i = 0, l = experiment.variations.length; i < l; ++i)
 {
 total += experiment.variations[i].deviation;
 if (deviationRandom <= total)
 {
 registeredVariationId = experiment.variations[i].id;
 break;
 }
 }
 return registeredVariationId ? registeredVariationId : "none";
 }
}

It is necessary to place this code in you account advanced options.

Then, use the left menu to go to Administrate > Sites.

Click on Configuration on the card of your website.

Click to display the Experiment section of the page.

You will find a Variation selection script field.

Add the script above in the field and validate.