Reference summary
This section provides reference documentation for version 1.6 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 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 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 |
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. | Variant scripts |
css | Stores the CSS data of the variant above the script node where the variable is called. | Variant scripts |
Examples
- Skip rendering of the default experience (basic example)
- Apply dynamic variant (basic example)
- Persistent data storage (basic example)
- Process variant content from a campaign script (advanced)
- Share variables across campaign scripts (advanced)
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 |
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
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
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
getExperience() → {Object}
Gets information about the variants generated for the current campaign.
Returned object nesting
'Element1Name': 'GeneratedVariantName',
'Element2Name': 'GeneratedVariantName',
...
}
Code example
$('#cta').css('color', colorVariantName);
getName() → {String}
Gets the campaign name.
Code example
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
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
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
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
campaign.scope.basketValue = $("#total").text();
actions.set("Purchase", parseInt(campaign.scope.basketValue, 10));
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:
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:
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:
.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:
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:
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.
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.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
Properties
scope → {Object}
Editable property to be used for data sharing between different scripts on a page.
Code example
site.scope.pageId = document.title.match(/\d+/)[0];
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:
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:
/* do something here*/
}
The following example shows the code in a campaign script:
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
.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
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
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:
|
Object |
Code example
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
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
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
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
.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
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
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
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
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
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
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:
|
Object |
Code example
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:
|
Object |
Code example
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:
|
Object |
Code example
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
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
.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
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
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
Examples
Apply variant CSS
To apply variant CSS, use the following sample code in a Content Variant:
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. | Variant scripts |
css | String | Stores the CSS data of the variant above the script node where the variable is called. | Variant scripts |
Examples
- Render campaign content (basic example)
- Identify if a campaign applies to a page (basic example)
- Get campaign data (basic example)
- Handle content on AJAX pages (basic example)
- Configure time before campaign content is displayed (advanced example)
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
.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
.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
...
.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
.hide('.banner', 'bannerArea')
...
.show('bannerArea')
showAll() → {Renderer}
Shows all the previously hidden content for the current campaign.
Code example
.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
.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
...
.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
...
.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
<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
body {
color: #030;
}
</style>
<script type="text/javascript">
dom.addCss(css);
</script>
Examples
Basic example - render campaign content
Source code for original page:
<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:
// 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 |
|
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:
- Iteratively check whether page-specific content has appeared on the page.
- As soon as a decision can be made, send a request for a virtual page or finish the process.
- Apply the campaign to the page if required.
The steps are summarised in the following sample code:
// 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();
});
});
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'.
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.
// 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:
renderer.hide('td.add-to-cart');
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:
// this content will be shown automatically in 2 seconds
// unless you show it manually before timeout expires
renderer.hide('td.add-to-cart');
...
// 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
- Track sales amount (basic example)
- Track several actions (basic example)
- Track a postponed action (basic example)
- Advanced click-through action tracking
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
.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
.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:
|
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
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
.set('Click', '1')
.set('Purchase', '1299', 'USD')
.send();
Examples
Basic example - track sales amount
Tracking sales amount:
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:
.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:
// 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:
- Cancel the default behavior of the link or form that is triggered.
- Pass information about the action to the Content Generator.
- Replicate the default behavior of the link or form.
Here is an example:
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 |
getData | Retrieves the custom variable value from persistent storage. | * |
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
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
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
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
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
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
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. | String |
Code example
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
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
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
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
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
Examples
Basic example - persistent custom attribute
Use the following code on the registration page:
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
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
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):
|
Object |
Code example
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):
|
Object |
Code example
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
...
}
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
...
}
...
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
.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 | Function |
Code example
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:
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:
events.on('ConfirmationAction', function(productsAmount, salesAmount) {
actions.set('ProductsSold', productsAmount);
});
Campaign script from another campaign:
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:
campaign.events.trigger('buttonArrival');
});
And the sample code for the variant would be:
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
- Customize your workflow using deferred objects to manage asynchronous tasks (basic example)
- Customize renderer.when() (advanced example)
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
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 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
.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
.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
.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
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
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
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
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
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
...
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
...
jQuery.ajaxSuccess(function(event, xhr, settings) {
requests.resolveWith(xhr);
});
state() → {String}
Determines the current state of a Deferred object.
Code example
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
.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
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:
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:
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:
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:
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 | 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 | String |
properties | Optional properties for the module:
|
Object |
constructor | A function to be used as module constructor | Function |
Code example
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
myModule.myMethod();
Examples
Advanced example - tracking IFRAME clicks
Use custom modules to create templates for designing campaigns specifically for your site.
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.
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 *):
|
Object |
Code example
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 *):
|
Object |
Code example
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 *):
|
Object |
Code example
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"
}
});