Introduction

There are many useful applications for the JavaScript API. Be sure to modify the code appropriately before running in production! If can share your own code sample by posting in the developer community forum.

These code samples should be used in either Shared Code, Project JS or Variation code.

Custom Event Tracking

These code samples can be used to track events after specific user actions. The majority of these code samples should be used in Project JS, Shared Code, or variation code.

Scroll depth

This function checks after each scroll event to see if a visitor has achieved certain scroll depth milestones. In the case of this example, custom events will be fired off when a visitor scrolls 25%, 50%, 75%, and 100% of the way down the page. You'll need to create custom events that correspond to the events below (e.g. "scroll25" for scrolling 25% of the way down the page).

NOTE: This code uses jQuery's .scrollTop() method which is not included in Optimizely's trimmed version of jQuery. To use this code within your Optimizely experiment, you must either include the full version of jQuery in Project Settings or use a native version of jQuery on the page.

Example Javascript

/*
 * Usage
 *    This function fires custom events at different scroll depth milestones.
 */

  // Variables to prevent continuous firing of custom events

  var scrollTwentyFive = true;
  var scrollFifty = true;
  var scrollSeventyFive = true;
  var scrollOneHundred = true;

  // Create the scrollPercentage

  $(window).bind('scroll', function() {
      window.scrollPercent = ($(window).scrollTop() / ($(document).height() - $(window).height())) * 100;

      // Conditional code we'll use to fire events based on scrollPercentage.

      if (window.scrollPercent >= 25 && scrollTwentyFive) {
          window['optimizely'] = window['optimizely'] || [];
          window['optimizely'].push({type: "event", eventName: "scroll25"});
          scrollTwentyFive = false;
      }

      if (window.scrollPercent >= 50 && scrollFifty) {
          window['optimizely'] = window['optimizely'] || [];
          window['optimizely'].push({type: "event", eventName: "scroll50"});
          scrollFifty = false;
      }

      if (window.scrollPercent >= 75 && scrollSeventyFive) {
          window['optimizely'] = window['optimizely'] || [];
          window['optimizely'].push({type: "event", eventName: "scroll75"});
          scrollSeventyFive = false;
      }

      if (window.scrollPercent >= 100 && scrollOneHundred) {
          window['optimizely'] = window['optimizely'] || [];
          window['optimizely'].push({type: "event", eventName: "scroll100"});
          scrollOneHundred = false;
      }

  });

Track clicks on dynamic content

This JavaScript code will let you track clicks on elements loaded after DOM ready as a custom event in Optimizely. See our article on events to learn more about tracking custom events.

Example Javascript

/*
 *  Usage
 *    Track clicks on elements loaded after DOM ready.  The .delegate() method allows you to select all current and future elements that match the selector passed in as the first argument.
 *
 *  @param {String} selector - Provide the element selector.
 *  @param {String} eventName - Provide the custom event name.
 */

 var selector = [YOUR_SELECTOR];
 var eventName = [YOUR_EVENT_NAME];

 $('html').delegate(selector, 'mousedown touchend', function() {
   window['optimizely'] = window['optimizely'] || [];
   window['optimizely'].push({type: "event",eventName: "eventName"});
 });

Custom Audience Targeting

These code samples can be used within the Custom JS Audience Condition. Keep in mind that the JavaScript within this condition must evaluate to a boolean value on the last line of the code.

Please Note: jQuery is not included in the Snippet by default and is required for the following samples. This can be configured in the settings tab.

Access data on page

This is an example using JavaScript to access an object defined outside of the Optimizely snippet. Please note that the variable must be declared above the snippet, so it is defined before Optimizely evaluates Audience conditions or executes experiment code. Read more here

Example Javascript

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

 // Audience condition example checking the 'category' property of the 'exampleObject'
 window.exampleObject['category'] == 'shirts';

Target pages based on meta values

The following condition will only run an experiment when a certain meta value is present on the page.

Example Javascript

/*
 * Usage
 * Replace "desired_value" with the name of the meta value you're testing for.
 */

 $('meta[name="desired_value"]').length > 0

Target visitors based on screen size

The first condition will ensure that the experiment only runs if the screen width is greater than 1400 pixels and the height is greater than 800 pixels. The second condition will ensure the experiment only runs if the viewport width is between 320 and 480 pixels and the height is less than or equal to 640 pixels.

Example Javascript

