JS Pixel Methods

Estimated reading time: 8 min
In this article

JS Pixel Methods are available methods you can use within your Javascript custom code or external scripts on the website.

Campaign object

Campaign Object can be accessed at: _vtsdk.Campaign

Display Campaign

As developer you can force display a campaign by running the following code:

_vtsdk.Campaign.displayCampaign(campaignId, display)

Parameters

campaignId: ID of campaign that you want to display. This must be active.

display: boolean value, use true to display the campaign

Return value

object: JS object with the DOM element and template ID.

{ 
	"dom": DOM Element,
	"tpl": chosen content ID
}

Remarks

Content selection is done within this method, based on campaign configuration.

Extract user attributes from a string

Used on input elements class names so system can send the attributes accordingly.

_vtsdk.Campaign.extractAttributeFromClass(string)

Parameters

string: text you want attributes to be extracted from

Return value

string: attribute name without prefix

Remarks

For example

InputOutput
vta-name other_classname
vta-birthdatebirthdate

Embed Campaign

Embeds a campaign into the webpage, checking first display limits for that campaign.

_vtsdk.Campaign.embedCampaign(cId, tId)

Parameters

cId: ID of the campaign

tId: ID of the content

Return value

DOM element: if successfully displayed the campaign

undefined: otherwise

Remarks

This method params determine method behaviour:

  1. Passing cId and tId is used to preview campaigns that are not published (for example draft campaigns)
  2. Passing only cId expects the campaign to be published.

Track display of a campaign

Generates events for displaying a campaign.

Runs Code added for display event (if any).

Manages auto Close configuration.

_vtsdk.Campaign.runDisplayCampaign(cId)

Parameters

cId: ID of campaign

Return value

Remarks

This method is called automatically from within all triggering methods.

Interpolate Data into string

Interpolates a JS data object variable within a string with VT placeholders (**|variable.name|**).

_vtsdk.Campaign.interpolateVars(string, params, skip)

Parameters

string: string where the replacements will be done

params: JS object with the values that are replaced. Can be nested.

skip: true/false. If set to true it will skip replacing placeholders when no value found in .

Return value

string with placeholders replaced from params object.

Remarks

Only **|placeholder|** are accepted.

Build Attribute Object

Builds a JS object with all attributes and values found for a list of elements

_vtsdk.Campaign.buildAttrObject(elem, includeSubmit)

Parameters

elem: List of DOM elements

includeSubmit: true/false if submit input will be included

Return value

JS object with all the attributes found in the class name from all elements.

Remarks

Create a site event

Generates a valid JS object to be pushed to the event queue

_vtsdk.Campaign.createSiteEvent(type, cId, tId, params)

Parameters

type: event type

cId: campaign ID

tId: content ID

params: JS object with params that will be merged into the event object

Return value

JS object with a valid representation of a VT event

Remarks

  • params object is not required. If you want to have generic fields added, pass it as {“generic”: {“fields”:…}}

Attach click events

Adds default events (click, close, submit, toggle) on a DOM element, based on class names found within

_vtsdk.Campaign.attachClickEvents(cId, tId, cDom)

Parameters

cId: campaign ID

tId: content ID

cDom: DOM element 

Return value

Remarks

Make sure positioning & style of children elements within the parent do not overlap, as that might generate unexpected behaviour/events.

Check Display Rules

Validates a list of rules if they are all or at least one valid.

_vtsdk.Campaign.checkDisplayRules(displayRules, firstValid)

Parameters

displayRules: list of display rules, in our internal specific format

firstValid: true/false.

Return value

  • true or false. 

Remarks

  • If firstValid is set to false, all rules must return true.
  • If firstValid is set to true, returns true if at least one rule is true, otherwise returns false.
  • Example Rule: {key: “session.pathname”, val: “/blog/”, op: “regex”}

Embed Content Campaigns

Embeds page content campaigns by looping through all campaigns and all groups of conditions.

