Campaign Design API > Reference

Reference summary

This section provides reference documentation for version 1.9 of the Maxymiser Campaign Design Javascript API (API).

Below is a summary of the available methods, functions, properties and variables for you to design campaigns using the API.

Methods

You can use chaining to tie multiple API calls together into one statement to save space in code and provide a logical flow of events in scripts. Chaining items (such as actions or hide/show scripts) together allows you to easily follow how the script is executed. For reference on the objects that you can chain together, check the returned values type for the API methods.

The following table shows all the available methods:

Module Availability Description Methods
Campaign Campaign scripts Use to retrieve campaign-specific data such as generated experiences, etc. clearData
getData
getElements
getExperience
getName
getRecommendations
getStyles
isDefault
setData
Site Site and campaign scripts Use to store the experiences generated for all active campaigns on the current page. getPageExperiences
Dom

Site and campaign scripts

Use to apply CSS to the current page. addCss
addListener
bringToFront
changeImageBanner
changeLinkUrl
changeStyle
editHtml
freeMove
getNodesAttribute
guidedMove
hide
insertHtmlAbove
insertHtmlBelow
insertHtmlWithin
insertImageBannerAbove
insertImageBannerBelow
insertImageBannerWithin
remove
removeCss
removeListener
resize
setNodesAttribute
Renderer

Campaign scripts

Use to retrieve and display campaign content on a page. getContent
hide
runVariantJs
show
showAll
unhideAfter
waitUntilDom
waitForElement
when
Actions Site and campaign scripts Use to capture actions during a campaign and send the information to the Content Generator. postpone
send
set
trackClicks
Visitor Site and campaign scripts Use to retrieve and send visitor data, such as gender or age, to the Content Generator. clearData
getAttr
getData
getServerAttrs
navigateTo
removeAttr
removeId
requestPage
setAttr
setData
setId
storeAttr
storeId
Cookies Site and campaign scripts Use to integrate with 3rd-party logic. get
remove
set
Events Site and campaign scripts Use to share campaign logic between different scripts. domReady
off
on
trigger
Deferred Site and campaign scripts Use to manage the results for asynchronous tasks. Deferred
promise
always
done
fail
notify
notifyWith
progress
reject
rejectWith
resolve
resolveWith
state
then
Recommendations Site and campaign scripts Use to retrieve recommended products getProducts
requestPage
setCategoryFilter
setProductFilter
Modules Site and campaign scripts Use to introduce custom functionality into your campaigns define
require
Widgets Site and campaign scripts Use to embed widgets on your website pages createCallout
createLightbox
createNotification

Properties

The following table shows all the available properties:

Property Description
campaign.scope Use to share campaign-relevant data between campaign scripts on the same page.
site.scope Use to share data between campaigns or site scripts on the same page.

Functions

The following table shows the available function:

Function Description Availability
when Instantiates Master-Deferred from a set of Deferred objects / functions. Site and campaign scripts

Variables

The following table shows the available variables:

Variable Description Availability
html Stores the HTML data of the variant above the script node where the variable is called. In case multiple script nodes exist in a variant, every script will have its own html variable value corresponding the HTML data between itself and the previous script node. Variant scripts
css Stores the CSS data of the variant above the script node where the variable is called. In case multiple script nodes exist in a variant, every script will have its own css variable value corresponding the stylesheet content between itself and the previous script node. Variant scripts

Examples

Campaign

Use the Campaign module in campaign scripts to retrieve data for a campaign.

Reference table

Method Description Return type
clearData Removes custom variable data from the campaign's persistent storage.
getData Retrieves the value of the custom variable from the campaign's persistent storage. *
getElements Gets the content of all variants generated for the given visitor on the current page in JSON format. Object
getExperience Gets information about the variants generated for the current campaign. Object
getName Gets the campaign name. String
getRecommendations Gets the recommended products that arrived with the campaign. Campaign type should be set to MaxRecommend. Array<Object>
getStyles Retrieves CSS text from campaign's HTML sources. Array<String>
isDefault Identifies whether only default variants were generated on the page for the given campaign. Boolean
setData Saves the value of the custom variable to the campaign's persistent storage, so it can be retrieved on other site pages using the campaign.getData() method.

Property Variable type Description
scope Object Editable campaign namespace for reusable parameters, so that they are available for use between campaign scripts on a page.

Members

events - implement events localized on a campaign level (see the Events module for more information about event-driven scripts).

Methods

clearData( name )

Removes custom variable data from the campaign's persistent storage.

Parameters

Name Description Type
name Name of the variable. String

Code example

campaign.clearData('purchase-total');

getData( [name] ) → {*}

Retrieves the value of the custom variable from the campaign's persistent storage. Returns undefined for data that does not exist.

Parameters

Name Description Type
name Optional name of the variable that you have passed to campaign.setData() method. Leave blank to retrieve all the data set by current campaign for the given visitor. String

Code example

var visits = campaign.getData('page-visits');

getElements() → {Object}

Gets the content of all variants generated for the given visitor on the current page in JSON format.

Returned object nesting