/*
 * Usage
 *  Specifies window size (in pixels) to target visitors.
 */

 //target desktop viewports
 //matches CSS media queries for height/width or max/min-height or -width
 window.innerWidth > 1400 && window.innerHeight > 800

 //target mobile phones
 //matches CSS media queries using device-height and device-width
 screen.width >= 320 && screen.width <= 480 && screen.height <= 640

Target specific user agents

The following condition will only run for visitors who are using the Google Chrome web browser.

Example Javascript

/*
 * Usage
 *  Targets visitors based on user-agent.
 */

 window.navigator.userAgent.indexOf("Chrome") !== -1

Variation Code

These code samples will help you write Variation Code in the visual editor.

Bind events

Bind events to each product on a category page. This example is intended for a e-commerce site.

Example Javascript

function variationCode() {
  // select your product item elements
  $('<selector>').each(function(){
    // can be used to target elements inside the product item container
    $(this).find('<selector>').css('color','red');
    // can be used to bind events to elements inside the product item container
    $(this).find('<selector>').bind("click", function() {
      window['optimizely'].push({
       type: "event",
       eventName: "<event name>"
      });
    });
  });
};

Advanced Experiment Configuration

These code samples can be used within Shared code or Variation code to help satisfy advanced use cases within Optimizely.

Execute code for X visits

This JavaScript will let you execute code a certain number of times within an experiment.

For example, you might want to only show a pop up to visitors on their first 3 visits. In this case, you place this code in either the (edit this) Experiment JS or Variation code.

Example Javascript


/*
 * Usage
 *   The following allows you to set a limit on the number of times a Code Block will execute for any given visitor.
 */

 // the number of times the code should execute for a given visitor
 var limit = 3;
 // the number of days the evaluation limit should last
 var days = 180;
 // name of the cookie we use as the counter
 var cookieName = 'counterCookie';

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

 // function to create cookies
  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=/";
  }

 // logic that counts and limits number of times code can evaluate for given visitor
 if (!getCookie(cookieName)) {
   setCookie(cookieName, 1, days, window.location.hostname);
 } else {
   var numberPops = parseInt(getCookie(cookieName)) + 1;
   setCookie(cookieName, numberPops, days, window.location.hostname);
 }

 if (getCookie(cookieName) <= limit) {
  // INSERT code to evaluate HERE
 }

Change page title

This JavaScript will modify the text of the browser tab when a visitor focuses and unfocuses on the tab. You can display one title when a visitor is focused on the tab and a different title when they toggle to a different tab or window.

Example Javascript


/*
 * Usage
 *   The following code will modify the title of the browser tab on the "blur" event and change it back to the original on the "focus" event.
 *
 */

 // store the original tab title
 var origTitle = document.title;

 // function to change title when focusing on tab
 function oldTitle() {
   document.title = origTitle;
 }

 // function to change title when un-focusing on tab
 function newTitle() {
   document.title = 'HELLO WORLD';
 }

 // bind functions to blur and focus events
 window.onblur = newTitle;
 window.onfocus = oldTitle;

Get Optimizely data for custom events

This provides the Optimizely Data Object to return the information necessary to retrieve relevant data. This data can be used with internal tools, the Event API or Custom Analytics Integrations

Example Javascript

/*
 * Usage
 * Loops through the Optimizely Data Object to return the information necessary to construct the Event API payload.
 *
 */

 var campaign_data;
 var state = optimizely.get('state');

 // return all active campaigns
 campaign_data = state.getCampaignStates({"isActive": true});

 for (var campaign_id in campaign_data) {
    if (campaign_data.hasOwnProperty(campaign_id)) {
       // Returns campaign_id, experiment_id, variation_id
       var data = state.getDecisionObject({"campaignId": campaign_id});
       // code to use data
    }
 }

Page Activation

Conditional activation mode is a flexible and powerful way to activate a page, and its associated experiments. There are two ways to use it: with polling, you enter a condition and Optimizely activates the page once that condition is true. With a callback, you enter a function and trigger a callback once your code is ready for the page to activate. These methods are described in more detail below, and we've also highlighted several examples using each method.

Based on the code you enter, Optimizely will automatically determine if it should be polled for or executed as a function. See the examples for detailed usage definitions.

Polling

If the code entered does not evaluate to a function type, it will be checked every 50ms and the page will be activated when it evaluates to true. Optimizely checks this code in a try/catch block, so a condition which results in an error will be assumed to be false and polling will continue.

Callback Function