_vtsdk.Campaign.embedContentCampaigns()

Parameters

Return value

JS object with campaigns that were embeded and first valid group ID.

Remarks

  • Method called on each page view to embed content campaigns;

EVENTS API

Push event on Next Page

Instead of pushing event right away, it gets saved and will be pushed when the user goes to the next page. The format of the event is the same with any event format.

vtsdk.eventApi.pushNext({"addtocart":{"itemId":idInShop}})

Parameters

event: object

Return Value

None

Remarks: This is useful when the event you want to track happens just before a page redirection. Examples are: form submissions, clicks.

Send multiple Events

If you are sending multiple events from the same page it’s a better idea to send them at once instead of making multiple requests.

vtsdk.eventApi.sendEventArray([{"addtocart":{"itemId":idInShop}}, {"confirmation":{"items":[], "generic":{"orderId": ""}}}])

Parameters

event_list: array of events

Return Value:

None

HELPERS

Return User Context Value

Return context value from Onsite Shared Data or event.

_vtsdk.Helpers.getContextValue(key, trigger, event)

Parameters

key: key of the element. Can be a a key to a nested value using .

trigger: e for event, p for page

event: event object

Return value

Various values

Remarks

Most use cases you will need are from User context so you can skip trigger and event parameters.

Return value of object key

Returns value from a nested object.

_vtsdk.Helpers.getDeepValue(value, path)

Parameters

key: key of the element. Can be a a key to a nested value using .

path: path of the value. Use . to go for deep values. Eg: context.session.browser

Return value

Returns undefined if not found

Returns the found value otherwise.

Remarks

Clean Email Address

Cleans an email address string by stripping some characters and making it lowercase. 

_vtsdk.Helpers.cleanEmail(string)

Parameters

string: email address to clean

Return value

cleaned email address. String.

Remarks

Extract Tag From HTML

Returns content of specific html tag as string.

_vtsdk.Helpers.extractTagFromHtml(string, tag)

Parameters

string: html string where to look for

tag: tag type (script, div …)

Return value

Content of first found tab or empty string if not found

Remarks

Add Class to element

Adds a class to provided DOM element

_vtsdk.Helpers.addClass(element, className)

Parameters

element: DOM element

className: name of the class to be added

Return value

Remarks

If class already exists it won’t be added twice.

Remove Class from element

Remove class from provided DOM element

_vtsdk.Helpers.removeClass(element, className)

Parameters

element: DOM element

className: name of the class to be removed

Return value

Remarks

Serialize Form Data

Returns a list of values from input fields within a Form element.

_vtsdk.Helpers.serializeForm(form)

Parameters

form: Form DOM element

Return value

list of variables and values as strings: [“var1=value”, “var2=3″…]

Remarks

Returns only input fields that are not disabled and not of type file, reset, submit, button.

Generate Random Number

Returns an integer random number between min and max

_vtsdk.Helpers.generateRandomBetween(min, max)

Parameters

min: minimum value

max: maximum value

Return value

Integer number between the two values

Remarks

If wrong values are passed (float values, max < min) method will probably return invalid data.

Compare Values

Compare 2 values  using specified operator

_vtsdk.Helpers.valuesComparer(val1, val2, operator)

Parameters

val1: value to compare

val2: value to compare against

operator: one of the comparison query operators gt, gte, lt, lte, eq, ne, regex, eval

Return value

true / false

Remarks

There are some special cases that are worth mentioning.

  • “true” / “false” strings are converted to boolean
  • val1 undefined will be equal to val2 false
  • val2 is 0 and val1 is undefined will return true for eq, lte, gte operators
  • eval is a special operator used to evaluate a JS expression. It’s only valid when it returns a boolean value.

Add Event Listener to element

Adds an event listener to specific element.

_vtsdk.Helpers.addEventListener(element, eventType, eventHandler, useCapture)

Parameters

element: DOM element

eventType: type of event, string. Click, mouseover…