{
'Element1Name': {
{
'GeneratedVariantName': '...',
'Order': ...,
'Data': [{
'Type': 'Html',
'Data': '...',
'Attrs': {}
},
{
'Type': 'Script',
'Data': '...',
'Attrs': {}
}]
},
'Element2Name': {
...
},
}

Code example

var variantContent = campaign.getElements()[ "HPBanner" ].Data;

getExperience() → {Object}

Gets information about the variants generated for the current campaign.

Returned object nesting

{
'Element1Name': 'GeneratedVariantName',
'Element2Name': 'GeneratedVariantName',
...
}

Code example

var colorVariantName = campaign.getExperience()[ "Color" ];
$('#cta').css('color', colorVariantName);

getName() → {String}

Gets the campaign name.

Code example

var campaignName = campaign.getName();

getRecommendations() → {Array<Object>}

Gets the recommended products that arrived with the campaign. Campaign type should be set to MaxRecommend.

Code example

var products = campaign.getRecommendations();
for ( var i = 0; i < products.length; i++ ) {
// ... do something with all the products that arrived
}

getStyles( [idAttribute] ) → {Array<String>}

Retrieves CSS text from campaign's HTML sources of the variants generated on the current page.

Parameters

Name Description Type
idAttribute Optional ID attribute of the target CSS node String

Code example

// Variant HTML
var i,
campaignStyles = campaign.getStyles();

dom.addCss(campaignStyles.join());

isDefault() → {Boolean}

Identifies whether only default variants were generated on the page for the given campaign.

In case this method is called when campaign has not been generated yet, it throws an exception. This was done to avoid confusion with the implicitly converted value campaign.isDefault() may return.

Code example

if (!campaign.isDefault()) {
renderer
.hide(...)
.waitFor(...)
...
}

setData( name, value [, expires] ) → {Visitor}

Saves the value of the custom variable to the campaign's persistent storage, so it can be retrieved on other site pages using the campaign.getData() method.

The main difference between campaign.setData and visitor.setData is where the data is available. You can use campaign.setData to store campaign-specific information that will not be available for any other campaign. For instance, you may need to create only one campaign that runs if a certain banner was shown on a previous page. Whether or not the banner was shown to the user on a previous page can be stored with campaign.setData and then retrieved with campaign.getData within the scripts of the same campaign only.

Parameters

Name Description Type
name Name of the variable. String
value Value of the variable *
expires Optional. Variable's life time in days. The default value is '0' - this means 'session' Number

Code example

// Script #1
campaign.setData('SeenOffers', 'Yes');

// Script #2
actions.send('Purchase', 1, campaign.getData('SeenOffers'));

Properties

scope → {Object}

Editable property to be used for data sharing between different scripts on a page.

Code example

// script #1
campaign.scope.basketValue = $("#total").text();
// script #2
actions.set("Purchase", parseInt(campaign.scope.basketValue, 10));
// script #3
if (campaign.scope.basketValue > 10) {
$("banner").html("Get 10% off!");
}

Examples

Basic example - skip rendering of the default experience

After your campaign arrives to the page with the Content Generator response, you can check the experience that was generated. When the experience to be shown is the default content, you can skip content hiding, using a campaign script, since content replacement is not required. See the following example:

if (!campaign.isDefault()) {
renderer
// hiding target node
.hide('...')
...

}

Basic example - apply dynamic variant

If you have several alternative variants based on the same HTML/CSS template, it may be easier to combine common logic and experiences using a campaign script. See the following example:

// get generated variant names: {'ElementName': 'VariantName'}
var genInfo = campaign.getExperience();
// save button source to campaign namespace
campaign.scope.buyButtonSrc = '/images/' + genInfo['Button'] + '.png';
renderer
// hiding target node
.hide('...')

The following example shows the HTML for the variant:

<style type="text/css">
.cta {
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
}
</style>

<script type="text/javascript">
jQuery('.cta').html('<img src="' + campaign.scope.buyButtonSrc + '">');
</script>

Basic example - persistent data storage

To pass information between pages or browser sessions for a specific visitor, you can use cookies to automatically store custom visitor data, and then use a campaign script that is mapped to the campaign page, to pass the visitor data to storage. See the following example:

function lowerThan7(nights) {
if (nights < 7) {
return 'less than 7';
} else {
return 'not less than 7';
}
}

events.domReady(function() {
var numberOfNights = jQuery('#nights').val();
campaign.setData('numberOfNights', lowerThan7(numberOfNights));
});

To retrieve the data from storage, use a campaign script that is mapped to the action page. See the following example:

actions.send('Confirmation', '1', campaign.getData('numberOfNights'));

Advanced example - process content from a campaign script

You can specify how content is applied to a page (i.e. how experiences are rendered on a page), by using the campaign.getElements() method in a campaign script.

In this scenario you would not need to call renderer.runVariantJs() method to avoid duplicate content application. If a campaign is not rendering correctly, ensure this method call is included in the campaign script. Without this call, the variant's contents are not initialized, and the campaign shows the default content in all variants instead.
// Campaign Script
var buttonHTML = '';

function getVariantHTML(elementName) {
var elementContentChunks = campaign.getElements[ elementName ];
for (var i = 0; i < elementContentChunks.length; i++) {
if (elementContentChunks[i].Type === 'Html') {
return elementContentChunks[i].Data;
}
}
}

buttonHTML = getVariantHTML("Shape")
.replace(/#color#/, getVariantHTML("Color"))
.replace(/#label#/, getVariantHTML("Label"));

...

Advanced example - share variables across campaign scripts

Campaign scripts and campaign variants do not share namespaces to avoid code conflicts. To pass data between scripts, you need to use campaign.scope:

// Campaign Script #1
campaign.scope.isMobile = /(iPad|iPhone|iPod|Android)/g.test(navigator.userAgent);

// Variant HTML
<script type="text/javascript">
if (campaign.scope.isMobile) {
$('body').css('background-attachment', 'scroll');
}
</script>

Site

Use the Site module within site and campaign scripts to store the experiences generated for all active campaigns on the current page. The Site module also provides a shared namespace for all campaigns.

Reference table

Method Description Return type
getPageExperiences Gets information about the variants generated for all campaigns on the current page. Object

Property Description Variable type
scope Editable site-wide namespace for reusable parameters, so that they are available for use in different scripts on a page. Object

Examples

Methods

getPageExperiences() → {Object}

Gets information about the variants generated for all campaigns on the current page.

Returned object nesting

{
'Campaign1Name': {
'Element1Name': 'GeneratedVariantName',
'Element2Name': 'GeneratedVariantName',
},
'Campaign2Name': {
...
},
...
}

Code example

var genInfo = site.getPageExperiences();

Properties

scope → {Object}

Editable property to be used for data sharing between different scripts on a page.

Code example

// script #1
site.scope.pageId = document.title.match(/\d+/)[0];
// script #2
var pageId = site.scope.pageId;

Examples

3rd-party integration

You can use a site script to integrate with a 3rd-party application that accepts generated campaign info as an argument. See the following example:

// get generated experiences: {'CampaignName': {'ElementName': 'VariantName'}[, {...}]}
var genInfo = site.getPageExperiences();
GoogleAnalytics.sendData(genInfo);

Sharing data across campaigns

You can share data between different scripts or define functions that will be available across a site. See the following example for the code in a site script:

site.scope.md5 = function(param){
/* do something here*/
}

The following example shows the code in a campaign script:

var hash = site.scope.md5(campaign.getName());

Dom

Use the Dom module within site and campaign scripts for DOM manipulation.

Reference table

Method Description Return type
addCss Applies CSS rules to a page. Dom
addListener Assigns DOM event handler to the selected elements.
bringToFront Changes the z-index value of the target node to the highest value across all the DOM nodes on the page.
changeImageBanner Updates an existing image or banner.
changeLinkUrl Sets the 'href' attribute value of the target node.
changeStyle Updates the inline style of the target node.
editHtml Replaces the innerHTML value of the target node.
getNodesAttribute Reads the specified attribute values for the selected elements. Promise
freeMove Changes the relative position of the target node.
guidedMove Changes the relative placement of the target node within its parent in relation to the siblings.
hide Hides the target node.
insertHtmlAbove Adds HTML content above the target node.
insertHtmlBelow Adds HTML content below the target node.
insertHtmlWithin Adds HTML content to the end of the content of the target node.
insertImageBannerAbove Creates an image banner before the target node.
insertImageBannerBelow Creates an image banner after the target node.
insertImageBannerWithin Creates an image banner within the target node.
remove Deletes the target node from the DOM.
removeCss Removes the CSS that was previously added. Dom
removeListener Removes the specified DOM event handler from the selected elements.
resize Changes height and width of the target node.
setNodesAttribute Sets the specified attribute values for the selected elements.

Example

Methods

addCss( css [, alias] ) → {Dom}

Applies CSS rules to a page.

Parameters

Name Description Type
css CSS rule(s) to be applied immediately. String
alias Optional custom identifier for the CSS rule(s) that have been applied (you can deactivate this later as required). This parameter is useful when you want to apply CSS rules for a limited period of time. String

Code example

dom
.addCss('body { visibility: hidden }', 'T4HPBanner')
.addCss('.banner { margin-left: 100px }');

addListener( selector, eventName, handler )

Assigns DOM event handler to the selected elements.

Parameters

Name Description Type
selector Target DOM node(s) described by a CSS selector. String
eventName Target event name to listen for. String
handler Reference to the event handler. Function

Code example

dom.addListener('submit', 'click', function() {
actions.send('register', '1');
});

bringToFront( element [, zIndex] )

Changes the z-index value of the target node to the highest value across all the DOM nodes on the page.

This method iteratively waits (with a 50 ms interval) for the target nodes to appear, so that the change can be applied even if content arrives asynchronously.

Parameters

Name Description Type
element Element(s) or CSS path to be processed. HTMLElement, array <HTMLElement> or string
zIndex Optional z-index value. By default, the value is the 'maximum z-index value on the page +10'. Number

Code example

dom.bringToFront('.floating-menu');

changeImageBanner( element, properties )

Updates an existing image or banner.

This method iteratively waits (with a 50 ms interval) for the target nodes to appear, so that the change can be applied even if content arrives asynchronously.

Parameters

Name Description Type
element Element(s) or CSS path to be processed. HTMLElement, array <HTMLElement> or string
properties

Optional banner properties:

  • linkUrl ← String
    'href' value; if omitted image is not wrapped with <a> tag.
  • imageUrl ← String
    Image 'src' attribute value; if you don't pass a property, the attribute is not added within the node attribute.
  • imageAlt ← String
    Image 'alt' attribute value; if you don't pass a property, the attribute is not added within the node attribute.
  • imageTitle ← String
    Image 'title' attribute value; if you don't pass a property, the attribute is not added within the node attribute.

Object

Code example

dom.changeImageBanner('.view-basket', {
linkUrl: '/basket-v2/'
});

changeLinkUrl( element, value )

Sets the 'href' attribute value of the target node.

This method iteratively waits (with a 50 ms interval) for the target nodes to appear, so that the change can be applied even if content arrives asynchronously.

Parameters

Name Description Type
element Element(s) or CSS path to be processed. HTMLElement, array <HTMLElement> or string
value New 'href' attribute value. String

Code example

dom.changeLinkUrl('.view-basket', '/basket-v2/');

changeStyle( element, cssRules )

Updates the inline style of the target node.

This method iteratively waits (with a 50 ms interval) for the target nodes to appear, so that the change can be applied even if content arrives asynchronously.

Parameters

Name Description Type
element Element(s) or CSS path to be processed. HTMLElement, array <HTMLElement> or string
cssRules New CSS rules for the target node. String

Code example

dom.changeStyle('.product-description', 'border: 1px solid #333; opacity: .7');

editHtml( element, html )

Replaces the innerHTML value of the target node.

This method iteratively waits (with a 50 ms interval) for the target nodes to appear, so that the change can be applied even if content arrives asynchronously.

Parameters

Name Description Type
element Element(s) or CSS path to be processed. HTMLElement, array <HTMLElement> or string
html New innerHTML value. String

Code example

dom.editHtml('.buy-btn', '<a href="/buy-me/">Buy</a>');

getNodesAttribute( selector, name ) → {Promise}

Reads the specified attribute values for the selected elements.

Parameters

Name Description Type
selector Target DOM node(s) described by a CSS selector. String
name Target attribute name. String

Code example

dom
.getNodesAttribute('.buy-btn', 'href')
.done(function(attrValues) {
for (var i = 0; i < attrValues.length; i++) {
// ...
}
});

freeMove( element, deltaX, deltaY )

Changes the relative position of the target node.

This method iteratively waits (with a 50 ms interval) for the target nodes to appear, so that the change can be applied even if content arrives asynchronously.

Parameters

Name Description Type
element Element(s) or CSS path to be processed. HTMLElement, array <HTMLElement> or string
deltaX X-axis shift in pixels (positive or negative). Number
deltaY Y-axis shift in pixels (positive or negative). Number

Code example

dom.freeMove('.product-description', 30, 5);

guidedMove( element, index )

Changes the relative placement of the target node within its parent in relation to the siblings.

This method iteratively waits (with a 50 ms interval) for the target nodes to appear, so that the change can be applied even if content arrives asynchronously.

Parameters

Name Description Type
element Element(s) or CSS path to be processed. HTMLElement, array <HTMLElement> or string
index New position of the target node compared to its siblings. Index starts from 0. Number

Code example

dom.guidedMove('.selected-products', 0);

hide( element )

Hides the target node.

This method iteratively waits (with a 50 ms interval) for the target nodes to appear, so that the change can be applied even if content arrives asynchronously.

Parameters

Name Description Type
element Element(s) or CSS path to be hidden via added 'visibility: hidden' style HTMLElement, array <HTMLElement> or string

Code example

dom.hide('.intro');

insertHtmlAbove( element, html )

Adds HTML content above the target node.

This method iteratively waits (with a 50 ms interval) for the target nodes to appear, so that the change can be applied even if content arrives asynchronously.

Parameters

Name Description Type
element Element(s) or CSS path to be processed. HTMLElement, array <HTMLElement> or string
html HTML to be added. String

Code example

dom.insertHtmlAbove('.product-description', 'Get 10% off by purchasing this product now!');

insertHtmlBelow( element, html )

Adds HTML content below the target node.

This method iteratively waits (with a 50 ms interval) for the target nodes to appear, so that the change can be applied even if content arrives asynchronously.

Parameters

Name Description Type
element Element(s) or CSS path to be processed. HTMLElement, array <HTMLElement> or string
value HTML to be added. String

Code example

dom.insertHtmlBelow('.product-description', 'Get 10% off by purchasing this product now!');

insertHtmlWithin( element, html )

Adds HTML content to the end the target node content.

This method iteratively waits (with a 50 ms interval) for the target nodes to appear, so that the change can be applied even if content arrives asynchronously.

Parameters

Name Description Type
element Element(s) or CSS path to be processed. HTMLElement, array <HTMLElement> or string.
value HTML to be added. String

Code example

dom.insertHtmlWithin('.product-description', 'Get 10% off by purchasing this product now!');

insertImageBannerAbove( element, properties )

Creates an image banner before the target node.

Parameters

Name Description Type
element Element(s) or CSS path to be processed. HTMLElement, array <HTMLElement> or string
properties

Optional banner properties:

  • linkUrl ← String
    'href' value; if the omitted image is not wrapped with the <a> tag.
  • imageUrl ← String
    Image 'src' attribute value; if you don't pass a property, the attribute is not added within the node attribute.
  • imageAlt ← String
    Image 'alt' attribute value; if you don't pass a property, the attribute is not added within the node attribute.
  • imageTitle ← String
    Image 'title' attribute value; if you don't pass a property, the attribute is not added within the node attribute.
Object

Code example

dom.insertImageBannerAbove('.product-description', {
linkUrl: '/discount/',
imageUrl: '/assets/discount.png',
imageAlt: 'Get 10% off by purchasing this product now!',
imageTitle: 'Get 10% off by purchasing this product now!'
});

insertImageBannerBelow( element, properties )

Creates an image banner after the target node.

Parameters

Name Description Type
element Element(s) or CSS path to be processed. HTMLElement, array <HTMLElement> or string
properties

Optional banner properties:

  • linkUrl ← String
    'href' value; if omitted image is not wrapped with <a> tag.
  • imageUrl ← String
    Image 'src' attribute value; if you don't pass a property, the attribute is not added within the node attribute.
  • imageAlt ← String
    Image 'alt' attribute value; if you don't pass a property, the attribute is not added within the node attribute.
  • imageTitle ← String
    Image 'title' attribute value; if you don't pass a property, the attribute is not added within the node attribute.
Object

Code example

dom.insertImageBannerBelow('.product-description', {
linkUrl: '/discount/',
imageUrl: '/assets/discount.png',
imageAlt: 'Get 10% off by purchasing this product now!',
imageTitle: 'Get 10% off by purchasing this product now!'
});

insertImageBannerWithin( element, properties )

Creates an image banner into the target node.

Parameters

Name Description Type
element Element(s) or CSS path to be processed HTMLElement, array <HTMLElement> or string
properties

Optional banner properties:

  • linkUrl ← String
    'href' value; if omitted image is not wrapped with <a> tag.
  • imageUrl ← String
    Image 'src' attribute value; if you don't pass a property, the attribute is not added within the node attribute.
  • imageAlt ← String
    Image 'alt' attribute value; if you don't pass a property, the attribute is not added within the node attribute.
  • imageTitle ← String
    Image 'title' attribute value; if you don't pass a property, the attribute is not added within the node attribute.
Object

Code example

dom.insertImageBannerWithin('.product-description', {
linkUrl: '/discount/',
imageUrl: '/assets/discount.png',
imageAlt: 'Get 10% off by purchasing this product now!',
imageTitle: 'Get 10% off by purchasing this product now!'
});

remove( element )

Deletes the target node from the DOM.

This method iteratively waits (with a 50 ms interval) for the target nodes to appear, so that the change can be applied even if content arrives asynchronously.

Parameters

Name Description Type
element Element(s) or CSS path that describes a set of elements to be deleted from DOM. HTMLElement, array <HTMLElement> or string

Code example

dom.remove('.intro');

removeCss( alias ) → {Dom}

Removes the CSS that was previously added.

Parameters

Name Description Type
alias A custom identifier of the CSS node created by dom.addCss() String

Code example

dom
.addCss('.loading { visibility: visible }', 'T4HPBanner')
...
.removeCss('T4HPBanner');

removeListener( selector, eventName, handler )

Removes the specified DOM event handler from the selected elements.

Parameters

Name Description Type
selector Target DOM node(s) described by a CSS selector. String
eventName Target event name to remove the handler from. String
handler Reference to the event handler. Function

Code example

var trackRegistration = function() {
actions.postpone('register', '1');
}
dom.addListener('submit', 'click', trackRegistration);
...
dom.removeListener('submit', 'click', trackRegistration);

resize( element, width, height, deltaX, deltaY )

Changes the height and width of the target node.

This method iteratively waits (with a 50 ms interval) for the target nodes to appear, so that the change can be applied even if content arrives asynchronously.

Parameters

Name Description Type
element Element(s) or CSS path to be processed. HTMLElement, array <HTMLElement> or string
width New width of the target node in pixels. Number
height New height of the target node in pixels. Number
deltaX X-axis shift in pixels (positive or negative). Number
deltaY Y-axis shift in pixels (positive or negative). Number

Code example

dom.resize('.buy-btn', 200, 80, 0, 0);

setNodesAttribute( selector, name, value )

Sets the specified attribute values for the selected elements.

Parameters

Name Description Type
selector Target DOM node(s) described by a CSS selector. String
name Target attribute name. String
value Target attribute value. String

Code example

dom.setNodesAttribute('.buy-btn', 'href', '/basket/');

Examples

Apply variant CSS

To apply variant CSS, use the following sample code in a Content Variant:

<style type="text/css">
body {
color: #030;
}
</style>

<script type="text/javascript">
dom.addCss(css);
</script>

Renderer

Use the Renderer module in campaign scripts to retrieve and display campaign content on a page.

You can either use Maxymiser's out-of-the-box logic to retrieve and show campaign content, or customize it as required.

Reference table

Method Description Return type
getContent Makes a request to the Content Generator to get campaign content. Promise
hide Hides the test areas for replacement with alternative content. Renderer
runVariantJs Applies an element to the page immediately. Renderer
show Shows content using the given alias identifier. Renderer
showAll Shows all previously hidden content for the current campaign. Renderer
unhideAfter Automatically displays content after a specified time has elapsed. Renderer
waitUntilDom Executes the when() method before DOM is ready. Promise
waitForElement Checks if the specified element exists on the page and executes success and always callbacks. Promise
when renderer.when() is an alias to when() function Promise

Variable Type Description Availability
html String Stores the HTML data of the variant above the script node where the variable is called. In case multiple script nodes exist in a variant, every script will have its own html variable value corresponding the HTML data between itself and the previous script node. Variant scripts
css String Stores the CSS data of the variant above the script node where the variable is called. In case multiple script nodes exist in a variant, every script will have its own css variable value corresponding the stylesheet content between itself and the previous script node. Variant scripts

Examples

Methods

getContent( [virtualUrl] ) → {Promise}

Makes additional requests to the Content Generator to get campaign content. See the Deferred module for more information on 'promise'.

Parameters

Name Description Type
virtualUrl Optional URL value to be passed to the Content Generator. You cannot pass the same URL as the URL of the original page - this is to prevent looping. Leave blank to pass the default value: <campaign name> String

Code example

renderer
.getContent('T4HPBanner')
.always(function() {
renderer
.runVariantJs()
.showAll();
});

hide( cssSelector [, alias] ) → {Renderer}

Hides the test areas for replacement with alternative content.

The content you hide is automatically unhidden after 7 seconds. The default behavior of the API is to automatically call the renderer.unhideAfter method with a preset value of 7 seconds (7000 ms) on every campaign. This timeout is the default functionality to prevent accidentally hiding elements of a page and never showing them again (i.e. without calling renderer.show or renderer.showAll).

Parameters

Name Description Type
cssSelector

A CSS 'path' to the test areas. Used exclusively for hiding content. May either be a selector itself or contain CSS properties if default hiding properties do not work for you (default value is { position: relative; left: -10000px; top: -10000px })

A different logic is used for replacing content.

String
alias Optional custom identifier of applied CSS rules to deactivate them later if needed. Leave blank in case you'll use only renderer.showAll() method. String

Code example

renderer
.hide('.banner', 'BannerArea')
...
.show('BannerArea');

runVariantJs( [element] ) → {Renderer}

Applies an element to the page immediately. This method can be called when you want to replace the default content.

Parameters

Name Description Type
element Optional element name or element data object to be rendered. If this parameter is not set, all campaign variant scripts are executed. String

Code example

renderer
...
.always(function() {
renderer
.runVariantJs('Banner')
.showAll();
});

show( alias ) → {Renderer}

Shows content using the given alias identifier.

Parameters

Name Description Type
alias Custom identifier specified in the hide() method call. String

Code example

renderer
.hide('.banner', 'bannerArea')
...
.show('bannerArea')

showAll() → {Renderer}

Shows all the previously hidden content for the current campaign.

Code example

renderer
.hide('body')
...
.showAll();

unhideAfter( timeoutValue ) → {Renderer}

Automatically displays content after a specified time has elapsed.

You may need to override the default 7-second unhide in certain situations. For example, when a campaign is dependent on several AJAX calls on the page that may take longer than the pre-defined timeout. To eliminate the potential for flicker (momentary flashing of the default content) for this type of campaign, you may need to hide the test elements before they arrive to the page, and then wait for all the AJAX content to appear, so we can generate the campaign and perform unhiding.

Parameters

Name Description Type
timeoutValue Timeout value in milliseconds after which content will be automatically displayed. This method is automatically called inside any campaign with a pre-set value of "7000" (means "7 seconds"). If you want to disable the unhideAfter feature, pass "never" value as its argument. Number or string

Code example

renderer
.unhideAfter("never")
.hide("body")
.when(function() {
return document.getElementById('product-data');
})
.done(function() {
renderer
.runVariantJs();
})
.always(function() {
renderer
.showAll();
});

waitUntilDom( successCondition ) → {Promise}

Executes the when() method with the specified success() condition and pre-defined reject() condition - DOM readiness.

Parameters

Name Description Type
successCondition A function that serves as an iterative condition. If successCondition() returns false, nothing happens and iterative checks will be continued. If it returns a non-false value, all done and always callbacks are triggered. Function

Code example

renderer
...
.waitUntilDom(function() {
return document.getElementById('footer');
})
.done(function() {
renderer
.runVariantJs()
.showAll();
})
.fail(function() {
renderer
.showAll();
});

waitForElement( cssSelector ) → {Promise}

Checks if the specified element exists on the page and as soon as it appears, executes success and always callbacks. The method continues with iterative checks until DOM is ready, then fail callbacks are triggered.

Parameters

Name Description Type
cssSelector A CSS selector that describes an area on the page. If document.querySelectorAll(cssSelector) returns 0 results, nothing happens and iterative checks continue. If the method returns at least 1 node, all done and always callbacks are triggered. String

Code example

renderer
...
.waitForElement('.banner')
.done(function() {
renderer
.runVariantJs()
.showAll();
})
.fail(function() {
renderer
.showAll();
});

when( ... ) → {Promise}

renderer.when() is an alias to when() function.

Variables

html → {String}

Stores the HTML data of the variant above the script node where the variable is called. Exists only within Variant script nodes.

html

Code example

<a href="/">Home</a>

<script type="text/javascript">
jQuery(".nav").prepend(html);
</script>

css → {String}

Stores the CSS content of the variant above the script node where the variable is called. Exists only within Variant script nodes.

html

Code example

<style type="text/css">
body {
color: #030;
}
</style>

<script type="text/javascript">
dom.addCss(css);
</script>

Examples

Basic example - render campaign content

Source code for original page:

<td class="add-to-cart">
<input type="submit" value="" name="MyBuy" class="wpsc_buy_button" id="add_product_175_submit_button">
</td>
...
<div id="footer">...</div>

Use the following campaign script to render campaign content:

renderer
// hiding a node with class "add-to-cart"
.hide('td.add-to-cart')
// waiting for "#footer" to arrive
.waitForElement('#footer')
.then(function() {
renderer
// applying all alternative Elements to the page
.runVariantJs()
// un-hiding hidden content
.showAll();
});

The code results in the change highlighted in the example below:

Default page

Alternative page

Remember to map the campaign script to the test page in the Maxymiser UI.

Basic example - identify if a campaign applies to a page

There may be cases where you cannot identify your test page using the URL, for instance when several pages share the same URL. You can validate whether the campaign is applicable to the page using the following steps:

  1. Iteratively check whether page-specific content has appeared on the page.
  2. As soon as a decision can be made, send a request for a virtual page or finish the process.
  3. Apply the campaign to the page if required.

The steps are summarised in the following sample code:

renderer
// hiding a node with class "add-to-cart"
.hide('td.add-to-cart')
// checking whether it's the 5th step of purchase process
.waitUntilDom(function() {
var image = document.getElementById('navigation');
if (image && image.src.indexOf('step5') !== -1) {
return true;
} else {
return false;
}
})
.then(function() { // done callback
renderer
// making request to a virtual page that has mask 'Purchase - Step 5'
.getContent('Purchase - Step 5')
// applying all alternative Elements
.then(function() {
renderer
.runVariantJs()
.showAll();
});
},
function() { // fail callback
renderer
.showAll();
});
});
Remember that the test content should be shown as soon as the condition is not satisfied, or after the campaign has been applied to the page.

Basic example - get campaign data

You can use an auxiliary campaign module to get campaign-specific data. For example, the campaign.isDefault() method that returns 'true', if all the generated experiences are 'Default'.

// render only if your campaign has alternative content
if (campaign.isDefault() === false) {
renderer

// hiding a node with class "add-to-cart"
...
}

See the Campaign module for more information.

Basic example - handle content on AJAX pages

On AJAX pages, content may arrive after the page load event. Use the when() method to wait for the specific element before and after DOM ready.

renderer
// hiding a node with class "add-to-cart"
.hide('td.add-to-cart')
// waiting for AJAX template to arrive
.when(function(){
return document.getElementById('step-5-bar');
})
.then(function() {
renderer
// applying all alternative Elements to the page
.runVariantJs()
// un-hiding hidden content
.showAll();
});

You can also establish the custom rendering logic. See the following examples:

// hiding a node with class "add-to-cart"
renderer.hide('td.add-to-cart');
// applying a global AJAX complete handler
jQuery(document).ajaxComplete(function() {
// checking whether Default has arrived
if (document.getElementById('step-5-bar')) {
renderer
.runVariantJs()
.showAll();
}
});

Advanced example - configure time before campaign content is displayed

To minimize coding errors, the Renderer module automates the process of showing content. You can configure the time that should elapse before content is displayed:

renderer.unhideAfter(2000);
// this content will be shown automatically in 2 seconds
// unless you show it manually before timeout expires
renderer.hide('td.add-to-cart');
...
renderer.unhideAfter("never");
// this content will not be shown automatically
renderer.hide('td.add-to-cart');
...

By default, timeout is set to expire 7 seconds after the last .hide() call in a campaign.

Actions

Use the Actions module in campaign and site scripts to capture actions during a campaign and send the information to the Content Generator.

Reference table

Method Description Return type
postpone Captures action data to be sent to the Content Generator in subsequent requests. Actions
send Sends all captured action data to the Content Generator. Promise
set Captures action data to be sent to the Content Generator when actions.send() is called. Actions
trackClicks Assigns an On-Click action tracking handler to a DOM node.

Examples

Methods

postpone( name [, value, attribute] ) → {Actions}

Captures action data to be sent to the Content Generator in subsequent requests.

Parameters

Name Description Type
name Action name as configured in the Maxymiser UI String
value Optional integer value of the action. Is set to 1 by default (e.g. one click, one form submission). For advanced action tracking, you can specify values such as basket value, registration period, etc. Integer
attribute Optional string to filter action reports by value (for example, currency, the part of the page that the user clicked, is logged in, etc) String

Code example

actions
.postpone('Click', '1')
.postpone('Purchase', '1299', 'USD');

send( [name, value, attribute] ) → {Promise}

Sends all captured action data to the Content Generator. See the Deferred article for more information on promise.

Parameters

Name Description Type
name Optional action name as configured in the Maxymiser UI String
value Optional integer value of the action. Is set to 1 by default (e.g. one click, one form submission). For advanced action tracking, you can specify values such as basket value, registration period, etc. Integer
attribute Optional string to filter action reports by value (for example, currency, the part of the page that the user clicked, is logged in, etc) String

Code example

actions
.set('Click', '1')
.set('Purchase', '1299', 'USD')
.send();

trackClicks( selector, parameters, guid ) → {Actions}

Assigns an On-Click action tracking handler to a DOM node.

Parameters

Name Description Type
selector Target DOM node(s) described by a CSS selector or a reference to the HTML element String or HTMLElement
parameters

Action properties:

  • name ← String
    Action name
  • value ← Number
    Optional value of the action. If you don't pass a value, the value defaults to `1`.
  • attribute ← String
    Optional attribute of the action.
Object
guid Unique ID of an action used in VCB, so that editing an action name or value in VCB changes only that instance of the action. String

Code example

actions.trackClicks('#change-details', {
name: 'ChangeDetClick',
value: 1
}, 1);

set( name [, value, attribute] ) → {Actions}

Captures action data to be sent to the Content Generator when actions.send() is called.

Parameters

Name Description Type
name Action name as configured in the UI String
value Optional integer value of the action. Is set to 1 by default (e.g. one click, one form submission). For advanced action tracking, you can specify values such as basket value, registration period, etc. Integer
attribute Optional string to filter action reports by value (for example, currency, the part of the page that the user clicked, is logged in, etc) String

Code example

actions
.set('Click', '1')
.set('Purchase', '1299', 'USD')
.send();

Examples

Basic example - track sales amount

Tracking sales amount:

// getting action information when DOM is ready
events.domReady(function() {
var price = jQuery('.price')
.text()
.replace('\.', '');
// passing gathered information to Maxymiser server
actions.send('Sale', price);
});

Basic example - track several actions

Tracking several actions:

actions
.set('ProductView', 1)
.set('CategoryView', 1, categoryName)
.send();

Basic example - track a postponed action

Postponed actions are useful for preventing data loss when there is an immediate browser redirect to another page when a visitor leaves a page.

Applying a click handler to track a postponed action:

jQuery('.buy').live('click', function() {
// this action will be tracked on the next page
actions.postpone('BuyButtonClick', 1);
});

Advanced click-through action tracking

If there are restrictions on tracking click-through actions on a specific page, you can do the following:

  1. Cancel the default behavior of the link or form that is triggered.
  2. Pass information about the action to the Content Generator.
  3. Replicate the default behavior of the link or form.

Here is an example:

// set handler when DOM is ready
events.domReady(function() {
jQuery('.more-information').bind('click', function() {
// save target
var link = this;
actions
.send('MoreInfo', 1)
// set 'always' callback to Promise
.always(function() {
location.assign(link.href);
});

// cancel default behavior
return false;
});
});

Visitor

Use the Visitor module in campaign and site scripts to retrieve and send visitor data, such as gender or age, to the Content Generator.

Reference table

Method Description Return type
clearData Removes custom variable data from persistent storage
getAttr Retrieves the value of the custom attribute that was saved using visitor.storeAttr().

String | undefined

getData Retrieves the custom variable value from persistent storage. *
getServerAttrs Returns attributes that are enabled for use in the browser. Object
navigateTo Redirects the visitor to the specified URL.
removeAttr Removes the value of a custom attribute from persistent storage. Visitor
removeId Removes the value of the external visitor ID from persistent storage. Visitor
requestPage Sends additional request to Maxymiser Content Generator. Promise
setAttr Captures custom attribute data to temporary storage to be sent to the Content Generator in subsequent page requests. Visitor
setId Captures the external visitor ID to temporary storage to be sent to the Content Generator. Visitor
setData Saves the custom variable value in persistent storage, so it can be retrieved on other site pages using visitor.getData(). Visitor
storeAttr Saves custom attribute data to permanent storage to be sent to the Content Generator in subsequent page requests. Visitor
storeId Saves the external visitor ID to permanent storage to be sent to the Content Generator in subsequent page requests. Visitor

Examples

Methods

clearData( name )

Removes custom variable data from persistent storage.

Parameters

Name Description Type
name Name of the variable String

Code example

visitor.clearData('purchase-total');

getAttr( name ) → {String | undefined}

Retrieves the value of the custom attribute that was saved using visitor.storeAttr(). Returns undefined for non-existing attributes.

Parameters

Name Description Type
name Name of the custom attribute configured in the Maxymiser UI String

Code example

var loggedIn = visitor.getAttr('LoggedIn');

getData( [name] ) → {*}

Retrieves the custom variable value from persistent storage. Returns undefined for data that does not exist.

Parameters

Name Description Type
name Optional name of the variable that you have passed to visitor.setData() method. Leave blank to retrieve all the data set for the current visitor. String

Code example

var visits = visitor.getData('site-visits');

getServerAttrs() → {Object}

Returns attributes that are enabled for use in the browser.

Attributes can be populated by using visitor.setAttr(), visitor.storeAttr(), or CRM import.

You can enable an attribute for use in the browser on the Personalisation Criteria page:

Code example

var popularCategory = visitor.getServerAttrs()['PopularCategory'];

navigateTo( targetUrl )

Redirects the visitor to the specified URL.

Parameters

Name Description Type
targetUrl The URL the visitor will be immediately redirected to. String

Code example

visitor.navigateTo('/category-alternative/');

removeAttr( name ) → {Visitor}

Removes the value of a custom attribute from persistent storage.

Parameters

Name Description Type
name Name of the custom attribute String

Code example

visitor.removeAttr('LoggedIn');

removeId( key ) → {Visitor}

Removes the value of the external visitor ID from persistent storage.

Parameters

Name Description Type
key External ID key bound to a specific data table. The value can be an integer from 1 to 5. Number

Code example

visitor.removeId(1);

requestPage( virtualUrl ) → {Promise}

Sends an additional request to Maxymiser's Content Generator to pass the parameters captured on the page and retrieve test data.

Parameters

Name Description Type
virtualUrl URL value to be passed to the Content Generator. To prevent looping, you cannot pass the same URL as the URL of the original page. Please note that in case an empty string is passed, the original page URL is used for page determination. String

Code example

visitor.setAttr('LoggedIn', 'Yes');
visitor.requestPage('Product Pages');

setAttr( name, value ) → {Visitor}

Captures custom attribute data to temporary storage to be sent to the Content Generator. This method allows Maxymiser to remember the attribute value only until the next manual request to the Content Generator (i.e., renderer.getContent or visitor.requestPage).

Parameters

Name Description Type
name Custom attribute name that corresponds to the configuration in the Maxymiser UI String
value Custom attribute value String

Code example

// Script #1
visitor.setAttr('LoggedIn', 'Yes');

// Script #2
renderer
.getContent()
.always(function() {
renderer
.runVariantJs()
.showAll();
});

setData( name, value [, expires] )

Saves the custom variable value in persistent storage, so it can be retrieved on other site pages using visitor.getData().

The main difference between campaign.setData and visitor.setData is where the data is available. visitor.setData stores visitor-specific information that will be available to all other campaigns. For example, you may need to store the type of account the user has on the website (e.g., basic, premium, etc.) to be used later in different campaigns.

Parameters

Name Description Type
name Variable name String
value Variable value String
expires Optional life time of variable (in days). "0" by default, meaning "session" Number

Code example

// Script #1
visitor.setData('SeenOffers', 'Yes');

// Script #2
actions.send('Purchase', 1, visitor.getData('SeenOffers'));

setId( key, value ) → {Visitor}

Captures the external visitor ID to temporary storage to be sent to the Content Generator. The external visitor ID is used to bind the data between a specific visitor and the custom data table imported/exported in the Maxymiser UI. This method allows Maxymiser to remember the attribute value only until the next manual request to the Content Generator (i.e., renderer.getContent or visitor.requestPage).

Parameters

Name Description Type
key External ID key bound to a specific data table. The value can be an integer from 1 to 5. Number
value External ID value that corresponds to the first column of the table. String

Code example

// Script #1
visitor.setId(1, '345987');

// Script #2
renderer
.getContent()
.always(function() {
renderer
.runVariantJs()
.showAll();
});

storeAttr( name, value ) → {Visitor}

Saves custom attribute data to permanent storage to be sent to the Content Generator in subsequent page requests. This method allows Maxymiser to remember the attribute value for all future page loads and Content Generator requests. The value is retained until it is overwritten with a new value.

Parameters

Name Description Type
name Custom attribute name as configured in the Maxymiser UI String
value Custom attribute value String

Code example

visitor.storeAttr('LoggedIn', 'Yes');

storeId( key, value ) → {Visitor}

Saves the external visitor ID to permanent storage to be sent to the Content Generator in subsequent page requests. The external visitor ID is used to bind the data between a specific visitor and the custom data table imported/exported in the Maxymiser UI. This method allows Maxymiser to remember the external ID value for all future page loads and Content Generator requests. The value is retained until it is overwritten with a new value.

Parameters

Name Description Type
key External ID key bound to specific data table (integer from 1 to 5) Number
value External ID value that corresponds to the first column of the table String

Code example

visitor.storeId(1, '345987');

Examples

In the Maxymiser UI, custom attributes are called Personalization Criteria.

Basic example - persistent custom attribute

Use the following code on the registration page:

// assign a click handler to the 'Register' button
jQuery('.register').live('click', function() {
var gender = jQuery('#gender').val();
visitor.storeAttr('gender', gender);
});

The 'gender' custom attribute is captured as soon as a visitor registers.

Basic example - custom attribute for a specific campaign

// get visitor age from the page
var visitorAge = jQuery('#vcAge').val();

// set visitor age value to corresponding Custom Attribute
visitor.setAttr('age', visitorAge);

renderer
// send request to Maxymiser for Page mask 'Test 23 - Product Offers'
.getContent('Test 23 - Product Offers')
// when content arrives...
.done(function() {
renderer
.runVariantJs();
});

Cookies

Use the Cookies module in campaign and site scripts to integrate with 3rd-party logic. To store data related to testing, use the setData() and getData() methods in the Campaign and Site modules.

Reference table

Method Description Return type
get Reads the value of the cookie. String | undefined
remove Retrieves the value of the custom attribute that was saved using visitor.storeAttr(). Cookies
set Retrieves the custom variable value from persistent storage. Cookies

Methods

get( name ) → {String | undefined}

Reads cookie value.

Parameters

Name Description Type
name Name of the cookie String

Code example

var isLoggedIn = cookies.get('logged-in');

remove( name [, properties] ) → {Cookies}

Deletes a cookie.

Parameters

Name Description Type
name Name of the cookie String
properties Optional properties of the cookie (every property is optional as well):
  • domain ← String
    Optional domain where cookie should be removed (by default, the mmapi configuration is used).
  • path ← String
    Optional path where cookie should be removed (the default value is '/').
  • secure ← Boolean
    Optional secure flag (the default value is false).
Object

Code example

cookies.remove('logged-in');

set( name, value [, properties] ) → {Cookies}

Sets a cookie value.

Parameters

Name Description Type
name Name of the cookie String
value Value of the cookie String
properties Optional properties of the cookie (every property is optional as well):
  • domain ← String
    Optional domain where cookie should be removed (by default, the mmapi configuration is used).
  • path ← String
    Optional path where cookie should be removed (the default value is '/').
  • expires ← Number
    Optional cookie expiration (lifetime) defined in days (by default, is set to 0 – session).
  • secure ← Boolean
    Optional secure flag (the default value is false).
Object

Code example

var experiences = JSON.stringify( site.getPageExperiences() );
cookies.set('mm-generated-variants', experiences, {
expires: 3
});

Events

Use the Events module to delegate shared logic to an independent script, so you can have several campaign-specific handlers of visitors' activities. You can also communicate between different scripts using events.

Reference table

Method Arguments Description Return type
domReady callback Executes a callback function when DOM is ready. Boolean
off name, handler Removes event listener from a custom event. Events
on name, handler Assigns event listener to a custom event. Events
trigger name [, data] [, callback] Executes all the handlers assigned to a custom event. Events

Examples

Methods

domReady( [callback] ) → {Boolean}

Executes a callback function when DOM is ready. Returns true if DOM is ready, false if page is still loading.

Parameters

Name Description Type
callback Optional custom function to be called when DOM is ready Function

Code example

function init() {
...
}

events.domReady(init);

off( name, handler ) → {Events}

Removes event listener from a custom event.

Parameters

Name Description Type
name Custom event name that was previously established String
handler Pointer to the function that was previously assigned as a handler Function

Code example

function confirmationTracking() {
...
}
...
events
.off('purchaseComplete', confirmationTracking);

on( name, handler ) → {Events}

Assigns event listener to a custom event.

Parameters

Name Description Type
name Custom event name to bind handlers to. You can also use namespaces to bind handlers to a group of events: namespace1.* will include all names within namespace1 (namespace1.name1, namespace1.name2, etc.) String
handler Event handler. Accepts optional argument with custom value passed by events.trigger() method. Function

Code example

events
.on('purchaseComplete', function(data) {
...
});

trigger( name [, data, callback] ) → {Events}

Executes all the handlers assigned to a custom event.

Parameters

Name Description Type
name Custom event name String
data Optional data object passed to event handlers Object
callback Optional function that is called after all event handlers are executed. If no handlers have been set, callback is not called. Function

Code example

// Script #1
events.on('purchaseComplete', function(data) {
actions.set('SalesAmount', data.total);
});

// Script #2
events.trigger('purchaseComplete', {
'items': 12,
'total': 379
'currency': 'GBP'
}, function() {
actions.send();
});

Examples

You can create custom events and assign handlers to internal Campaign Design API events (such as events.domReady) using one of the two scopes of the Events module:

  • events - at site and campaign level
  • campaign.events - at campaign level only

To use custom event management, first bind the event handlers using events.on before you fire the event using events.trigger.

Basic example - shared action tracking

To aggregate shared logic at site level and create an event called "ConfirmationAction" that will trigger all child confirmation actions for a particular campaign, an example of the code that you can use in a site script is shown:

// trigger event when DOM is ready
events.domReady(function() {
var productsAmount,
salesAmount;

productsAmount= jQuery('.product').length;
salesAmount = jQuery('#price').text();

events.trigger('ConfirmationAction',
[productsAmount, salesAmount],
function() {
actions.send();
});
});

In a campaign script, you would use the following sample code:

// should be executed earlier than event is triggered
events.on('ConfirmationAction', function(productsAmount, salesAmount) {
actions.set('ProductsSold', productsAmount);
});

Campaign script from another campaign:

// should be executed earlier than event is triggered
events.on('ConfirmationAction', function(productsAmount, salesAmount) {
actions.set('Sale', salesAmount);
});

Basic example - campaign rendering

You can use the following sample code in a campaign script to apply campaign conditionally each time an event occurs, for example, specific AJAX content arrives on the page:

jQuery.ajaxSuccess(function() {
campaign.events.trigger('buttonArrival');
});

And the sample code for the variant would be:

<script type="text/javascript">
function replaceButtuns() {
// do something with the arrived AJAX content
}

campaign.events.on('buttonArrival', replaceButtuns);
</script>

Deferred

Use the Deferred module in campaign and site scripts to manage the results for asynchronous tasks.

Reference table

Method Description Return type
Deferred A constructor function that returns a chainable object which lets you assign callbacks to its state change, and manually change the state in order to trigger those callbacks. Deferred
promise Returns a chainable Promise object which assigns callbacks to the linked Deferred object and observes when the task finishes. Promise
always Adds handlers that are called when the Deferred object is either resolved or rejected. Deferred or Promise
done Adds handlers that are called when the Deferred object is resolved. Deferred or Promise
fail Adds handlers that are called when the Deferred object is rejected. Deferred or Promise
notify Calls the progressCallbacks on a Deferred object with the given args. Deferred
notifyWith Calls the progressCallbacks on a Deferred object with the given context and args. Deferred
progress Adds handlers that are called when the Deferred object generates progress notifications. Deferred or Promise
reject Rejects a Deferred object and calls any failCallbacks with the given args. Deferred
rejectWith Rejects a Deferred object and calls any failCallbacks with the given context and args. Deferred
resolve Resolves a Deferred object and calls any doneCallbacks with the given args. Deferred
resolveWith Resolves a Deferred object and calls any doneCallbacks with the given context and args. Deferred
state Determines the current state of a Deferred object. String
then Adds handlers that are called when the Deferred object is resolved, rejected, or still in progress. Deferred or Promise

Function Description Return type
when Provides a way to execute callback functions based on one or more Deferred objects or functions that represent asynchronous events. Promise

Examples

Methods

Deferred() → {Deferred}

A constructor function that returns a chainable object which lets you assign callbacks to its state change, and manually change the state in order to trigger those callbacks.

Parameters

None

Code example

var deferred = Deferred();

promise() → {Promise}

Returns a chainable Promise object which assigns callbacks to the linked Deferred object and observes when the task finishes.

Parameters

None

Code example

var deferred = Deferred();
var promise = deferred.promise();

always( alwaysCallback [, alwaysCallbacks] ) → {Deferred|Promise}

Adds handlers that are called when the Deferred object is either resolved or rejected.

Parameters

Name Description Type
alwaysCallback A function or array of functions that is called when the Deferred object is resolved or rejected. Function or array
alwaysCallbacks (Optional) Additional functions or arrays of functions that are called when the Deferred object is resolved or rejected. Function or array

Code example

renderer
.waitForElement( "#footer" )
.always(function() {
renderer.showAll();
});

done( doneCallback [, doneCallbacks] ) → {Deferred|Promise}

Adds handlers that are called when the Deferred object is resolved.

Parameters

Name Description Type
doneCallback A function or array of functions that is called when the Deferred object is resolved. Function or array
doneCallbacks (Optional) Additional functions or arrays of functions that are called when the Deferred object is resolved. Function or array

Code example

renderer
.waitForElement( "#footer" )
.done(function() {
renderer.runVariantJs();
})
.always(function() {
renderer.showAll();
});

fail( failCallback [, failCallbacks] ) → {Deferred|Promise}

Adds handlers that are called when the Deferred object is rejected.

Parameters

Name Description Type
failCallback A function or array of functions that is called when the Deferred object is resolved. Function or array
failCallbacks (Optional) Additional functions or arrays of functions that are called when the Deferred object is resolved. Function or array

Code example

renderer
.waitForElement( "#footer" )
...
.fail(function() {
renderer.showAll();
});

notify( [data] ) → {Deferred}

Calls the progressCallbacks on a Deferred object with the given args.

Parameters

Name Description Type
data (Optional) Arguments that are passed to the progressCallbacks. Object

Code example

var requests = Deferred();
requests.progress(function() {
// do something
});

jQuery.ajaxSuccess(function(event, xhr, settings) {
requests.notify(xhr.responseText);
});

notifyWith( context [, data] ) → {Deferred}

Calls the progressCallbacks on a Deferred object with the given context and args.

Parameters

Name Description Type
context The context that is passed to the progressCallbacks as the "this" object. Object
data (Optional) An array of arguments that is passed to the progressCallbacks. Array

Code example

jQuery.ajaxSuccess(function(event, xhr, settings) {
requests.notifyWith(xhr);
});

progress( progressCallbacks ) → {Deferred|Promise}

Adds handlers that are called when the Deferred object generates progress notifications.

Parameters

Name Description Type
progressCallbacks The context that is passed to the progressCallbacks as the "this" object. Function or array

Code example

var requests = Deferred();
requests.progress(function() {
// do something
});

jQuery.ajaxSuccess(function(event, xhr, settings) {
requests.notify(xhr.responseText);
});

reject( [args] ) → {Deferred}

Rejects a Deferred object and calls any failCallbacks with the given args.

Parameters

Name Description Type
args (Optional) Arguments that are passed to the failCallbacks. *

Code example

var requests = Deferred();
requests.fail(function() {
// do something
});

jQuery.ajaxError(function(event, xhr, settings) {
requests.reject(xhr.responseText);
});

rejectWith( context [, args] ) → {Deferred}

Rejects a Deferred object and calls any failCallbacks with the given context and args.

Parameters

Name Description Type
context The context that is passed to the failCallbacks as the "this" object. Object
args (Optional) An array of arguments that is passed to the failCallbacks. Array

Code example

jQuery.ajaxError(function(event, xhr, settings) {
requests.rejectWith(xhr);
});

resolve( [args] ) → {Deferred}

Resolves a Deferred object and calls any doneCallbacks with the given args.

Parameters

Name Description Type
args (Optional) Arguments that are passed to the doneCallbacks. *

Code example

var requests = Deferred();
...
jQuery.ajaxSuccess(function() {
requests.resolve();
});

resolveWith( context [, args] ) → {Deferred}

Resolves a Deferred object and calls any doneCallbacks with the given context and args.

Parameters

Name Description Type
context The context that is passed to the doneCallbacks as the "this" object. Object
args (Optional) An array of arguments that is passed to the doneCallbacks. Array

Code example

var requests = Deferred();
...
jQuery.ajaxSuccess(function(event, xhr, settings) {
requests.resolveWith(xhr);
});

state() → {String}

Determines the current state of a Deferred object.

Code example

var requests = Deferred(); // requests.state() is "pending"
requests.resolve(); // requests.state() is "resolved"
requests.reject(); // requests.state() is "rejected"

then( doneCallbacks [, failCallbacks] [, progressCallbacks] ) → {Deferred|Promise}

Adds handlers that are called when the Deferred object is resolved, rejected, or still in progress.

Parameters

Name Description Type
doneCallbacks A function or array of functions that is called when the Deferred object is resolved. Function or array
failCallbacks A function or array of functions that is called when the Deferred object is rejected. Function or array
progressCallbacks A function or array of functions that is called when the Deferred object notifies progress. Function or array

Code example

renderer
.waitForElement('#footer')
.then(function() {
renderer
.runVariantJs()
.showAll();
}, function() {
renderer.showAll();
});

Functions

when( Deferred [, Deferreds ] ) → {Promise}
when( condition [, stopCondition ] ) → {Promise}

Provides a way to execute callback functions based on one or more Deferred objects or functions that represent asynchronous event(s). Returns a master-Promise object which lets you assign callbacks to its state change.

Parameters

Deferreds: As soon as all Deferred objects are resolved, done callbacks for the master-Promise are executed. As soon as at least one Deferred object is rejected, fail callbacks assigned to the master-Promise are called.

Name Description Type
Deferred Deferred object to be used as Deferred reference for the resulting master-Promise. Deferred
Deferreds (Optional) Additional reference Deferred objects for master-Promise. Deferred

Functions: If the 'condition' function that is iteratively executed every 50ms returns true, done callbacks for the master-Promise are executed. As soon as 'stopCondition' returns true, fail callbacks are called.

Name Description Type
condition A function that triggers done callbacks (resolves virtual Deferred object) when a non-false value is returned. The value is checked every 50ms. Function
stopCondition (Optional) Additional function that stops continuous checks when a non-false value is returned. Function

Code example

var d1 = Deferred(),
d2 = Deferred();

when(d1, d2)
.done(function() {
// both Deferreds are resolved
})
.fail(function() {
// at least one Deferred is rejected
});

Examples

Basic example - customize your workflow using Deferred objects to manage asynchronous tasks

You can customize your workflow by creating Deferred objects to manage asynchronous tasks:

var d1 = Deferred();
d1.done(function() {
console.log('success');
});
d1.fail(function() {
console.log('failure');
});
d1.always(function() {
console.log('always');
});
d1.resolve(); // outputs "success" and "always"

You can use the when() function to get a similar result by creating a Promise:

var d1 = Deferred();
when(d1).then(function() {
console.log('success');
}, function() {
console.log('failure');
}).always(function() {
console.log('always');
});

d1.resolve(); // outputs "success" and "always"

Or you can create a Promise using the .promise() method:

var d1 = Deferred(),
p1 = d1.promise();
p1.then(function() {
console.log('success');
}, function() {
console.log('failure');
}).always(function() {
console.log('always');
});

d1.resolve(); // outputs "success" and "always"

Advanced example - customize renderer.when()

There may be cases when you need to customize renderer.when(). For example, to render content right after AJAX content arrives at a page:

var checker = Deferred();

renderer
// hide target node
.hide('...')
// pass checker Deferred object
.when(checker)
// set done and fail callbacks
.then(function() {
renderer
.runVariantJs()
.showAll();
}, function() {
renderer
.showAll();
});
}

