---
title: Helper functions
slug: web-experimentation/docs/helper-functions
docTags: 
createdAt: 2026-07-23T11:40:25.851Z
---

The following are some helper functions you might find useful to run more customized experiments in Optimizely Web Experimentation. These code samples are typically used in [Shared Code](docId\:u7NyuYQdFZ7CXPKxIQt1i), [Project JS](docId\:sVG-PHXNCgHp_N90jDQbx), or the variation code in the [Visual Editor](docId:7tM_zXfrTc6bB19wLURDw).

## Read cookie

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

```javascript
/*
 * Usage
 *    This function returns 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.

```javascript
/*
 * Usage
 *    This function sets 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 is not injected into the DOM until shortly after the document is ready.

```javascript
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 appends an external JavaScript to the head of the document. You can optionally provide a callback function as well.

```javascript
/*
 * Usage
 *    This function appends 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 returns 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.

```javascript
/*
 * 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 using [Extensions](docId\:QANZ3gFOty4EplLUP9jba). The following is a code sample of a [Banner bar](https://github.com/optimizely/addons-library/tree/master/Extensions/Editor%20Extensions/Banner):

```javascript
/*
 *  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 takes 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.

:::hint{type="info"}
**📘 Note**
The variable must be declared above the snippet so that it is defined before Optimizely evaluates audience conditions or executes experiment code.
:::

```javascript
/*
 * 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 gets active Experiment IDs and their Variation IDs for Optimizely and Personalization campaigns.

```javascript
/*
 * Get active Experiment IDs and their Variation IDs for both Optimizely 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 returns the values of all [tags](https://help.optimizely.com/Measure_success%3A_Track_visitor_behaviors/Tags%3A_Describe_elements_on_the_page) for all active pages using the [getPageStates](docId\:m8udKL9NcS-nLa7zeoq85) API.

```javascript
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
}
```