eventHandler: function passed to the event listener

useCapture: moment when it’s captured at the beginning (true), and at the end (false). 

Return value

Remarks


This method is just a wrapper over addEventListener / attachEvent default JS methods.

URL Call Async

Makes an async call to specified URL (adds a script element to the DOM).

_vtsdk.Helpers.getAsync(url, cached)

Parameters

url: url to call

cached: defaults to true, it adds a random param at the end of URL 

Return value

Script type DOM element that was embeded.

Remarks

  • mostly used to call internal backend API’s

Validate Email Address

Validates an email address if it respects a specific format.

_vtsdk.Helpers.emailIsValid(email)

Parameters

email: email address

Return value

true/false

Remarks

Log Info

Logs a message to the console, based on specific debug level.

_vtsdk.Helpers.log(msg, type)

Parameters

msg: string or object

type: default to info. Can be one of (info, warning, error, none). Default to info

Return value

  • (message is logged in Developers Console using console.log)

Remarks

  • type is compared to defaults debug level. If it’s below that level, message is not displayed.
  • debug level can be overwritten for client by passing value through a GET param vt_debug

Send to Google Analytics

Sends an event to Google Analytics, if account configuration is set.

_vtsdk.Helpers.sendToAnalytics(data)

Parameters

data: event object

Return value

Remarks

  • It uses Google Analytics GA method, building the values based on event data and account GA Category configuration.
  • type of event is the same for GA
  • label is built according to event data: itemID, category, checkout step, campaign/content ID, query, orderId

Update VT Cookie Data

Updates an existing VT cookie. 

_vtsdk.Helpers.updateCookie(key, update)

Parameters

key: local key name (without prefix)

update: JS object to be merged with existing data. Existing keys are overwritten.

Return value

  • no return values because it might be an async process.

Remarks

Set VT Cookie Data

Saves a local VT cookie. 

_vtsdk.Helpers.setCookie(key, value, expiration)

Parameters

key: local key name (without prefix)

value: any value type to be stored

expiration: value in milliseconds when key should expire. Can be ignored

Return value

  • no return values because it might be an async process.

Remarks

Get VT Cookie

Returns a local VT cookie. 

_vtsdk.Helpers.getCookie(key)

Parameters

key: local key name (without prefix)

Return value

  • value of the cookie, exactly as is was set

Remarks

Remove VT Cookie

Deletes a local VT cookie. 

_vtsdk.Helpers.removeCookie(key)

Parameters

key: local key name (without prefix)

Return value

Remarks

Read Cookie

Reads a standard browser cookie

_vtsdk.Helpers.readCookie(readCookie)

Parameters

key: cookie name

Return value

Value of the cookie. Unescaped string.

Remarks

Write Cookie

Writes a standard browser cookie

_vtsdk.Helpers.writeCookie(name, value, expiration)

Parameters

key: cookie name

value: any value type to be stored

expiration: value in milliseconds when key should expire.

Return value

Remarks

Extract Main URL

Extracts full URL from a string, without query params.

_vtsdk.Helpers.extractMainURL(url)

Parameters

url: url string

Return value

string. URL without any query string, if those exists.

Remarks

Extract Domain

Extracts domain/hostname from a URL string. 

_vtsdk.Helpers.extractDomain(url)

Parameters

url: url string

Return value

string. Hostname or domain from that URL

Remarks

  • Subdomains will be extracted as well.

Create Query String from Object

Creates a valid query string from a key:value JS object

_vtsdk.Helpers.makeQueryString(object)

Parameters

object: JS object

Return value

string. Valid query string, with encoded URI components

Remarks

Eg: name=John&age=18&email=…

Return URL GET Params

Adds a query string to an URL taking into consideration existing query string

_vtsdk.Helpers.getURLParams(url)

Parameters

url: URL string

Return value

JS object as key:value from URL query string params. Empty object if not params available.

Remarks

Add Query String to URL