jQuery.ajaxSuccess(function() {
// call checker's done callbacks
checker.resolve();
});

jQuery.ajaxError(function() {
// call checker's fail callbacks
checker.reject();
})

Recommendations

Use the Recommendations module in campaign and site scripts to retrieve recommended products with help of MaxRecommend campaigns. Recommendations are driven by a mathematical model.

Reference table

Method Description Return type
getProducts Returns all the recommended products that arrived with MaxRecommend campaigns to the current page. Object
requestPage An alias for visitor.requestPage(). Sends an additional request to Maxymiser's Content Generator to pass the parameters captured on the page and retrieve test data. Promise
setCategoryFilter Sets filtration by category name for the upcoming MaxRecommend campaigns. This setting is being passed to Content Generator, so that filtration itself is performed on the server side. Recommendations
setProductFilter Sets filtration by category id for the upcoming MaxRecommend campaigns. This setting is being passed to Content Generator, so that filtration itself is performed on the server side. Recommendations

Examples

Methods

getProducts() → {Object}

Returns all the recommended products that arrived with MaxRecommend campaigns to the current page.

Returned object nesting

{
'Campaign1Name': [
{
'id': '...',
'name': '...',
'price': ...,
...
},
{
'id': '...',
'name': '...',
'price': ...,
...
},
...
],
'Campaign2Name': {
...
},
}

