HomeGuidesAPI Reference
Submit Documentation FeedbackJoin Developer CommunityOptimizely GitHubOptimizely NuGetLog In

Utils

Returns a utils object that includes useful functions for developing experiences.

Syntax

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

Parameters

Parameter and TypeChild AttributeDescription
utils
string
N/AThe argument indicating to get the utils object. Required.

Return value

Parameter and TypeChild AttributeDescription
UtilsObjectN/AThe utils object that contains a number of useful functions for developing experiences.
observeSelector
function[observeSelector]
Child attribute of type UtilsObjectRun a callback whenever an element changes.
poll
function[poll]
Child attribute of type UtilsObjectA setInterval wrapper.
waitUntil
function[waitUntil]
Child attribute of type UtilsObjectWait until the provided function returns true.
waitForElement
function[waitForElement]
Child attribute of type UtilsObjectReturns a Promise that is resolved with the first HTMLDomElement that matches the supplied selector.

Example Call

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

Example Return Value

utils.waitForElement(selector);
utils.observeSelector(selector, callback, options);
utils.poll(callback, delay);
utils.waitUntil(conditionFn);

Description

Optimizely Web uses some common functions to deliver experiences. You can also use those functions to write your own custom experiences.

waitForElement()

Returns a Promise that is resolved with the first HTMLDomElement that matches the supplied selector.

Syntax

utils.waitForElement(selector);

Parameters

Parameter and TypeChild AttributeDescription
selector
string
N/AA CSS selector indicating the element to wait for. Required.

Return value

Parameter and TypeChild AttributeDescription
PromiseN/AAn ES6-style Promise that will be resolved with the matching element.

Example Call

utils.waitForElement("h2");

Description

Returns a Promise that's resolved with the first HTMLDomElement that matches the supplied selector. This is commonly used to make adjustments to the element that you're waiting for when the promise is fulfilled.

Examples

Change the color of an element

Wait for an element to be loaded on the dom and change the color as soon as it has become available.

Example code for changing the color of an element

// Retrieve the utils library
var utils = window["optimizely"].get('utils');

// Wait for the footer element to appear in the DOM, then change the color
utils.waitForElement('.footer').then(function(footerElement) {
  footerElement.style.color = 'black';
});

observeSelector()

Run a callback whenever an element changes.

Syntax

utils.observeSelector(selector, callback, options);

Parameters

Parameter and TypeChild AttributeDescription
selector
string
N/AA CSS selector indicating the element to wait for. Required.
callback
function
N/AThe function that will be executed when the element indicated by the selector changes. The first argument is the exact element that changed. Required.
options
ObserverOptions
N/ATiming configuration options. Required.
timeout
integer or null
Child attribute of type ObserverOptionsNumber of milliseconds or null. Default to null (i.e., no timeout).
once
Boolean
Child attribute of type ObserverOptionsOnly invoke the callback on the first match.
onTimeout
function
Child attribute of type ObserverOptionsIf timeout is specified and no elements match, execute timeout callback.

Return value

Parameter and TypeChild AttributeDescription
functionN/AA function that can be executed to unobserve selector.

Example Call

utils.observeSelector(".productPrice", function(priceElement) {
  priceElement.style.fontSize = '30px';
  priceElement.style.color = 'red';
}, {
  "timeout": 6000,
  "once": true,
  "onTimeout": function() {
    console.log("Stopped observing");
  }
});

Description

This utility provides a subset of the functionality of a MutationObserver, allowing you to run a function whenever a DOM selector changes. Given a CSS selector and a callback, this function will invoke the supplied callback whenever a new element appears in the DOM matching the supplied selector.

poll()

A setInterval wrapper.

Syntax

utils.poll(callback, delay);

ParametParameter and Typeers

Parameter and TypeChild AttributeDescription
callback
function[Callback]
N/AFunction to be executed on the interval specified by delay. Required.
delay
integer
N/AMilliseconds to wait in between each callback invocation. Required.

Return value

Parameter and TypeChild AttributeDescription
functionN/AReturns a function that cancels the polling.

Example Call

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

var cancelPolling = utils.poll(function() {
  timeRemaining = timeRemaining - 1000;

  // Update message based on how much time is remaining
  if (timeRemaining > 0) {
    var date = new Date(timeRemaining);
    headerElement.innerHTML = 'You have ' + date.getMinutes() + ':' + date.getSeconds() + ' before your reservation expires.';
  } else {
    headerElement.innerHTML = 'Your reservation has expired';
    cancelPolling();
  }
}, 1000);

Description

The poll function convenient wrapper around the setInterval function.

waitUntil()

Wait until the provided function returns true.

Syntax

utils.waitUntil(conditionFunction);

Parameters

Parameter and TypeChild AttributeDescription
conditionFunction
function
N/AA function that executes synchronously and returns a truthy value when the condition is met. Required.

Return value

Parameter and TypeChild AttributeDescription
PromiseN/AAn ES6-style Promise that will be resolved with the matching element.

Example Call

utils.waitUntil(function() {
  var productsShownOnThePage = document.querySelectorAll('.product-listing');
  return productsShownOnThePage && productsShownOnThePage.length > 200;
});

Description

This utility accepts a function that returns a Boolean value and returns a Promise that resolves when the supplied function returns true.

Examples

Warn after scrolling

Show the visitor an alert after the visitor has scrolled a significant distance down the page.

Example code for Warn after scrolling

// Retrieve the utils library
var utils = window["optimizely"].get('utils');

// We have infinite scroll enabled on the site. Wait until more than 200 products have been shown
// to prompt the user to try out our filter by color feature
utils.waitUntil(function() {
  var productsShownOnThePage = document.querySelectorAll('.product-listing');
  return productsShownOnThePage && productsShownOnThePage.length > 200;
}).then(function() {
  alert('Not finding what you\'re looking for? Try narrowing down your search using our new filter by color feature');
});