-->

API Calls with AJAX

Often, you'll want to connect to Optimizely using AJAX, as we did when creating our Wordpress plugin.

In this sample, we'll show how you can send AJAX calls using jQuery. We'll define a OptimizelyAPI class that handles all the authentication and encoding for API requests.

You can see this connection in action in our Wordpress sample below. To download it for use in your own projects, click the button below.

Download source code

Initialization

The OptimizelyAPI class provides a connection to the API via Javascript and lets you make authenticated calls without repeating yourself.

We store the API token in each instance of the object, and we can connect to multiple different accounts by creating new instances of the OptimizelyAPI class.

Finally, we keep track of how many requests are outstanding so we can tell when all the calls are complete.

Example Javascript

OptimizelyAPI = function(token) {
  this.outstandingRequests = 0;
  this.token = token;
}

optly = new OptimizelyAPI("abcdefghijklmnop:12345");

Calling the API

To call the API, we use jQuery's $.ajax function, which sends an asynchronous request based on a set of options.

Our function takes four arguments:

  • The request type, like GET or POST

  • The endpoint to hit, like projects/27

  • The data to send along with a POST or PUT request

  • A callback function to run when the operation is done. The callback should take one argument, the response.

We construct the URL by appending the endpoint to the base API link, and we authenticate by adding the token in the headers section.

To send data, we set content type to JSON and encode the array as a JSON string to send over the wire.

Example Javascript

OptimizelyAPI.prototype.call = function(type, endpoint, data, callback) {

  var self = this;

  var options = {
    url: "https://www.optimizelyapis.com/experiment/v1/" + endpoint,
    type: type,
    headers: {"Token": this.token},
    contentType: 'application/json',
    success: function(response) {
      self.outstandingRequests -= 1;
      callback(response);
    }
  }

  if (data) {
    options.data = JSON.stringify(data);
    options.dataType = 'json';
  }

  this.outstandingRequests += 1;
  $.ajax(options);

}

Request types

Using our call function, we can define convenience functions for each of the major types of call we'll need.

Example Javascript

OptimizelyAPI.prototype.get = function(endpoint, callback) {
  this.call('GET', endpoint, "", callback);
}

OptimizelyAPI.prototype.delete = function(endpoint, callback) {
  this.call('DELETE', endpoint, "", callback);
}

OptimizelyAPI.prototype.post = function(endpoint, data, callback) {
  this.call('POST', endpoint, data, callback);
}

OptimizelyAPI.prototype.put = function(endpoint, data, callback) {
  this.call('PUT', endpoint, data, callback);
}

Wordpress Headline Testing

This sample goes through a simplified version of our Wordpress plugin, which lets editors write alternate headlines for a blogpost and A/B test them directly from their Wordpress editor.

To see the full source of our plugin or download it to use on your own site, click the button below. Note that this plugin is just a proof of concept -- we encourage you to fork it, improve it for your own needs, and share it with the community.

Download source code

The plugin uses jQuery to make the API calls, as described in our AJAX code sample.

Connect a project

Our plugin starts with a configuration page that lets users connect their Optimizely account to Wordpress. It requests all the information needed to authenticate and run experiments.

First, we ask the user for their API token on our plugin configuration page. We use this to authenticate with the REST API.

We also ask them to choose a project to create the experiment in. They make this choice using a dropdown menu that we will populate using the "Connect Optimizely button."

When the user presses that button, we call the GET projects/ endpoint to list out all the projects in their account. For each project, we show its name in the dropdown and store its ID in the value attribute for submission to a form.

Example HTML

<h3>Enter Your API Token</h3>
<input id="token" type="text" />
<button id="connect_optimizely">Connect Optimizely</button>
<h3>Choose a Project</h3>
<select id="project_id">
  <option value="">Connect Optimizely to choose a project...</option>
</select>

Example Javascript

$("button#connect_optimizely").click(function() {
  
  $("#project_id").html("<option>Loading projects...</option>");
  
  // Authenticate and send the request
  optly = new OptimizelyAPI($("#token").val());
  optly.get('projects/', function(response) {
    
    $("#project_id").empty();

    $.each(response, function(key, val) {
      $("#project_id").append("<option value='" + val.id + "'>" + val.project_name + "</option>"); 
    });

  });
});

Create an experiment

Now, when users go to write their posts, they'll see a new section for A/B testing headlines. This section will include two inputs for users to write alternate headlines and a button to create the experiment.