Code example

recommendations.getProducts();

requestPage( virtualUrl ) → {Promise}

An alias for visitor.requestPage(). Sends an additional request to Maxymiser's Content Generator to pass the parameters captured on the page and retrieve test data.

Parameters

Name Description Type
virtualUrl URL value to be passed to the Content Generator. To prevent looping, you cannot pass the same URL as the URL of the original page. Please note that in case an empty string is passed, the original page URL is used for page determination. String

Code example

var product = location.href.match( /product-(\d+)/i );
// setting recommendation rating
actions.set( 'Recipe page', 1, product[1] );
recommendations
.setProductFilter( 2, '2543', true )
.requestPage( 'Recommendations URL' )
.done( function(){
var products = recommendations.getProducts();
// ... process and apply recommendations to the page
} );

setCategoryFilter( categoryId, categoryName, isInclusive ) → {Recommendations}

Sets filtration by category name explicitly by setting a setting for the upcoming Content Generator requests. Filtration itself is performed on the server side.

Parameters

Name Description Type
categoryId Category level in the inventory hierarchy. Takes values from 1 to 3 meaning filtering by category of the 1st, 2nd or 3rd level. Number
categoryName

Name of the category the recommended products will be filtered by. E.g., "Books", "Cloths", "Electornics", etc.