Adds a query string to an URL taking into consideration existing query string

_vtsdk.Helpers.addQueryString(url, object)

Parameters

url: URL string

object: JS object

Return value

string. URL with new params

Remarks

It uses makeQueryString and getURLParams to build new query string and add it to the URL

Return Browser Name

Returns browser name.

_vtsdk.Helpers.browserInfo('name')

Parameters

Return value

string. lowercase

Remarks

Return Browser Language

Returns browser language based on navigator language.

_vtsdk.Helpers.browserLang()

Parameters

Return value

string.

Remarks

Return Browser Version

Returns browser version

_vtsdk.Helpers.browserInfo('version')

Parameters

Return value

string.

Remarks

Return Operating System Name

Returns running operating system

_vtsdk.Helpers.osName()

Parameters

Return value

string.

Remarks

Check if Input has Value

Validates that input field has value. For Checkbox/Radio it checks for at least one to be checked/selected to return it’s value.

_vtsdk.Helpers.inputHasValue(elem, cDom)

Parameters

elem: DOM element to be checked

cDOM: form or some parent DOM element to check other checkbox/radio inputs

Return value

string. Value of the input field or false otherwise. 

Remarks

  • for checkbox and multi-select it returns one value only. Empty string is considered value.

Check if target is DOM element

Validates a target to be DOM element

_vtsdk.Helpers.isDomNode(elem)

Parameters

elem: DOM element to be checked

Return value

boolean. true or false

Remarks

Hide DOM element

Hides a DOM element or a list of elements using display:none

_vtsdk.Helpers.showDom(elem)

Parameters

elem: DOM element or list of elements to be hidden

Return value

Remarks

Show DOM element

Displays a DOM element or a list of elements using display:block

_vtsdk.Helpers.showDom(elem)

Parameters

elem: DOM element or list of elements to be displayed

Return value

Remarks

Create DOM element

Creates and embeds a DOM element into page

_vtsdk.Helpers.embedTag(tag, content, where, attributes)

Parameters

tag: type of DOM element to be created. 

content: HTML content for the newly created element

where: other HTML tag to append the new element at the end. (body/head/html)

attributes: JS object with key:values to be added as attributes for new new element

Return value

DOM element

Remarks

Read TagManager Data Layer

Reads window.dataLayer pushed variables into a JS object.

_vtsdk.Helpers.readDataLayer()

Parameters

Return value

JS object with values available from DataLayer

Remarks

  • This method returns variables pushed into window.dataLayer only.
  • Ignores events pushed into dataLayer

Return Device Type

Returns device type based on resolution, userAgent and some other values.

_vtsdk.Helpers.deviceType()

Parameters

elem: DOM element or list of elements to be displayed

Return value

string, one of the values: desktop/tablet/mobile

Remarks

  • Because of many browser types, this method might return a wrong result. 

Lowercase string

Returns a lowercase string or empty string if value is undefined.

_vtsdk.Helpers.strtolower(value)

Parameters

value: string to be lowercased

Return value

string

Remarks

  • If value is not string, is returned as is.

Return External Referrer

Returns external referrer (different domain) based on document.referrer.

_vtsdk.Helpers.getExternalReferrer()

Parameters

Return value

string: full URL of external referrer

null: if no external referrer

Remarks

Validate Checkbox and Subscribe Email

For subscribing users if they select a checkbox input, automatically generates a login event if email address from email input is valid.

_vtsdk.Helpers.checkAndSubscribe(inputCSS, conditionCSS, pushNext, params)

Parameters

inputCSS: CSS selector for email input 

conditionCSS: CSS selector for checkbox input field

pushNext: true/false whether to use pushNext method instead of making the request immediately

params: extra params JS object to be merged into login event

Return value

true if the method succeeded in validating conditions and generating login event

false otherwise. 

Remarks

  • You might consider using this method as event listener for checkbox input
Was this article helpful?
Dislike 0
Views: 72