When the button is pressed, we run the createExperiment function. This function creates an experiment by providing a description based on the post's title and an edit_url based on the permalink of the Wordpress post. We send these as a POST request and register a callback to run the onExperimentCreated function when it completes.

We aren't done yet. The experiment we created has two built-in variations, but now we need to add a third and update the content. Since we're adding a variation, we also need to calculate the traffic weight to use for each one. Once we've done this, we'll call the createVariation function explained below.

Example HTML

<h1>Variation #1</h1>
<input type="text" id="post_title1" class="optimizely_variation" placeholder="Alternate Title 1">
<h1>Variation #2</h1>
<input type="text" id="post_title2" class="optimizely_variation" placeholder="Alternate Title 2">
<a id="optimizely_create" class="button-primary">Create Experiment</a>

Example Javascript

$('#optimizely_create').click(createExperiment);

function createExperiment() {
  $('#optimizely_create').text('Creating...');

  experiment = {}
  experiment.description = "Wordpress: " + $('#title').val();
  experiment.edit_url = $('#post-preview').attr('href');

  optly.post('projects/' + projectId + '/experiments', experiment, onExperimentCreated);

}

function onExperimentCreated(experiment) {

  var variations = $('.optimizely_variation').filter(function(){return $(this).val().length > 0})
  
  // Set variation weights
  var numVariations = variations.length + 1;
  var variationWeight = Math.floor(10000 / numVariations);
  var leftoverWeight = 10000 - variationWeight*numVariations;

  // Create variations
  variations.each(function(index, input) {
    var weight = variationWeight + (index == 0 ? leftoverWeight : 0);
    createVariation(experiment, index + 1, $(input).val(), weight);
  });

}

Create variations

To create a variation, we first generate the variation code. We use a template based on the Wordpress theme, and then we drop in the values for our variation. The result would be:

$(".post-27 .entry-title a").text("Alternate Title #1");

Once we've generated this variation code, we include it in the js_component parameter of our API request. We also add a variation title and weight.

In this example, we have two alternate headlines plus an original. When we created the experiment, it also came with two variations that were created automatically. We'll leave variation 0 alone as the original, update variation 1 to use the first alternate headline, and create a new variation 2 with the second alternate headline.

Once all the PUT and POST requests have returned, we're done! At this point, we can let the user know that the experiment is created and ready.

Example Javascript

function createVariation(experiment, index, newTitle, weight) {

  // Generate variation code
  var variationTemplate = '$(".post-$POST_ID .entry-title a").text("$NEW_TITLE");';
  var postId = $('#post_ID').val();
  var originalTitle = $('#title').val();
  var code = variationTemplate
    .replace(/\$OLD_TITLE/g, originalTitle)
    .replace(/\$NEW_TITLE/g, newTitle)
    .replace(/\$POST_ID/g, postId);

  // Request data
  var variation = {
    "description": newTitle,
    "js_component": code,
    "weight": weight,
  }

  // Update variation #1, create the others
  if (index == 1) {
    optly.put('variations/' + experiment.variation_ids[1], variation, onVariationCreated);
  } else {
    optly.post('experiments/' + experiment.id + '/variations', variation, onVariationCreated);
  }

}

function onVariationCreated(variation) {
  // When all requests are done, we're finished!
  if (optly.outstandingRequests == 0) {
    alert("Experiment Created!");
  }
}

Start the experiment

Finally, we'll add a start button so users can run the experiment directly from Wordpress. Once it's started, we'll turn it into a pause button to stop the running experiement.

This button will update the experiment's status to Running or Paused.

Example Javascript

function startExperiment(experiment) {
  $('#optimizely_toggle_running').text('Starting...');
  optly.put('experiments/' + experiment.id, {'status': 'Running'}, function(response) {
    // Running
    $('#optimizely_toggle_running').text('Click to pause');
  });
}

function pauseExperiment(experiment) {
  $('#optimizely_toggle_running').text('Pausing...');
  optly.put('experiments/' + experiment.id, {'status': 'Paused'}, function(response) {
    // Pause
    $('#optimizely_toggle_running').text('Click to start');
  });
}

Creating Audiences via API

If you have data about the visitors to a site, you can use our platform to group those visitors into Optimizely Audiences. This makes it easy to target content to different audiences and segment experiment results.