String
isInclusive Flag that determines whether to include or exclude products of the specified category. Boolean

Code example

recommendations
.setCategoryFilter( 2, 'Socks', true )
.requestPage( 'Recommendations URL' );

setProductFilter( categoryId, productId, isInclusive ) → {Recommendations}

Sets filtration by category id for the upcoming MaxRecommend campaigns. This setting is being passed to Content Generator, so that filtration itself is performed on the server side.

Parameters

Name Description Type
categoryId Category level in the inventory hierarchy. Takes values from 1 to 3 meaning filtering by category of the 1st, 2nd or 3rd level. Number
productId

Id of the product the recommended products will be filtered by

String
isInclusive Flag that determines whether to include or exclude products of the specified product category. Boolean

Code example

recommendations
.setProductFilter( 3, '2342', true )
.requestPage( 'Recommendations URL' );

Examples

Basic example - apply recommendations to a page

Getting recommendations for 3 MaxRecommend campaigns (where different mathematical models are used):

// tracking product rating
var productId = location.href.match(/product-(\d+)/i);
actions.set('Product view', 1, productId[1]);

recommendations
.requestPage(
'ViewedThisCampaign URL' +
'RatedThisCampaign URL' +
'VisitorAffinityCampaign URL'
)
.done( function() {
events.trigger( 'ProductView', recommendations.getProducts() );
} );

