Javascript Snippet Library
This is a collection of Javascript snippets that may be used in full or for inspiration in order to log events and customize campaigns. You will find scripts that cover these areas:
- Campaign Targeting
- Campaign Design
- Datalayer and Cart Events
- Enrich Visitor Data
- Handle form data
- And some Other scripts
Note: These scripts are not one-fits-all. They need to be configured based on your specific webpage.
Campaign Targeting
Target Campaigns based on element CSS
getComputedStyle(document.querySelector(".login-button")).display=="none"
Target Campaigns based on specific time
function afterTime(hour,minutes) {
var d = new Date();
if (d.getHours() >= hour && d.getMinutes() >= minutes) {
return true;
}
}
Target Campaigns based on DOM elements
document.querySelector(".login-button").innerText=="login";
document.querySelector(".total").innerText.slice(0, -3) < 300;
Target Campaigns based on value in cart
/* helpfunction to put in client script */
function cartValueOver(value) {
var cartTotal = parseInt(document.querySelector(".cart-total").innerText;
if (value > cartTotal) {
return true;
}
}
/* Script to use in campaign Javascript condition */
cartValueOver(199);
Target Campaigns if a specific product is in cart
/* helpfunction to put in client script*/
function productInCart(productName) {
var cartProducts = document.querySelectorAll(".cart-items");
for (let index = 0; index < cartProducts.length; index++) {
const element = cartProducts[index];
if (element.innerText == productName) {
return true;
}
}
}
/* Script to use in campaign Javascript condition */
productInCart("Productname");
Target Campaigns based on URL
/* Domain, ex. google.com */
window.location.host == "domain.com"
/* Page, ex. /products/t-shirt */
window.location.pathname == "path"
window.location.pathname.includes("path");
/* Query, ex. a certain utm-tag */
window.location.search == "utm_campaign=wintercampaign"
window.location.search.includes("utm_campaign=wintercampaign");
Open a campaign on click
window.addEventListener('load', function () {
var tbClickButtons = document.querySelectorAll(".click-button");
if (tbClickButtons) {
for (var index = 0; index < tbClickButtons.length; index++) {
const tbClickButton = tbClickButtons[index];
tbClickButton.addEventListener("click", function () {
triggerbee.widgets.api.trigger(1234);
})
}
}
});
Campaign Design
Anchor widget to another element (Login nudge)
document.addEventListener("onTriggerbeeWidgetOpened", function (event) {
if(event.detail.id==39832){
/* Step 1: Retrieve references to the target element and the div element */
const targetElement = document.getElementById('user-dialog');
const divElement = document.querySelector('triggerbee-widget').shadowRoot.querySelector("[data-position-id='61023']");
/* Step 2: Calculate the position of the target element */
const targetRect = targetElement.getBoundingClientRect();
const targetTop = targetRect.top;
const targetLeft = targetRect.left;
/* Step 3: Set the position and dimensions of the div element */
divElement.style.position = 'absolute';
divElement.style.top = targetTop+60+"px";
divElement.style.left = targetLeft-180+"px";
}
});
Rotate the teaser
/* ROTATE TEASER */
document.addEventListener("onTriggerbeeWidgetOpened", function (event) {
if (event.detail.campaignName.includes("XX")) { /* Replace XX with the name of your campaign */
var widgetRotate = document.querySelector('triggerbee-widget[data-id="'+event.detail.id+'"]').shadowRoot.querySelector(".state.state-teaser.cursor-pointer").style;
/* The adjustments for the appearance */
widgetRotate.transform="rotate(-90deg)";
widgetRotate.msTransform="rotate(-90deg)";
widgetRotate.minHeigt="30px";
widgetRotate.right="50px";
widgetRotate.width="150px";
widgetRotate.marginBottom="250px";
}
});
Change deadline to count 3 minutes from session start
/* Change counter to 3 minutes for campaign with ID 58089 */
document.addEventListener("onTriggerbeeWidgetOpened", function (event) {
if (event.detail.id == 58089) {
/* Get the deadline component element */
const tbWidget = document.querySelector('triggerbee-widget[data-id="58089"]').shadowRoot;
const deadlineElement = tbWidget.querySelector('.deadline-component');
/* Set the deadline time to 30 minutes from now */
const deadlineTime = new Date();
deadlineTime.setMinutes(deadlineTime.getMinutes() + 3);
deadlineElement.querySelector('.minutes .deadline-section-slide1').textContent = 0;
deadlineElement.querySelector('.seconds .deadline-section-slide1').textContent = 0;
function updateCountdown() {
/* Calculate the time remaining until the deadline */
const now = new Date();
const timeRemaining = deadlineTime - now;
/* Calculate the minutes, and seconds remaining */
const minutes = Math.floor((timeRemaining % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((timeRemaining % (1000 * 60)) / 1000);
/* Update the HTML elements with the new values */
deadlineElement.querySelector('.minutes .deadline-section-slide2').style.display = "none";
deadlineElement.querySelector('.seconds .deadline-section-slide2').style.display = "none";
deadlineElement.querySelector('.minutes .deadline-section-value2').style.display = "none";
deadlineElement.querySelector('.seconds .deadline-section-value2').style.display = "none";
deadlineElement.querySelector('.minutes .deadline-section-slide1').textContent = String(minutes).padStart(2, '0');
deadlineElement.querySelector('.seconds .deadline-section-slide1').textContent = String(seconds).padStart(2, '0');
}
/* Update the countdown every second */
setInterval(updateCountdown, 1000);
}
});
});
Change color of copy check mark
document.addEventListener("onTriggerbeeWidgetOpened", function () {
var tbWidget=document.querySelector('triggerbee-widget');
var tbCheckMark = tbWidget.shadowRoot.querySelector(".checkmark-circle");
if(tbCheckMark){
tbCheckMark.style.backgroundColor="#000";
tbWidget.shadowRoot.querySelector(".checkmark").style.borderColor="#FFF";
}
});
Rolling animation (Marquee)
/* Marquee CSS */
document.addEventListener("onTriggerbeeWidgetOpened", function (event) {
if (event.detail.campaignName.includes("Marquee")) {
var sheetMarquee = document.createElement('style');
sheetMarquee.innerHTML = `
.marquee {
white-space: nowrap;
overflow: visible;
display: inline-block;
animation: marquee 20s linear infinite;
}
.marquee p {
letter-spacing: 1px;
font-weight: 500;
margin-top: 4px;
margin-left: 25px;
margin-right: 25px;
display: inline-block;
}
@keyframes marquee {
0% {
transform: translate3d(0, 0, 0);
}
100% {
transform: translate3d(-50%, 0, 0);
}
}
@media only screen and (max-width: 700px){
.marquee {
animation: marquee 7s linear infinite;
}
}
`;
var tbWidget = document.querySelector('triggerbee-widget[data-id="' + event.detail.id + '"]');
tbWidget.shadowRoot.appendChild(sheetMarquee);
<br> tbWidget.shadowRoot.querySelector(".text-content").classList.add("marquee");
tbWidget.shadowRoot.querySelector(".container").style.overflow="hidden";
var bfElement = tbWidget.shadowRoot.querySelector(".text-content p");
for (let index = 0; index < 7; index++) {
tbWidget.shadowRoot.querySelector(".text-content").appendChild(bfElement.cloneNode(true));
}
}
});
Change CSS of element in specific campaign
document.addEventListener("onTriggerbeeWidgetOpened", function (event) {
if (event.detail.id==1234) {
document.querySelector('triggerbee-widget[data-id="'+event.detail.id+'"]').shadowRoot.querySelector('.state').style.minHeight="32px";
}
});
Fade out Effect
function fadeOutEffect() {
var fadeTarget = document.querySelector("triggerbee-widget").shadowRoot.querySelector(".modal");
var fadeEffect = setInterval(function () {
if (!fadeTarget.style.opacity) {
fadeTarget.style.opacity = 1;
}
if (fadeTarget.style.opacity > 0) {
fadeTarget.style.opacity -= 0.1;
} else {
clearInterval(fadeEffect);
}
}, 40);
}
Align content to left on embedded campaigns
document.addEventListener('onTriggerbeeWidgetOpened', function () {
if(event.detail.id==widgetID)){ /* optional if you want to limit the code to specific URLs. Could also limit by specific widget with */
var states = document.querySelector('triggerbee-widget').shadowRoot.querySelectorAll('.position-embedded');
for (var index = 0; index < states.length; index++) {
const state = states[index];
state.style.float = 'left';
}
}
});
Set dynamic height on Embedded Campaigns
document.addEventListener("onTriggerbeeWidgetOpened", function (event) {
if (event.detail.id == 14727) {
var elements = document.getElementsByClassName('feature - banner');
if (elements !== undefined && !!elements[0]) {
var requiredElement = elements[0];
elements[0].querySelector('span').innerHTML = "";
var widget = document.querySelector('triggerbee-widget');
var states = widget.shadowRoot.querySelectorAll('.state');
for (var index = 0;
index < states.length; index++) {
const state = states[index];
state.style.height = requiredElement.offsetHeight + "px";
}
}
}
});
Remove click-event from powered by logo
document.addEventListener("onTriggerbeeWidgetOpened", function (event) {
if(event.detail.id==2555){
var poweredLink=document.querySelector('triggerbee-widget').shadowRoot.querySelector('#powered-by a');
poweredLink.addEventListener("click", function(event){
event.preventDefault()
});
poweredLink.style.cursor="default";
}
});
Change close button to white in Cookie Policy
var policyStyle = document.createElement('style');
policyStyle.innerHTML = `
.step-summary-close img{
content:url("//assets.triggerbee.com/triggerbee/conversionbanner-wizard/close-buttons/btn-close-round-transparent-white.png");
width: 20px !important;
height: 20px !important;
}
`;
document.head.appendChild(policyStyle);
Replacing {email} in text with identified email
document.addEventListener("onTriggerbeeWidgetOpened", function (event) {
var person = mtr.getPerson();
var triggerbeeWidget = document.querySelector('triggerbee-widget').shadowRoot;
triggerbeeWidget.innerHTML = triggerbeeWidget.innerHTML.replace('{email}', person.identifier);
});
Replacing {delivery} in text with calculated value left to delivery
document.addEventListener("onTriggerbeeWidgetOpened", function (event) {
if (event.detail.id==27376) {
var checkoutTotal = parseInt(document.querySelector("div[data-test-id='CheckoutSelectors.OrderTotal']").innerText.slice(0,-4));
if (checkoutTotal < 4000) {
var leftToDelivery = 4000 - checkoutTotal;
var triggerbeeWidget = document.querySelector('triggerbee-widget[data-id="'+event.detail.id+'"]').shadowRoot;
triggerbeeWidget.innerHTML = triggerbeeWidget.innerHTML.replace('{delivery}', leftToDelivery);
}
}
});
Add Gradient Color to Text block
document.addEventListener("onTriggerbeeWidgetOpened", function (event) {
var widget = document.querySelector('triggerbee-widget');
if(event.detail.id==1874){
var textParagraphs = widget.shadowRoot.querySelectorAll('.text-content');
const textP = textParagraphs[0]; /* finding the first .text-content paragraph */
textP.style.background="-webkit-linear-gradient(90deg, #FF0000, #00ff00 80%)";
textP.style["-webkit-text-fill-color"] = "transparent";
textP.style["-webkit-background-clip"] = "text";
}
});
Remove PoweredBy
document.addEventListener("onTriggerbeeWidgetOpened", function (event) {
if(event.detail.id==2555){
document.querySelector('triggerbee-widget[data-id="2555"]').shadowRoot.querySelector('#powered-by').remove();
}
});
Change CSS in Mobile devices - 1 slide
document.addEventListener("onTriggerbeeWidgetOpened", function (event) {
var widget = document.querySelector('triggerbee-widget');
if(widget && window.innerWidth < 767){
widget.shadowRoot.querySelector('.state').style.marginRight="20px";
}
});
Change CSS in Mobile devices - several slides
document.addEventListener("onTriggerbeeWidgetOpened", function (event) {
var widget = document.querySelector('triggerbee-widget');
if(event.detail.id==1234 && window.innerWidth < 767){
var states = widget.shadowRoot.querySelectorAll('.state');
for (var index = 0; index < states.length; index++) {
const state = states[index];
state.style.marginRight="20px";
}
}
});
Change Font Weight CSS on all text elements
document.addEventListener("onTriggerbeeWidgetOpened", function (event) {
var widget = document.querySelector('triggerbee-widget');
var states = widget.shadowRoot.querySelectorAll('.state p');
for (var index = 0; index < states.length; index++) {
const state = states[index];
state.style.fontWeight = 100;
}
});
Prefill input field with Email for identified users
document.addEventListener("onTriggerbeeWidgetOpened", function() {
var tbWidget = document.querySelector("triggerbee-widget");
var tbUserEmail = mtr.getPerson().identifier;
if (tbWidget && tbUserEmail) {
var tbEmailInput = tbWidget.shadowRoot.querySelector("input[type=email]");
tbEmailInput.value=tbUserEmail;
}
});
Datalayer and Cart Events
Rule Cart Abandoned
if(window.location.pathname=="/checkout/"){
var productsInCart=google_tag_manager['GTM-ABC1234'].dataLayer.get('ecommerce.checkout.products');
var tbCartProducts = [];
for (let i = 0; i < productsInCart.length; i++) {
const item = productsInCart[i];
const product = {
namn: item.name,
pris: item.price,
kategori: item.category,
antal: item.quantity,
bild: item.image
}
tbCartProducts.push(product);
}
if (tbCartProducts.length > 0) {
mtr_custom.session = { cartproducts: JSON.stringify(tbCartProducts)};
mtr.goal("Initiated purchase");
}
}
Voyado Cart Abandoned
if(window.location.pathname=="/checkout/"){
var date = new Date();
var timeZone ='+0' + Math.abs(date.getTimezoneOffset()) / 60 + ':00';
var time = date.toLocaleString('sv-SE') + ' ' + timeZone;
var productsInCart=google_tag_manager['GTM-ABC1234'].dataLayer.get('ecommerce.checkout.products');
var tbCartProducts = [];
for (let i = 0; i < productsInCart.length; i++) {
const item = productsInCart[i];
const product = {
sku: item.sku,
quantity: item.quantity,
}
tbCartProducts.push(product);
}
if (tbCartProducts.length > 0) {
mtr_custom.session = { products: JSON.stringify(tbCartProducts), time: time};
mtr.goal("Initiated purchase");
}
}
Filter specific value from the data layer and store in an array
/* Create new array with only product names */
function checkProducts(prod){
let checkoutProducts = dataLayer.filter(function (e) {
return e.event == "checkout";
});
return checkoutProducts[0].ecommerce.checkout.products.map(({ name }) => name).includes(prod);
};
/* Call function with product name in Campaigns. Returns true if product exists */
checkProducts("Product name");
Log cart Contents (products, productID and cartSum) to client
if (window.location.pathname=="/checkout") {
var productsInCart=dataLayer[3].ecommerce.items;
var cartSum=dataLayer[3].ecommerce.value;
var tbCartProducts = [];
var tbCartProductIDs = [];
for (let i = 0; i < productsInCart.length; i++) {
const item = productsInCart[i];
const product = {
name: item.item_name,
price: item.price,
quantity: item.quantity,
category: item.item_category
}
tbCartProducts.push(product);
tbCartProductIDs.push(item.item_id);
}
mtr_custom.session = { cartProducts: JSON.stringify(tbCartProducts)};
mtr.goal("Initiated purchase");
}
Get specific value from Datalayer
google_tag_manager['GTM-ABCDEF'].dataLayer.get('ecommerce.checkout.products');
Check products in Checkout
Gets all products in the checkout. Loop through and collect in an array. Then log to Triggerbee.
if (window.location.pathname=="/checkout") {
var tbProductsinCart = document.querySelectorAll(".product-name");
var tbProducts = [];
for (var index = 0; index < tbProductsinCart.length; index++) {
const tbProduct = tbProductsinCart[index].innerText;
tbProducts.push(tbProduct.toLowerCase());
}
window.triggerbee=window.triggerbee || {};
window.triggerbee.products=tbProducts;
}
/* Combine with this snippet for campaigntargeting: */
triggerbee.products.includes("productX");
Enrich Visitor Data
Add tags based on host
document.addEventListener("afterTriggerbeeReady", function () {
if (window.location.host == "yourdomain.com") {
triggerbee.session.addTags('Yourdomain');
}
});
Set tag based on email domain for identified visitors
var emailDomains = ["mail.com"];
window.addEventListener('load', function () {
var emailDomain = mtr.getPerson().identifier.split("@")[1];
if (emailDomains.includes(emailDomain)) {
triggerbee.identity.addTags("Tag");
}
});
Log goal on a specific state in Onsite Campaigns
document.addEventListener("onTriggerbeeWidgetStateSwitched", function (event) {
if (event.detail.stateId==1234) {
mtr.goal("State goal");
}
});
Log goal based on querystring
window.addEventListener('load', function () {
if (window.location.search.includes("utm_source=facebook")) {
mtr.goal("Came from Facebook Campaign");
}
});
Log "seen campaign" on every campaign
Use this snippet to set a goal on the visitor every time they see a campaign. Useful for creating funnels in which visitors have seen a campaign, but not converted.
document.addEventListener("onTriggerbeeWidgetOpened", function (event) {
mtr.goal("Seen campaign: "+event.detail.campaignName)
});
Handle form data
Log Identity from form submit in modal
This snippet listens to a button that opens a login modal. In that modal, there's a login form in which we get the email address and log to Triggerbee for identification.
if (document.querySelector("#login-btn")) {
tbLoginButton.addEventListener("click", function(){
setTimeout(function(){
var tbLoginForm = document.querySelector("form");
tbLoginForm.addEventListener("submit", function(){
var tbUserEmail = document.querySelector("#user-email");
var tbContact = window.mtr_custom || {};
tbContact.session = tbContact.session || {};
tbContact.session.email = tbUserEmail.value;
window.mtr_custom = tbContact;
mtr.goal("Logged in");
});
}, 1000);
});
}
Do something with submitted form values
document.addEventListener("onAfterTriggerbeeFormSubmitted", function (e) {
if(e.detail.id == 4817){
var widget = document.querySelector('triggerbee-widget').shadowRoot;
var widgetForm = widget.querySelector("form");
if (widget) {
var filledEmail = widgetForm.querySelector('input[type=email]').value;
var filledName = widgetForm.querySelector("input[name='name']").value;
console.log("Epostadress: " + filledEmail);
console.log("filledName: " + filledName);
triggerbee.widgets.api.close(event.detail.id);
}
}
});
Other
Delete memory of what state was latest shown
var tbStateCookie = JSON.parse(mtr.get_cookie("triggerbee_widgets_state_147707"))
tbStateCookie.widgets = tbStateCookie.widgets.filter(state => state.id != 15773);
mtr.set_cookie("triggerbee_widgets_state_147707",JSON.stringify(tbStateCookie))
Remove specific value from Array
/* remove all objects with id 1234 from array */
Array.filter(object => object.id != 1234);<br>
Randomize number 1-100 for AB-testing in variable
var testNumber=Math.floor((Math.random() * 100) + 1);
Randomize number 1-100 for AB-testing in cookie
if (mtr.get_cookie("tb_abTestGroup")=="") {
var abTestNumber = Math.floor((Math.random() * 100) + 1);
document.cookie = "tb_abTestGroup" + "=" + abTestNumber + ";path=/;domain=" + "." + location.hostname.replace(/^www\./i, "") + ";";
}
/* target group A */
mtr.get_cookie("tb_abTestGroup")>50
/* target group B */
mtr.get_cookie("tb_abTestGroup")<51
General Triggerbee Namespace Function
var triggerbeeClient = triggerbeeClient || (function () {
function init(){
myFunction();
}
function myFunction(){
/* Code to run */
}
window.addEventListener('load', function() {
init();
});
return {
}
})();
Advanced Cookies
Buying Intent Cookie
/* START BUYING INTENT */
/* START DONT TOUCH */
var slidingCookie = function (settings) {
var isTrue = function () {
var minutes = settings.minimumInterval;
var count = settings.minOccurances;
if (!minutes)
minutes = 0; /* Avoid "Invalid date" in list */
var list = filterList(minutes);
/* Return true if list is more than count */
return list.length >= count;
}
var filterList = function (minutes) {
var list = getList();
var now = getNow();
var isDirty = false;
/* Filter expired items from list */
for (var i = list.length - 1; i >= 0; i--) {
var validUntil = new Date(list[i]);
validUntil.setMinutes(validUntil.getMinutes() + minutes);
var isWithin = validUntil > now;
if (!isWithin) {
list.splice(i, 1);
isDirty = true;
}
}
if (isDirty)
setCookie(getCookieName(), JSON.stringify(list));
return list;
}
var incrementList = function () {
var list = getList();
/* Add current pageview to list */
list.push(getNow().toString());
/* Limit to 50 items (dates) in list */
if (list.length >= 50)
list.shift();
/* Save list */
setCookie(getCookieName(), JSON.stringify(list));
return list;
}
var getList = function () {
/* Get list */
var list = getCookie(getCookieName());
list = !list ? [] : list = JSON.parse(list);
return list;
}
var getCookieName = function () { return "mtr_slidingCookie-" + settings.id }
var getNow = function () {
var now = new Date();
return now;
}
var getCookie = function (name) {
var ca = document.cookie.split(';');
for (var i = 0, l = ca.length; i < l; i++) {
if (ca[i].match(new RegExp("\\b" + name + "="))) {
return decodeURIComponent(ca[i].split(name + '=')[1]);
}
}
return '';
}
var setCookie = function (name, value) {
var ex = new Date;
ex.setTime(ex.getTime() + (3600 * 1000 * 24) * 21);
document.cookie = name + "=" + value + ";expires=" + ex.toGMTString() + ";path=/;";
}
/* * Constructor * */
/* Check and increment */
if (settings.callback()) {
var list = getList();
/* we only store PageView IF the time since last */
/* PageView is more than minimumInterval */
var lastView = (list.length > 0) ? new Date(list[list.length - 1]) : Date.now();
var interval = Date.now() - lastView;
var intervalSeconds = parseInt(interval / 1000);
if (intervalSeconds > settings.minimumInterval || list.length == 0) {
incrementList();
}
}
/* Run final actions */
var boolCounterTrue = isTrue();
if (settings.isDebug) {
console.log('Action taken more than ' + settings.minOccurances + ' times in ' + settings.minimumInterval + ' seconds?: ' + isTrue());
console.log(getList());
}
if (boolCounterTrue) {
/* Log goal */
if (settings.goalName && mtr.getPerson().goals.indexOf(settings.goalName) === -1) {
if (settings.isDebug) {
console.log('Logging goal ' + settings.goalName);
}
mtr.goal(settings.goalName);
}
/* Save boolean on window-namespace so other scripts can use it */
eval("window." + settings.id + " = true");
/* Open campaign */
if (settings.isDebug) {
console.log('Showing widget ' + settings.widgetId);
console.log("window." + settings.id + " = true");
console.log("window.buyingIntentSofa ?: => " + window.buyingIntentSofa);
}
/* triggerbee.widgets.api.trigger(settings.campaignId); */
}
return {};
};
function afterTriggerbeeReady(callback) {
var maxAttempts = 10;
var counter = 0;
checkIsInitialized();
function checkIsInitialized() {
if (typeof (window.mtr) !== "undefined" && typeof (window.triggerbee.widgets) !== "undefined") {
callback();
} else {
if (counter < maxAttempts) {
setTimeout(function () {
counter++;
checkIsInitialized();
}, 250);
}
}
}
}
/* Init sliding cookie */
afterTriggerbeeReady(function () {
initSlidingCookie();
document.addEventListener('onTriggerbeeSpaPageChanged', function (e) {
initSlidingCookie();
});
})
/* END DONT TOUCH */
/* CUSTOMER SPECIFIC */
/* check if current page should count as a match */
function isPageViewMateus() {
if (window.location.pathname.includes("mateus")) {
return true;
}
}
function initSlidingCookie() {
var settingsMateus = {
id: 'buyingIntentMateus', /* unique id to group your cookie, ex. category */
minimumInterval: (3600 * 12), /* number of seconds before a pageview is expired - 12 is number of hours */
minOccurances: 2, /* number of visits before triggering the intent */
callback: isPageViewMateus, /* function to run to check if we are on the correct category */
goalName: 'Buying Intent on Mateus', /* goal to complete when expression is true */
/*campaignId: 21379, Campaign to open when expression is true
isDebug: false Log debugmessages */
};
new slidingCookie(settingsMateus);
}
/* END BUYING INTENT */
Set cookie based on URL for Campaign targeting
/* Set cookie on every visitor from a certain query. Expires on session */
if (window.location.search.includes("vipBlackFridaySms")) {
document.cookie = "tb_user" + "=" + "vip" + ";path=/;domain=" + "." + location.hostname.replace(/^www\./i, "") + ";";
}
/* Do something if cookie exists */
if(document.cookie.includes("tb_user=vip")){
console.log("you have cookie!");
}
Store data in cookie
/* this particular variable is from GTM, but snippet can be used outside GTM too */
var productsInCart = {{Checkout - items}};
/* Get Cookie */
var productCookie=Cookies.get("products_in_cart");
/* Check if cookie exists */
if (!productCookie) {
/* if not - create new cookie */
Cookies.set("products_in_cart",JSON.stringify(productsInCart),10);
}else{
var cookieArray = JSON.parse(productCookie);
cookieArray.push(productsInCart[0]);
Cookies.set("products_in_cart",JSON.stringify(cookieArray),10);
}
/* Get new cookie and log to Triggerbee */
var newProductCookie = Cookies.get("products_in_cart");
window.mtr_custom.session = { products: newProductCookie}
Set cookie based on URL for Campaign targeting - expire after X seconds
/* Create cookie function */
var setCookie = function (name, value, expires) {
var ex = new Date;
ex.setTime(ex.getTime() + (expires || 10 * 365 * 86400) * 1000);
document.cookie = name + "=" + value + ";expires=" + ex.toGMTString() + ";path=/;domain=" + "." + location.hostname.replace(/^www\./i, "") + ";";
}
/* Set cookie on every visitor from a certain query. Set expire date to a specific date. */
window.addEventListener("load", function () {
if (window.location.search.includes("coupon_code")) {
setCookie("tb_user","vip",7200); /* will expire after 7200 seconds = 2 hours */
}
});
/* Use this snippet for campaign targeting */
!document.cookie.includes("tb_user=vip");
Set cookie based on URL for Campaign targeting - expire on a specific date
/* Create cookie function */
var setCookie = function (name, value, expires) {
document.cookie = name + "=" + value + ";expires=" + expires.toGMTString() + ";path=/;domain=" + "." + location.hostname.replace(/^www\./i, "") + ";";
}
/* Set cookie on every visitor from a certain query. Set expire date to a specific date. */
window.addEventListener("load", function () {
var tb_date = new Date(2020, 10, 25); /* Creates date 2020-11-24 00:00 */
if (window.location.search.includes("coupon_code")) {
setCookie("tb_user","vip",tb_date);
}
});
/* Use this snippet for campaign targeting */
!document.cookie.includes("tb_user=vip");
Redeal scripts
/* Tracking script */
(function(i,s,o,g,r,a,m){i['RedealObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window, document, 'script', window.location.protocol + '/static.redeal.se/widget/js/redeal.js', 'redeal');
/* Open Cornerwidget */
redeal("cornerwidget");
<br>/* Identification of ambassadors to Triggerbee */
window.addEventListener("message", function(e) {
var tbRedeal=e.data.redeal;
if(tbRedeal?.email){
var tbContact = window.mtr_custom || {};
tbContact.session = tbContact.session || {};
tbContact.session.email = tbRedeal.email;
window.mtr_custom = tbContact;
mtr.goal("Redeal Conversion");
}
});
/* Open Redeal on Triggerbee Button */
redeal('banner');
mtr.widget('clickthrough', 15083);