If the code entered is a function, Optimizely will assume it is of the form shown here and call it immediately, passing an activate function and an options object. Rather than returning a value, your code should call activate() when it is ready, leveraging options.isActive and options.pageId if needed. Note that because this function is called immediately when the Optimizely snippet loads, any functions or variables referenced here should be available/defined at the time they are used.

Note: No matter which method is used, remember that this is only an activation condition. Visitors must still meet URL and Audience targeting to actually be bucketed into any experiments.

Example Javascript


/*
 * Usage Option #1 - Polling
 *   Optimizely will poll for the code condition to be true if the JavaScript
 *   entered does not evaluate to a function type.
 *
 *  Note: Optimizely will evaluate this code in a try/catch block, meaning
 *  if your expression errors, it will be evaluated as false. Timeout is two seconds.
 */

 // check if butter bar is in the DOM
 document.getElementById("butter-bar-flash-sale") !== null;


/*
 * Usage Option #2 - Callback Function
 *   Optimizely will call the function entered immediately if the JavaScript entered
 *   does evaluate to a function type.
 *
 * @param {Function} activate - Activate this Page
 * @param {Object=}  options {
 *                     isActive : {Boolean} - Indicates if this page is active
 *                     pageId : {String} - ID of the activated Page
 *                   }
 *
 *  Note: Optimizely will call this function immediately when the snippet loads, so make
 *  sure any functions referenced are defined at that time.
 */

 function(activate, options) {
   // Do logic and call `activate()` when appropriate
 }

Polling - Meta tag data

To activate an experiment based on the value of a meta tag, select the contents of the meta tag with jQuery and check them for your value.

Example HTML

<meta name="keywords" content="movies,games,videos,photos"/>

Example Javascript

/*
 * Condition: Activate when the description meta tag contains 'sports', 'games', or 'puzzles'
 * Type: Polling
 */

 (/sports|games|puzzles/).test($('meta[name=keywords]').attr('content'))

Polling - JavaScript variable

To activate an experiment based on the value of a JavaScript variable, simply enter the condition to check.

Example Javascript

/*
 * Condition: Activate when the Omniture eVar 33 contains 'product'
 * Type: Polling
 */

 window.s.eVar33.indexOf('product') != -1

Polling - DOM element

To activate an experiment based on the existence of a DOM element, simply select that element and check the length of the result.

Example Javascript

/*
 * Condition: Activate when the green button DOM element appears
 * Type: Polling
 */

 function pollingFn() {
   return document.querySelectorAll("button.green").length > 0;
 }

Function - Button click

To activate an experiment when a button is clicked on, bind a click or mousedown event to that element using jQuery and activate the experiment when that event fires.

Example Javascript

/*
 * Condition: Activate when a button is clicked
 * Type: Callback function
 */

 function(activate, options) {
   // following line assumes you are including jQuery in your Optimizely snippet
   var $ = window.optimizely.get('jquery');

   $('html').on('mousedown', '#btn', function() {
     activate();
   });
 }

Function - AJAX response

To activate an experiment after an AJAX call returns, leverage jQuery's ajaxComplete function to listen to completed AJAX requests. If the response contains or corresponds to the element that should be changed, activate the experiment.

Note: Optimizely's default (trimmed) version of jQuery does not contain the ajaxComplete function. To use this function, you can include the full version of jQuery in your Optimizely snippet (Project Settings -> Project Code Settings) or reference your own version of jQuery which loads above the Optimizely snippet via window.$.

Additionally, $.ajaxComplete can be disabled on your site if the AJAX setup is called with global option set to false, preventing this event from firing. See jQuery's documentation for more information.

Example Javascript

/*
 * Condition: Activate when an AJAX call contains the element that should be changed
 * Type: Callback function
 */

 function(activate, options) {
   // following line assumes you are including (full version of) jQuery in your Optimizely snippet
   var $ = window.optimizely.get('jquery');

   $(document).ajaxComplete(function(event, xhr, settings) {
     if (xhr.responseText.indexOf('rightRailModule') != -1) {
       activate();
     }
   });
 }

Function - DOM mutation activation

To activate an experiment based on a DOM element either changing or appearing on the page, simply make the following call in your experiment's conditional activation code box:

function(activate, options) {
  window.activateOnDOMMutation('#element:not(.changed)', activate, true);
}

The first part of the call, #element:not(.changed), is a DOM element selector that you would like to monitor. Any time this element appears on the page or is changed, the experiment will be activated either once or multiple times depending on the last parameter. You can use any DOM selector that you can use with jQuery. If you are change the selected element or its children in Variation code you will create an infinite loop. You can prevent this by excluding selectors with an added class as shown in the code example. You would add the ".changed" class in experiment code.