Applying the recommendations from a variant HTML:

<style type="text/css">
.products {
overflow: hidden;
padding-top: 56%;
position: relative;
}
</style>

<a href="/products/{pageurl}">
<div class="products">
<img src="{imageurl}"/>
</div>
<h2>{name}</h2>
</a>

<script type="text/javascript">
var productsHTML = '';
dom.addCss( css );

// basic templater
function template(t,o) {
return t.replace(/{([^{}]*)}/g,
function(a, b) {
var r = o[b];
return typeof r === 'string' || typeof r === 'number' ? r : a;
}
);
};

// when products arrive to the page
events.on( 'ProductView', function( recommendedProducts ) {
// get products for the current campaign
var products = recommendedProducts['ViewedThisCampaign'];
for ( var i = 0; i < products.length; i++ ) {
// add every product to the aggregated HTML string
productsHTML += template( html, products[i] );
}
} );

// apply the HTML to the page
dom.insertHtmlWithin( '.product-description', productsHTML );
</script>

Modules

Use Modules in site and campaign scripts to introduce custom functionality into your campaigns.

Reference table

Method Description Return type
define Defines a custom module Object
require Gets instance of a module Object

Methods

define( name [, properties], constructor ) → {Modules}

Defines a custom module.

Parameters

Name Description Type
name Unique name of the module, should conform JavScript variable naming rules String
properties Optional properties for the module:
  • autoDefine ← Boolean
    Automatic module declaration. If set to true (default value), the module is available by its name. If set to false, you need to retrieve the module instance by calling modules.require().
  • singleton ← Boolean
    Force using one instance for all page scripts. If set to true (default value), all scripts will have access to the same instance. If set to false, each script will get its own instance.
  • extend ← Module
    Name of the parent module to extend from
