Introduction

In order to help you get up and running quickly, we have provided a number of code samples that you can use. Be sure to modify the code appropriately before running in production!

Table of Contents

  • Event tracking: To track events that are not provided out of the box by Optimizely (e.g. purchase data or offline conversions), check out our section on Events which explains all of our available tracking APIs.

  • Custom JS conditions: If you expose first or third party data on the client, then you can use Optimizely's custom JS conditions to port data into different audiences.

  • Advanced use cases: These advanced use cases will help you push the limits of what Optimizely is capable of doing within Project, Experiment, and Variation JavaScript.

  • Conditional activation: Sometimes you'll want to trigger an Optimizely experiment dynamically, after some part of the page or screen has loaded. Read our Conditional activation section for more information on how to control when Optimizely activates.

  • Helper functions: Many times, it is necessary to use getter and setter methods within Optimizely to better interact with your website. This list of helper functions are frequently used in Project, Experiment, and Variation JavaScript.

  • Mutually Exclusive: In addition to normal experiments, you can mutually exclusive experiments.

  • Single page apps: On traditional websites, when visitors click links, the links generally lead to a new URL and load an entirely new page. In Single Page Applications, the whole page doesn't reload; instead, certain content is changed, loaded, and swapped out in the current URL. Check out our single page app section to help accommodate the behavior of Single Page Applications.

  • Integrations: Whether you're looking to create a custom integration with an analytics platform or if you're looking to do WordPress headline testing with Optimizely, these integration code samples will help you navigate these processes.

  • Variation code: If you would like to write your own variation code instead of using the Optimizely visual editor, check out our Variation code section that explains how to format Optimizely variations with example code.

Event tracking

These code samples can be used to track goals after specific user actions. The majority of these code samples should be used in Project JS, Experiment JS, or Variation JS.

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. Within the goals menu, you'll need to create custom event goals 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(["trackEvent", "scroll25"]);
          scrollTwentyFive = false;
      }

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

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

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

  });

Custom JS conditions

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.

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

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

Advanced use cases

These code samples can be used within Experiment JS or Variation JS 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 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 offline conversion parameters

This JavaScript loops through the Optimizely Data Object to return the information necessary to construct the off-line conversions URL. Please note this code is only valid on pages where an experiment is currently running.

Example Javascript

/*
 * Usage
 *    Loops through the Optimizely Data Object to return the information necessary to construct the off-line conversions URL.
 *
 */

 // grab the endUserID from the Optimizely Cookie
 var endUserId = document.cookie.match('optimizelyEndUserId=([^;]*)')[1];

 for (var i=0; i < optimizely.activeExperiments.length; i++) {
   var experimentID = optimizely.activeExperiments[i];
   var variationID = optimizely.variationIdsMap[experimentID];
   var variationName = optimizely.variationNamesMap[experimentID];
   // code to pass this data to your backend should go here
 }

Conditional activation

Conditional activation mode is a flexible and powerful way to activate an experiment. There are two ways to use it: with polling, you enter a condition and Optimizely activates the experiment once that condition is true. With a callback, you enter a function and trigger a callback once your code is ready for the experiment 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 experiment 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.experimentId 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 the experiment.

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

 [Code whose last line evaluates to true/false, just like custom JS targeting]


/*
 * 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 experiment
 * @param {Object=}  options {
 *                     isActive : {Boolean} - Indicates if this experiment is active
 *                     experimentId : {Integer} - This experiment's Id
 *                   }
 *
 *  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 with jQuery and check the length of the result.

Example Javascript

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

 $('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) {
   $('html').delegate('#btn', 'mousedown', 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) {
   $(document).ajaxComplete(function(event, xhr, settings) {
     if (xhr.responseText.indexOf('rightRailModule') != -1) {
       activate();
     }
   });
 }

Function - Angular page change

To activate an experiment when an Angular.js location change happens, setup an event listener on the $locationChangeSuccess event and activate the experiment if the page change meets the right criteria.

Note: Not all Angular.js implementations are the same and thus this exact implementation may not work correctly on all websites. This is just an example of how to leverage built in Angular.js functions to activate an experiment at the right time.

Example Javascript

/*
 * Condition: Activate when an Angular.js application successfully changes location
 * Type: Callback function
 */

 function(activate, options) {
   var scope = window.angular.element('body').scope();
   scope.$on('$locationChangeSuccess', function(event, next, current) {
     if (next.indexOf('/productPage') != -1) {
       if (!options.isActive) {
         activate();
       }
     }
   });
 }

Function - DOM mutation activation

Note: This activation mode requires that you have Project Javascript enabled on your account. If you don't currently have ProjectJS in your account, you can upgrade! Get more information at: https://help.optimizely.com/hc/en-us/articles/200040055#switching

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);

Helper functions

Below are some helper functions you might find useful to run more customized Optimizely experiments. These code samples are typically used in the Edit Code box or Experiment JS, 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 an element on the page every 50ms that matches a specified selector. This is useful when you want to modify an element that is not injected into the DOM until shortly after document ready.

Example Javascript

/*
 * Usage
 *    This function is a recursive setTimeout of 50ms that polls for an element matching the selector in the if statement.
 *  @param {String} selector - The CSS path for the selector that you're polling for.
 */

 var pollForElement = function(selector) {
   if ($(selector).length > 0) {
   // code to run once element is found on page
   }
   else {
     setTimeout(pollForElement, 50);
   }
 };

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'));

