Campaign Design API > Reference

Reference summary

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

Below is a summary of the available methods, functions, properties and variables to enable you to design campaigns using 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
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
removeCss
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 (Content Generator). postpone
send
set
Visitor Site and campaign scripts Use to retrieve and send visitor data, such as gender or age, to the Content Generator. clearData
getAttr
getData
removeAttr
requestPage
setAttr
setData
storeAttr
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
Modules Site and campaign scripts Use to introduce custom functionality into your campaigns define
require

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. Variant scripts
css Stores the CSS data of the variant above the script node where the variable is called. Variant scripts

Examples

Campaign

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

Reference table

Method Return type Description
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 Object Gets the content of all variants generated for the given visitor on the current page in JSON format.
getExperience Object Gets information about the variants generated for the current campaign.
getName String Gets the campaign name.
getStyles Array<String> Retrieves CSS text from campaign's HTML sources.
isDefault Boolean Identifies whether only default variants were generated on the page for the given campaign.
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 Type Description
name String Name of the variable.

Code example

campaign.clearData('purchase-total');

getData( [name] ) → {*}

Retrieves the value of the custom variable from the campaign's persistent storage.

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

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.

Code example

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

setData( name, value [, expires] )

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.

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.
// 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 Return type Description
getPageExperiences Object Gets information about the variants generated for all campaigns on the current page.

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

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 to apply CSS content.

Reference table

Method Return type Description
addCss Dom Applies CSS rules to a page.
removeCss Dom Removes the CSS that was previously added.

Examples

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 applied CSS rule(s) which can be deactivated 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 }');

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

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

Variable Type Description Availability
html String Stores the HTML data of the variant above the script node where the variable is called. Variant scripts
css String Stores the CSS data of the variant above the script node where the variable is called. 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.

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.

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 Return type Description
postpone Actions Captures action data to be sent to the Content Generator in the next (single) request.
send Promise Sends all captured action data to the Content Generator.
set Actions Captures action data to be sent to the Content Generator when actions.send() is called.

Examples

Methods

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

Captures action data to be sent to the Content Generator in the next (single) request.

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

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 Return type Description
clearData Removes custom variable data from persistent storage
getAttr String Retrieves the value of the custom attribute that was saved using visitor.storeAttr().
getData * Retrieves the custom variable value from persistent storage.
removeAttr Removes the value of a custom attribute from persistent storage.
requestPage Promise Sends additional request to Maxymiser Content Generator.
setAttr Captures custom attribute data to temporary storage to be sent to the Content Generator in the next (single) page request.
setData Saves the custom variable value in persistent storage, so it can be retrieved on other site pages using visitor.getData().
storeAttr Saves custom attribute data to permanent storage to be sent to the Content Generator in subsequent requests.

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}

Retrieves the value of the custom attribute that was saved using visitor.storeAttr().

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.

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

removeAttr( name )

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

requestPage( virtualUrl ) → {Promise}

Sends additional request to Maxymiser Content Generator in order to pass captured on page parameters and retrieve required for testing data.

Parameters

Name Description Type
virtualUrl 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. String

Code example

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

setAttr( name, value )

Captures custom attribute data to temporary storage to be sent to the Content Generator in the next (single) page request.

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().

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

storeAttr( name, value )

Saves custom attribute data to permanent storage to be sent to the Content Generator in subsequent requests on site.

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

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

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 Function

Code example

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

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 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 Return type Description
when Promise Provides a way to execute callback functions based on one or more Deferred objects or functions that represent asynchronous events.

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 of 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 resulted master-Promise Deferred
Deferreds (Optional) Additional reference Deferred objects for master-Promise Deferred

Functions: In case 'condition' function that is being iteratively executed every 50ms returns true, done callbacks of 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 non-falsy value is returned. The value is being checked every 50ms. Function
stopCondition (Optional) Additional function that stops continues checks in case it returns a non-falsy value. 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();
})

Modules

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

Reference table

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

Methods

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

Defines a custom module.

Parameters

Name Description Type
name Unique name of a module String
properties Optional module properties (every property is optional as well):
  • autoDefine → Boolean
    Automatic module declaration. If true (default value) module will be available by its name. If false you need to retrieve 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 false – every 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']);

Go to the Top