Object
constructor A function to be used as module constructor Function

Code example

modules.define('myModule', { extend: 'parentModule' }, function() {
this.myProperty = ...;
this.myMethod = function() {
...
}
});

require( name ) → {Module}

Gets the instance of a custom module.

Parameters

Name Description Type
name Name of the module String

Code example

var myModule = modules.require('myModule');
myModule.myMethod();

Examples

Advanced example - tracking IFRAME clicks

Use custom modules to create templates for designing campaigns specifically for your site.

// Script #1
modules.define('iframeActions', {}, function() {
this.clickHandlerIsActive = false;
this.trackClicks = function(node, actionData) {
if (!this.clickHandlerIsActive) {
this.clickHandlerIsActive = true;

window.addEventListener('message', function(event) {
if (data.type && data.type == 'CLICK') {
actions.send.apply(actions, actionData);
}
});
}
}
});

// Script #2
var iframeActions = modules.require('iframeActions');
iframeActions.trackClicks($('#bannerFrame'), ['iframeClick', '1']);

Widgets

Use Widgets in site and campaign scripts to embed widgets in your website pages.

You must have a current license agreement for MaxEngage to use the Widgets module. Contact Maxymiser for more information.

Reference table

Method Description Return type
createCallout Embeds a call out in the test page
createLightbox Embeds a lightbox in the test page
createNotification Embeds a notification in the test page

Methods

createCallout( properties )

Embeds a call out in the test page.

Parameters

Name Description Type
properties Properties of the notification (all properties are optional. The properties that are unique to this widget are marked with an asterisk *):
  • content ← String
    HTML content of the widget that will be embedded in the page.

  • appearance ← Object
    Properties container to describe the look of the widget.
    • name ← String
      Identifies the widget within VCB.
    • backgroundColor ← String
      Background color of the dialog element. A hex value or any other valid format of CSS color. The default value is #FFFFFF.
    • autofit ← Boolean
      Defines if the dialog content is stretched. The default value is true.
    • position* ← Object
      Defines the position of the widget.
      • at ← String
        Relative positioning described by 2 dimensions separated by space: "{side} {alignment}". Choose from the following values: "top|bottom|right|left left|center|right". The default value is "top left".
      • offset ← String
        Relative offset of the widget defined from the corners set using the 'at' value. Consists of 2 values in pixels. For example, "10px 20px" together with the "top left" value of the property above will set the top margin to 10px, and left margin to 20px.
      • pointer ← String|Boolean
        Determines whether a pointer is shown (non-false value is passed) and its position. Set the position in case 'relativeTo' parameter is passed with 'page' or 'viewport' values, in the following format: "bottom|top left|right". The default value is "top left".
      • relativeTo ← String
        Determines the element on the page where the widget is embedded. You can specify a valid CSS selector, "page" (embedded to the <body>) or "viewport" (embedded with fixed position on the screen).
      • viewportDetection ← Boolean
        Defines whether the position of the widget is automatically adjusted to be closer to the device viewport. Ignored if 'relativeTo' is not a CSS selector.
    • height ← String
      Dialog height. Specify a valid CSS dimension value. The value is ignored if 'autofit' is set to true.
    • width ← String
      Dialog width. Specify a valid CSS dimension value. The value is ignored if 'autofit' is set to true.

  • displayEvent ← Object
    Properties container to describe when the widget appears.
    • onPageLoad ← Boolean
      Determines if the widget is shown when the page is loaded. The default value is true.
    • delay ← Number
      The delay before the widget appears (in milliseconds).
    • startAfterIdle ← Boolean
      Determines if the display delay is counted after the last mouse move. The default value is false.
    • initAttachedTo ← String
      Defines the elements that trigger the appearance of the widget when a website visitor clicks, places mouse over or on mouse out. Specify a valid CSS selector.
    • onClick ← Boolean
      Determines if the widget is displayed when the 'initAttachedTo' element is clicked. The default value is false.
    • onMouseOver ← Boolean
      Determines if the widget is displayed when the visitor places their mouse over the 'initAttachedTo' element. The default value is false.
    • onMouseOut ← Boolean
      Determines if the widget is displayed when the visitor takes their mouse off the 'initAttachedTo' element. The default value is false.
    • onViewportMouseOut ← Boolean
      Determines if the widget is displayed when the visitor's mouse is out of the browser. The default value is false.
    • onLosePageFocus ← Boolean
      Determines if the widget is displayed when the browser tab loses focus. The default value is false.
    • onCustomEvent ← String
      Custom event defined by the API developer.

  • closeEvent ← Object
    Properties container to describe when the widget disappears.
    • dismissElements ← String
      Defines the elements that will trigger the appearance of the widget when a website visitor clicks on them. Specify a valid CSS selector.
    • onDismissButton ← Boolean
      Identifies whether the widget reappears after dismissal. The default value is true.
    • onClickOutside ← Boolean
      Identifies whether the widget closes when a visitor presses Esc or clicks a page overlay. The default value is true.

  • showFrequency ← Object
    Properties container to describe how frequently the widget appears.
    • always ← Boolean
      Identifies if the widget should be shown every time displayEvent is triggered. The default value is true.
    • neverAfterDismiss ← Boolean
      Determines that the widget is not shown after dismissal. The default value is true.
    • showsCount ← Number
      The maximum number of times the widget is displayed, after which, the widget is no longer shown.
    • showsInterval ← String
      Dispaly period: "hour", "day", "week", "month", "session", "campaign".