In this example, we'll show how a data management platform could connect to Optimizely to create audiences and assign visitors to them on the fly. In this case, we'll use the REST API to create a "Truck Shoppers" audience, and then we'll use the Javascript API to assign visitors to it whenever their cookie indicates they're in the market for a truck.

Connect a project

GET projects/

First, you'll need to authenticate with our REST API. This will let you create audiences in the right account.

You'll also need to choose a project to create the audiences in. If you're building an integration, you could ask for a project_id directly from the user.

Alternatively, you can list out all the projects in a user's account and have them pick from a dropdown, as the example at right shows.

Example Request

curl \
  -H "Token: abcdefghijklmnopqrstuvwxyz:123456" \
  -X GET "https://www.optimizelyapis.com/experiment/v1/projects/"

Example Response

[
  {
    "project_id": 1234,
    "project_name": "My project"
  },
  {
    "project_id": 1235,
    "project_name": "My other project"
  }
]
GET

Raw Request

Copy

Response Status


  

Response Headers


  

Request Output

Create an audience

POST projects/43523/audiences/

Let's say you've chosen project ID 43523. You can send a POST request to the projects/43523/audiences entrypoint to create an audience in that project.

The response will include a unique id for the audience you created. You'll use this ID to assign visitors to the audience.

Example Request

curl \
  -H "Token: abcdefghijklmnopqrstuvwxyz:123456" \
  -H "Content-Type: application/json" \
  -d '{"name":"Truck Shoppers","description":"(Imported from ______)"}' \
  -X POST "https://www.optimizelyapis.com/experiment/v1/projects/43523/audiences/"

Example Response

{
  "name": "Truck Shoppers",
  "description": "(Imported from ______)",
  "project_id": 43523,
  "id": 85094
}

Assign visitors

Now that you've created the audience, you can assign visitors to it programmatically using our Javascript API.

Use the addToAudience call with the audience's id as the first argument.

This call needs to happen before the Optimizely snippet loads, otherwise visitors won't see experiments targeted to that audience.

Example Javascript

window['optimizely'] = window['optimizely'] || [];
window['optimizely'].push(["addToAudience", 85094]);

Getting Results via API

To illustrate how to get experiment results via the REST API, we've built a basic web application that gets the top-level results for the active experiments in a project. This code sample walks through all of the REST API calls that are used by the web application.

To use this web application, visit resultsapisample.appspot.com and follow the instructions. You can also download the full source code from the link below.

Download source code

The application uses jQuery to make the API calls, as described in our AJAX code sample.

Connect a project

GET projects/

First, you'll need to authenticate with our REST API and choose which project to retrieve results for. You can list out all the projects in a user's account using the example request here.

Example Request

curl \
  -H "Token: abcdefghijklmnopqrstuvwxyz:123456" \
  -X GET "https://www.optimizelyapis.com/experiment/v1/projects/"

Example Response

[
  {
    "project_id": 1234,
    "project_name": "My project"
  },
  {
    "project_id": 1235,
    "project_name": "My other project"
  }
]
GET

Raw Request

Copy

Response Status


  

Response Headers


  

Request Output

List experiments

GET projects/1234/experiments

Next, you'll want to list out all of the experiments for the selected project. You can tell which experiments are active based on the status field.

Example Request

curl \
  -H "Token: abcdefghijklmnopqrstuvwxyz:123456" \
  -X GET "https://www.optimizelyapis.com/experiment/v1/projects/1234/experiments"

Example Response

[
  {
    "id": 15,
    "project_id": 1234,
    // ... (other fields omitted)
    "variation_ids": [115, 210, 215],
    "edit_url": "https://mysite.com/products/",
    "status": "Not started"
  },
  {
    "id": 16,
    "project_id": 1234,
    // ... (other fields omitted)
    "variation_ids": [216, 217, 218],
    "edit_url": "https://mysite.com/cart/",
    "status": "Running"
  },
]
GET

Raw Request

Copy

Response Status


  

Response Headers


  

Request Output

Get results

GET experiments/1234/results

Finally, you'll want to get the results for each active experiment. The response contains the results for every variation_id and goal_id that has been defined for that experiment.

Example Request

curl \
  -H "Token: abcdefghijklmnopqrstuvwxyz:123456" \
  -X GET "https://www.optimizelyapis.com/experiment/v1/experiments/1234/results"
GET

Raw Request

Copy

Response Status


  

Response Headers


  