Track clicks on dynamic content

This JavaScript will let you track clicks on elements loaded after DOM ready as a custom event in Optimizely. See our article on Custom Event Goals 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(["trackEvent", eventName]);
 });

Sticky navigation bar

This JavaScript will make one element's position fixed once the visitor scrolls below its original position.

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');

Redirect - Query parameter

This JavaScript will redirect a visitor to a new URL after appending a query parameter you specify.

Please exclude the query parameter as an Audience condition to prevent it from getting added multiple times.

Example Javascript


/*
 *  Usage
 *    This JavaScript will add a query parameter you specify to the visitor's current URL.
 *
 *  @param {String} newQuery - Parameter key-value pair. Replace [PARAM_NAME] and [PARAM_VALUE] with your values.
 */

/* _optimizely_redirect=http://custom_add_query_param */
var newQuery = "[PARAM_NAME]=[PARAM_VALUE]";
var _optly = {redir: document.createElement("a")};
_optly.redir = {protocol: "https:" == document.location.protocol ? "https://" : "http://",
                domain: window.location.hostname,
                pathname: window.location.pathname
               };
_optly.cur = window.location.search;
if (_optly.cur) {
  _optly.redir.query = _optly.cur + "&" + newQuery;
} else {
  _optly.redir.query = "?" + newQuery;
}
_optly.redir.href = _optly.redir.protocol + _optly.redir.domain + _optly.redir.pathname + _optly.redir.query;
window.location.replace(_optly.redir.href);

Redirect - New path

This JavaScript will redirect a visitor to a new path, preserving the rest of the URL.

Example Javascript


/*
 *  Usage
 *    This JavaScript will redirect a visitor to a new path.
 *
 *  @param {String} newPath - Replace "/[NEW_PATH]" with your new path, but keep the '/'.
 */

/* _optimizely_redirect=http://custom_new_path */
var newPath = "/[NEW_PATH]";
var _optly = {redir: document.createElement("a")};
_optly.redir = {protocol: "https:" == document.location.protocol ? "https://" : "http://",
                domain: window.location.hostname,
                query: window.location.search
               };
_optly.redir.href = _optly.redir.protocol + _optly.redir.domain + newPath + _optly.redir.query;
window.location.replace(_optly.redir.href);

Redirect- Same path different domain

This JavaScript will redirect a visitor to a new domain, preserving the rest of the URL.

Example Javascript


/*
 *  Usage
 *    This JavaScript will redirect a visitor to the same path on a different domain.  Make sure NOT to include the protocol when passing in the NEW_DOMAIN.
 *
 *  @param {String} newDomain - Change "[NEW_DOMAIN]" to the new domain, NOT including the protocol.
 */

/* _optimizely_redirect=http://custom_new_domain */
var newDomain = "[NEW_DOMAIN]";
var _optly = {redir: document.createElement("a")};
_optly.redir.href = window.location.href;
_optly.redir.hostname = newDomain;
window.location.replace(_optly.redir.href);

Redirect - Hash parameter

This JavaScript will redirect a visitor to a new URL while preserving the hash parameters.

Example Javascript


/*
 *  Usage
 *    This JavaScript will redirect a visitor to the URL you pass in while preserving all hash parameters.  Be sure to include the protocol in the [REDIRECT_URL]
 *
 *  @param {String} redirectUrl - Replace "[REDIRECT_URL]" with the new URL.
 */

/* _optimizely_redirect=http://custom_keep_hash */
var redirectUrl = "[REDIRECT_URL]";
var _optly = {redir:document.createElement("a")};
_optly.redir.href = redirectUrl;  //
_optly.cur = window.location.search;
if (_optly.cur) {
  _optly.redir.search = _optly.redir.search ? _optly.cur + "&" + _optly.redir.search.slice(1) : _optly.cur;
}
if (window.location.hash) {
  _optly.redir.hash = window.location.hash;
}
window.location.replace(_optly.redir.href);

Mutually Exclusive

These code samples are for mutually exclusive experiments.

Single page apps

On traditional websites, when visitors click links, the links generally lead to a new URL and load an entirely new page. In Single Page Applications, the whole page doesn't reload; instead, certain content is changed, loaded, and swapped out in the current URL. Since Optimizely generally loads once per page load we've created these code samples to help accommodate the behavior of Single Page Applications.

AJAX complete

This JavaScript will apply variation code whenever an AJAX request is complete. In this example, we also require that the request URL contain the sub-string "/shopping-cart". Please see the official jQuery documentation for more details on this method.

Please note that the .ajaxComplete() method is not included in the trimmed version of jQuery loaded with Optimizely by default. A library defining this method must be loaded before the snippet to use this code.

Example Javascript

/*
 *  Usage
 *     Apply variation code when an AJAX request is completed. In this example, we also require the request URL contain the sub-string "/shopping-cart".
 *
 *  @param {Function} handler - A function to execute when the ajaxComplete event is triggered.
 *
 *  e.g. window.$(document).ajaxComplete(handler)
 */

 // Usage example
 window.$(document).ajaxComplete(function(event, xhr, settings) {
   if (settings.url.indexOf('/shopping-cart') > -1) {
     //apply variation code
   }
 });

Integrations

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

Variation code

These code samples can be used within your experiments' variation code.

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']);