The second part of the call, activate, activates the experiment with the given ID.

The last parameter, true, tells the DOM Mutation call whether you want to re-activate the experiment every time the selector changes or is added to the page. Adding 'false' here will only activate the experiment once. This is useful when you are appending content to the page and you don't want to append every time the DOM selector changes.

Example Javascript

/*
 * Condition: Activate when the dom selector changes on the page
 * Type: Callback Function
 *
 * Place the following code in your Project Javascript and call the function below in your experiment's
 * conditional activation code box:
 *
 * window.activateOnDOMMutation('#element', window['optimizely'].push(["activate", EXPERIMENT_ID]), true);
 * @param '#element': DOM Selector of element you'd like to watch
 * @param 'window['optimizely'].push(["activate", EXPERIMENT_ID])': Replace EXPERIMENT_ID with the current
 * experiment's ID
 * @param 'true': True re-activates the experiment on the DOM selector changing or being added to the DOM.
 * False activates the experiment only the first time the selector is added or updated.
 */

(function(win) {
    'use strict';

    var listeners = [],
        doc = win.document,
        MutationObserver = win.MutationObserver || win.WebKitMutationObserver,
        observer;

    function waitForElement(selector, repeat, fn) {

        // Store the selector and callback to be monitored
        listeners.push({
            selector: selector,
            fn: fn,
            repeat: repeat,
        });
        if (!observer) {
            // Watch for changes in the document
            observer = new MutationObserver(check);
            observer.observe($(document), {
                childList: true,
                subtree: true
            });
        }
        // Check if the element is currently in the DOM
        check();
    }

    function check() {
        // Check the DOM for elements matching a stored selector
        for (var i = 0, len = listeners.length, listener, elements; i < len; i++) {
            listener = listeners[i];
              // Query for elements matching the specified selector
              elements = $(listener.selector);
              for (var j = 0, jLen = elements.length, element; j < jLen; j++) {
                 element = elements[j];
                if (!element.ready || listener.repeat) {
                     // Invoke the callback with the element
                      listener.fn.call(element, element);
                  }
             }
        }
    }

    function activateOnDOMMutation(selector, activate, repeat) {
      repeat = repeat === undefined ? false : repeat;
      if (window.MutationObserver || window.WebKitMutationObserver) {
        waitForElement(selector, repeat, function(element) {
           activate();
        });
      } else {
        // this solution does not handle older browsers
      }
    }

    // Expose functions
    win.waitForElement = waitForElement;
    win.activateOnDOMMutation = activateOnDOMMutation;

})(this);

Conditionally Activated Pages - Callback Activation

Use jQuery and Optimizely's native utility functions to activate a page conditionally after a DOM element is found on the page. This is method is advantageous to the polling activation type because it is not limited by the two second timeout after DOM ready.

Example Javascript

function callbackFn(activate, options) {
  var utils = window.optimizely.get('utils');
  var $ = window.optimizely.get('jquery');

  utils.waitForElement('button').then(function(buttonElement) {
    if ($('button').length > 0) {
      activate();
    }
  });
}

Custom Activation

There may be instances where you want to activate a page following the execution of an asynchronous function. You can use conditional activation to call the external function and pass activate as a callback.

Example Javascript

function callbackFn(activate, options) {
    if (window.location.href.indexOf(/* Some URL */) !== -1) {
        options.isActive && activate({isActive: false});
        window.customProcessFunction.init(activate);
    }
}

Helper Functions

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

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

Example Javascript

/*
 * 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;
 };

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

Example Javascript

/*
 * 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 is not injected into the DOM until shortly after document ready.

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

Example Javascript

/*
 * 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'd like to render a query parameter value on the page itself.

For example, you may 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.

Example 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 will make one element's position fixed once the visitor scrolls below its original position. Additionally, you could achieve this by leveraging Extensions. Here's a code sample of a Banner bar.

Example 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 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 using JavaScript to access an object defined outside of the Optimizely snippet. Please note that the variable must be declared above the snippet, so it is defined before Optimizely evaluates Audience conditions or executes experiment code.

Example 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

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

Example Javascript

/*
 * 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

Return the values of all tags for all active pages using the getPageStates API.

Example 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
}

Dynamic Websites

The Dynamic Websites code samples are embedded in the feature's developer documentation.

Integrations

You can find code samples for creating integrations with Optimizely in the integrations section.