Request Output

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 functon 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();
       }
     }
   });
 }

Custom Experiment Setups

Below are some code samples 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. If you have suggestions for new code samples, please email developers@optimizely.com.

Example Javascript

/*
 *	Below you will find some code samples to help you build customized experiments.
 * 
 */

Read Cookie

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

Set Cookie

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} name - The name of the cookie.
 *  @param {String} value - The value of the cookie.
 *  @param {String} domain - The domain on which this cookie should be set and can be read.
 *  @param {Float} age - The number of days the cookie should last.
 *   
 */

 var setCookie = function(name, value, domain, age) {
   var futureDate = new Date(+new Date() + age * 1000);
   var parts = [
     name, '=', encodeURIComponent(value),
     '; domain=.', domain,
     '; path=/',
     '; expires=', futureDate.toUTCString(),
     ';'
   ];
   document.cookie = parts.join('');
 };

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

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

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

 var selector = [YOUR_SELECTOR]; //provide the element selector as a string
 var eventName = [YOUR_EVENT_NAME];  //provide the custom event name

 $('html').delegate(selector, 'mousedown touchend', function() {
   window.optimizely.push(['trackEvent', eventName]);
 });

.ajaxComplete()

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

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(name, value, domain, age) {
   var futureDate = new Date(+new Date() + age * 1000);
   var parts = [
     name, '=', encodeURIComponent(value),
     '; domain=.', domain,
     '; path=/',
     '; expires=', futureDate.toUTCString(),
     ';'
   ];
   document.cookie = parts.join('');
 };

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

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

Scroll depth

This JavaScript will let you trigger a custom event when a visitor has scrolled to a certain element on the page. Please note the entire element has to display before this will fire.

Please see our Custom Event Goals documentation for more information on tracking custom events.

Example Javascript

/*
 * Usage
 *     Send an Optimizely custom event after a visitor has scrolled to a certain element on the page.  Note that the entire element must be displayed for this to function properly.
 *     
 *  @param {String} element - The jQuery selector for the element to trigger the call.
 *  @param {String} eventName - The name of the custom event to send to Optimizely.
 *     
 */

 window.trackScrolling = function(element, eventName){
   this.element = element;
   this.eventName = eventName;
   this.hasBeenSent = false;
   var self = this;
   window.$(window).scroll(function() {
     self.checkScroll();
   });

   this.isScrolledIntoView = function(){
     var docViewTop = window.$(window).scrollTop(),
     docViewBottom = docViewTop + window.$(window).height(),
     docViewAvg = (docViewTop + docViewBottom) / 2,
     elemTop = window.$(self.element).offset().top,
     elemBottom = elemTop + window.$(self.element).height(),
     elemAvg = (elemTop + elemBottom) / 2;
     return (elemBottom <= docViewBottom);
   }
   
   this.checkScroll = function(){
     if (!this.hasBeenSent && this.isScrolledIntoView()) {
       window.optimizely = window.optimizely || [];
       window.optimizely.push(['trackEvent', this.eventName]);
       this.hasBeenSent = true;
     }
   }
 }

 // Usage Example
 var scrollMyDiv = new window.trackScrolling('#myDiv', 'scrolled_to_mydiv');
 var scrollBottom = new window.trackScrolling('.footer', 'scrolled_to_bottom');

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

Access data on page

These are two examples of 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';

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

Get off-line 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
 }

Redirect - Add query parameter to URL

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

/* _optimizely_redirect = custom_add_query_param */
var newQuery = "[PARAM_NAME]=[PARAM_VALUE]";  // Replace [PARAM_NAME] and [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.
 */

/* _optimizely_redirect = custom_new_path */      
var newPath = "/[NEW_PATH]";  // Replace [NEW_PATH] with your new path, but keep the '/'
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 on 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.
 */

/* _optimizely_redirect = custom_new_domain */
var _optly = {redir: document.createElement("a")};
_optly.redir.href = window.location.href;
_optly.redir.hostname = "[NEW_DOMAIN]";  // Change [NEW_DOMAIN] to the new domain, NOT including the protocol
window.location.replace(_optly.redir.href);

Redirect - Keep 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]
 */

/* _optimizely_redirect = custom_keep_hash */
var _optly = {redir:document.createElement("a")};
_optly.redir.href = "[REDIRECT_URL]";  // Replace [REDIRECT_URL] to the new URL
_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);