Disclaimer: This website requires Please enable JavaScript in your browser settings for the best experience.

The availability of features may depend on your plan type. Contact your Customer Success Manager if you have any questions.

Dev GuideAPI Reference
Dev GuideAPI ReferenceUser GuideLegal TermsGitHubDev CommunityOptimizely AcademySubmit a ticketLog In
Dev Guide

Helper functions

Describes how to run experiments using helper functions.

Below are some helper functions you might find useful to run more customized experiments in Optimizely Web Experimentation. These code samples are typically used in Variation code, Project JS, or Shared code, unless otherwise noted.

Read cookie

This function reads a cookie from the visitor's browser and returns the value.

/*
 * Usage
 *    This function will return the value of the cookie name passed in as the argument.
 *
 *  @param {String} name - The name of the cookie.
 */

 var getCookie = function(name) {
   var match = document.cookie.match(name+'=([^;]*)');
   return match ? match[1] : undefined;
 };

Set cookie

This function sets a cookie and accepts the cookie's name, value, domain, and duration in days as arguments.

/*
 * Usage
 *    This function will set a cookie on the visitor's browser.
 *
 *  @param {String} c_name - The name of the cookie.
 *  @param {String} value - The value of the cookie.
 *  @param {Float} exdays - The number of days the cookie should last.
 *  @param {String} c_domain - The domain on which this cookie should be set and can be read.

 *
 */

 var setCookie = function(c_name,value,exdays,c_domain) {
   c_domain = (typeof c_domain === "undefined") ? "" : "domain=" + c_domain + ";";
   var exdate=new Date();
   exdate.setDate(exdate.getDate() + exdays);
   var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
   document.cookie=c_name + "=" + c_value + ";" + c_domain + "path=/";
 }

Poll for element

This function polls for the variable accountBalance and displays an appropriate message. This is useful when you want to modify an element that's not injected into the DOM until shortly after document ready.

var utils = window["optimizely"].get("utils");

var cancelPolling = utils.poll(function() {
  if (typeof accountBalance !== 'number') {
    if (accountBalance <=20) {
      headerElement.innerHTML = 'Your account balance is low! Add funds';
    } else {
      headerElement.innerHTML = 'Your account balance is in good standing.';
    }
  cancelPolling();
  }
}, 1000);

Load external JavaScript

This function will append an external JavaScript to the head of the document. You can optionally provide a callback function as well.

/*
 * Usage
 *    This function will append an external JavaScript to the head of the document.
 *
 *  @param {String} location - The location of the file you'd like to load.
 *  @param {Function} callback - [OPTIONAL] A function to call when the script has completed downloading.
 *
 */

 var loadScript = function(location, callback){
   var fileRef = document.createElement('script');
   fileRef.setAttribute('type','text/javascript');

   if (callback) {
     if (fileRef.readyState) {  // IE
       fileRef.onreadystatechange = function() {
         if (fileRef.readyState == 'loaded' || fileRef.readyState == 'complete') {
           fileRef.onreadystatechange = null;
           callback();
         }
       };
     } else {  // Non-IE
       fileRef.onload = function(){
         callback();
       };
     }
   }

   fileRef.setAttribute('src', location);
   document.head.appendChild(fileRef);
 };

 loadScript('http://www.example.com/test.js', function() {
   // CALLBACK - code that does something with the data returned by loading the script
 });

Get query parameter value

This function will return the value of a query parameter. This is useful if you want to render a query parameter value on the page itself.

For example, you can store a visitor's search term in a query parameter. You can use this function to render their search term on the page, providing a personalized experience.

/*
 * Usage
 *    This function takes a query parameter name and returns its value.
 *
 *  @param {String} name - The name of the query parameter, whose value you want returned.
 */

 var getQueryParam = function(name) {
   var match = window.location.search.match(name + '=([^&]*)');
   return match ? match[1] : undefined;
 }

 // example showing the function called, with the return value inserted in the first h1 element
 $('h1:eq(0)').text(getQueryParam('myParam'));

Sticky navigation bar

This JavaScript makes one element's position fixed once the visitor scrolls below its original position. You could also achieve this by leveraging Extensions. A code sample of a Banner bar appears below.

/*
 *  Usage
 *     Pass in the ID of an element whose position you want fixed once the visitor scrolls past the element's initial position.  If the visitor scrolls up again, the element will take on its original position.
 *
 *  @param {String} id - The CSS ID of the element you want to have fixed position.
 *
 */

 var makeSticky = function(id) {
   var menuOffset = document.getElementById(id).offsetTop;
   var docScroll = $(document).scrollTop();
   $(document).bind('ready scroll', function() {
     docScroll = $(document).scrollTop();
     if(docScroll >= menuOffset) {
       $('#'+id).css({'position':'fixed', 'top':'0', 'z-index': '1000'});
     } else {
       $('#'+id).css({'position':'initial','z-index':'0'});
     }
   });
 }

 // Usage example
 makeSticky('mainNavBar');

Access data on page

This is an example of using JavaScript to access an object defined outside of the Optimizely snippet. Note that the variable must be declared above the snippet so that it's defined before Optimizely Web Experimentation evaluates audience conditions or executes experiment code.

/*
 * Example showing how to reference a variable defined natively on the page from inside Optimizely.
 */

 // Variation code example injecting the 'visitorName' property of the 'exampleObject' in the h3 elements
 $('h3').text('Hello,' + window.exampleObject['visitorName']);

Get active variations

This JavaScript will get active Experiment IDs and their Variation IDs for both Optimizely Web Experimentation and Personalization campaigns.

/*
 * Get active Experiment IDs and their Variation IDs for both Optimizely X Web Experiments and Personalization Campaigns.
 */

var activeCampaigns = optimizely.get('state').getCampaignStates({isActive:true});

for (var key in activeCampaigns) {
  if (activeCampaigns.hasOwnProperty(key)) {
    console.log("ExperimentId: " + activeCampaigns[key].experiment.id + ", variationId: " + activeCampaigns[key].variation.id);
  }
}

Get active tags

This JavaScript return the values of all tags for all active pages using the getPageStates API.

function getActiveTags() {
  var pages = optimizely.get('state').getPageStates()
  var activePages = pages ? Object.values(pages).filter(function(page) {
    return page.isActive && page.tags.length
  }) : []
  var tags = []
  activePages.forEach(function(page) {
    tags = tags.concat(Object.values(page.metadata))
  })
  return tags
}