Object

Code example

widgets.createCallout({
content: html,
appearance: {
name: "Callout 1",
backgroundColor: "#ffffff",
position: {
at: "top left",
offset: "30px 50px",
pointer: "top left",
relativeTo: "#confirmationButton",
viewportDetection: true
},
autofit: false,
height: "240px",
width: "440px"
},
displayEvent: {
onPageLoad: true,
delay: 25,
startAfterIdle: false,
initAttachedTo: "#main",
onClick: true,
onMouseOver: true,
onMouseOut: true,
onViewportMouseOut: true,
onLosePageFocus: true,
onCustomEvent: "eventName"
},
closeEvent: {
onDismissButton: true,
onClickOutside: true,
dismissElements: "#hideButton1, .hideClassSelector"
},
showFrequency: {
always: true,
neverAfterDismiss: true,
showsCount: 1,
showsInterval: "day"
}
});

createLightbox( properties )

Embeds a lightbox in the test page.

Parameters

Name Description Type
properties Properties of the widget (all properties are optional. The properties that are unique to this widget are marked with an asterisk *):
  • content ← String
    HTML content of the widget that will be embedded in the page.

  • appearance ← Object
    Properties container to describe the look of the widget.
    • name ← String
      Identifies the widget within VCB.
    • backgroundColor ← String
      Background color of the dialog element. A hex value or any other valid format of CSS color. The default value is "#FFFFFF".
    • fadeEnabled* ← Boolean
      Page overlay that acts as the widget background.
    • fadeColor* ← String
      Page overlay color. A hex value or any other valid format of CSS color. The default value is "#000000".
    • opacity* ← Number
      Page overlay's opacity. Decimal value between 0 and 1. The default value is 0.8.
    • autofit ← Boolean
      Defines if the dialog content is stretched. The default value is true.
    • height ← String
      Dialog height. Valid CSS dimension value. The value is ignored if 'autofit' is set to true.
    • width ← String
      Dialog width. Valid CSS dimension value. The value is ignored if 'autofit' is set to true.

  • displayEvent ← Object
    Properties container to describe when the widget appears.
    • onPageLoad ← Boolean
      Determines if the widget is shown when the page is loaded. The default value is true.
    • delay ← Number
      The delay before the widget appears (in milliseconds).
    • startAfterIdle ← Boolean
      Determines if the display delay is counted after the last mouse move. The default value is false.
    • initAttachedTo ← String
      Defines the elements that trigger the appearance of the widget when a website visitor clicks, places mouse over or on mouse out. Valid CSS selector.
    • onClick ← Boolean
      Determines if the widget is displayed when the 'initAttachedTo' element is clicked. The default value is false.
    • onMouseOver ← Boolean
      Determines if the widget is displayed when the visitor places their mouse over the 'initAttachedTo' element. The default value is false.
    • onMouseOut ← Boolean
      Determines if the widget is displayed when the visitor takes their mouse off the 'initAttachedTo' element. The default value is false.
    • onViewportMouseOut ← Boolean
      Determines if the widget is displayed when the visitor's mouse is out of the browser. The default value is false.
    • onLosePageFocus ← Boolean
      Determines if the widget is displayed when the browser tab loses focus. The default value is false.
    • onCustomEvent ← String
      Custom event defined by the API developer.

  • closeEvent ← Object
    Properties container to describe when the widget disappears.
    • dismissElements ← String
      Defines the elements that will trigger the appearance of the widget when a website visitor clicks on them. Valid CSS selector.
    • onDismissButton ← Boolean
      Identifies whether the widget reappears after dismissal. The default value is true.
    • onClickOutside ← Boolean
      Identifies whether the widget closes when a visitor presses Esc or clicks a page overlay. The default value is true.

  • showFrequency ← Object
    Properties container to describe how frequently the widget appears.
    • always ← Boolean
      Identifies if the widget should be shown every time displayEvent is triggered. The default value is true.
    • neverAfterDismiss ← Boolean
      Determines that the widget is not shown after dismissal. The default value is true.
    • showsCount ← Number
      Limit of display events after which the widget is not shown.
    • showsInterval ← String
      Display period: "hour", "day", "week", "month", "session", "campaign".
Object

Code example

widgets.createLightbox({
content: html,
appearance: {
name: "Lightbox 1",
backgroundColor: "#ffffff",
fadeEnabled: true,
fadeColor: "#000000",
opacity: 0.8,
autofit: false,
height: "500px",
width: "800px"
},
displayEvent: {
onPageLoad: true,
delay: 25,
startAfterIdle: false,
initAttachedTo: "#main",
onClick: true,
onMouseOver: true,
onMouseOut: true,
onViewportMouseOut: true,
onLosePageFocus: true,
onCustomEvent: "eventName"
},
closeEvent: {
onDismissButton: true,
onClickOutside: true,
dismissElements: "#hideButton1, .hideClassSelector"
},
showFrequency: {
always: true,
neverAfterDismiss: true,
showsCount: 1,
showsInterval: "day"
}
});

createNotification( properties )

Embeds a notification in the test page.

Parameters

Name Description Type
properties Properties of the notification (all properties are optional. The properties that are unique to this widget are marked with an asterisk *):
  • content ← String
    HTML content of the widget that will be embedded in the page.

  • appearance ← Object
    Properties container to describe the look of the widget.
    • name ← String
      Identifies the widget within VCB.
    • backgroundColor ← String
      Background color of the dialog element. A hex value or any other valid format of CSS color. The default value is "#FFFFFF".
    • autofit ← Boolean
      Defines if the dialog content is stretched. The default value is false.
    • insertAbove* ← String
      Defines the elements above which the notification will be embedded. Specify a valid CSS selector.
    • insertBelow* ← String
      Defines the elements below which the notification will be embedded. Specify a valid CSS selector.
    • insertWithin* ← String
      Defines the elements to which the notification will be embedded. Specify a valid CSS selector.
    • height ← String
      Dialog height. Specify a valid CSS dimension value. The default value is "240px". The value is ignored if 'autofit' is set to true.
    • width ← String
      Dialog width. Specify a valid CSS dimension value. The default value is "440px". The value is ignored if 'autofit' is set to true.

  • displayEvent ← Object
    Properties container to describe when the widget appears.
    • onPageLoad ← Boolean
      Determines if the widget is shown when the page is loaded. The default value is true.
    • delay ← Number
      The delay before the widget appears (in milliseconds).
    • startAfterIdle ← Boolean
      Determines if the display delay is counted after the last mouse move. The default value is false.
    • initAttachedTo ← String
      Defines the elements that trigger the appearance of the widget when a website visitor clicks, places mouse over or on mouse out. Specify a valid CSS selector.
    • onClick ← Boolean
      Determines if the widget is displayed when the 'initAttachedTo' element is clicked. The default value is false.
    • onMouseOver ← Boolean
      Determines if the widget is displayed when the visitor places their mouse over the 'initAttachedTo' element. The default value is false.
    • onMouseOut ← Boolean
      Determines if the widget is displayed when the visitor takes their mouse off the 'initAttachedTo' element. The default value is false.
    • onViewportMouseOut ← Boolean
      Determines if the widget is displayed when the visitor's mouse is out of the browser. The default value is false.
    • onLosePageFocus ← Boolean
      Determines if the widget is displayed when the browser tab loses focus. The default value is false.
    • onCustomEvent ← String
      Custom event defined by the API developer.

  • closeEvent ← Object
    Properties container to describe when the widget disappears.
    • dismissElements ← String
      Defines the elements that will trigger the appearance of the widget when a website visitor clicks on them. Valid CSS selector.
    • onDismissButton ← Boolean
      Identifies whether the widget reappears after dismissal. The default value is true.
    • onClickOutside ← Boolean
      Identifies whether the widget closes when a visitor presses Esc or clicks a page overlay. The default value is true.

  • showFrequency ← Object
    Properties container to describe how frequently the widget appears.
    • always ← Boolean
      Identifies if the widget should be shown every time displayEvent is triggered. The default value is true.
    • neverAfterDismiss ← Boolean
      Determines that the widget is not shown after dismissal. The default value is true.
    • showsCount ← Number
      Limit of display events after which the widget is not shown.
    • showsInterval ← String
      Display period: "hour", "day", "week", "month", "session", "campaign".
Object

Code example

widgets.createNotification({
content: html,
appearance: {
name: "Notification 1",
backgroundColor: "#ffffff",
insertWithin: "#someElement",
autofit: false,
height: "auto",
width: "100%"
},
displayEvent: {
onPageLoad: true,
delay: 25,
startAfterIdle: false,
initAttachedTo: "#main",
onClick: true,
onMouseOver: true,
onMouseOut: true,
onViewportMouseOut: true,
onLosePageFocus: true,
onCustomEvent: "eventName"
},
closeEvent: {
onDismissButton: true,
onClickOutside: true,
dismissElements: "#hideButton1, .hideClassSelector"
},
showFrequency: {
always: true,
neverAfterDismiss: true,
showsCount: 1,
showsInterval: "day"
}
});

Go to the Top