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: 

Note: These scripts are not one-fits-all. They are example scripts and 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

/* helpfunction to put in client script */
function afterTime(hour,minutes) {
    var d = new Date(); 
    if (d.getHours() >= hour && d.getMinutes() >= minutes) {
        return true;
    }
}

/* Script to use in campaign Javascript condition */
afterTime(20,00) // to start campaign after 20:00

Target Campaigns based on DOM elements

document.querySelector(".login-button").innerText=="login"; // target campaign if there is a button on the page with the class .login-button and text "login"

document.querySelector(".total").innerText.slice(0, -3) < 300; // target campaign if the element with class total has a value of more than 300

Target Campaigns based on value in the 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 different parts of the 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.includes("utm_campaign=wintercampaign");

Open a campaign on a click 

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

Target campaign if current URL matches a big set of URLs or part of URL

/* helpfunction to put in clientscript */

/* array of all variants to target */
var mySKUs = ['39500-02','45750-02','39524-04','39530-03','39533-01','39549-02','39502-02','39550-06'];

/* function to extract matching part of URL */
function extractpartofUrl(url) {
    const regex = /variantId=([^&]+)/;
    const match = url.match(regex);
    return match ? match[1] : null;
}

/* function to chef if current URL matches any of the variables in the array */ 
function isCorrectSKU() {
    const variantId = extractpartofUrl(window.location.href);
    return mySKUs.includes(variantId);
}

/* Javascript to target campaign on */ 
isCorrectSKU(); // will return true if current URL is a match

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 the 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";
        }
});

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

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

Change CSS in Mobile devices - 1 step

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 steps

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

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

Make it snow on your website - Snowflakes CSS hack

document.addEventListener('onTriggerbeeWidgetOpened', function (event) {
    if (event.detail.id==89769) {
    var tbWidget=document.querySelector('triggerbee-widget[data-id="'+event.detail.id+'"]').shadowRoot;
    snowDiv = document.createElement('div');
    snowDiv.classList.add("snow");
    tbWidget.appendChild(snowDiv);

    var snowStyle = document.createElement('style');
    snowStyle.innerHTML = `
    
.snow{
    position:fixed;
    pointer-events:none;
    top:0;
    left:0;
    right:0;
    bottom:0;
    height:100vh;
    background: none;
    background-image: url('https://widget-resources.triggerbee.com/accountfiles/147707/images/s3.6b2b8b4c.webp'), 
    url('https://widget-resources.triggerbee.com/accountfiles/147707/images/s2.611f40d4.webp'), 
    url('https://widget-resources.triggerbee.com/accountfiles/147707/images/s1.7ae5863f.webp');
    z-index:100;
    -webkit-animation: snow 10s linear infinite;
    -moz-animation: snow 10s linear infinite;
    -ms-animation: snow 10s linear infinite;
    animation: snow 10s linear infinite;
  }
  @keyframes snow {
    0% {background-position: 0px 0px, 0px 0px, 0px 0px;}
    50% {background-position: 250px 500px, 200px 200px, -150px 150px;}
    100% {background-position: 500px 1000px, 400px 400px, -300px 300px;}
  }
  @-moz-keyframes snow {
    0% {background-position: 0px 0px, 0px 0px, 0px 0px;}
    50% {background-position: 250px 500px, 200px 200px, -150px 150px;}
    100% {background-position: 500px 1000px, 400px 400px, 300px 300px;}
  }
  @-webkit-keyframes snow {
    0% {background-position: 0px 0px, 0px 0px, 0px 0px;}
    50% {background-position: 250px 500px, 200px 200px, -150px 150px;}
    100% {background-position: 500px 1000px, 400px 400px, -300px 300px;}
  }
  @-ms-keyframes snow {
    0% {background-position: 0px 0px, 0px 0px, 0px 0px;}
    50% {background-position: 250px 500px, 200px 200px, -150px 150px;}
    100% {background-position: 500px 1000px, 400px 400px, -300px 300px;}
  }
    `;
    tbWidget.appendChild(snowStyle);
    }
});

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 a 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("onBeforeTriggerbeeFormSubmitted", 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

Prevent closing of embedded campaign on canvas click

document.addEventListener('onTriggerbeeWidgetOpened', function (event) {
    if (event.detail.id==94830) {
    var tbWidget=document.querySelector('triggerbee-widget[data-id="'+event.detail.id+'"]').shadowRoot;
        tbWidget.querySelector(".state-regular").onclick = function () {
            window.open('https://www.google.com', '_blank')
            mtr.widget('clickthrough', 94830);
        }
    }
});

Delete memory of what state was latest shown

var tbStateCookie = mtr.get_cookie("triggerbee_widgets_state_121212"); //SITE ID
if (tbStateCookie.includes("12345")) { // WIDGET ID
var parsedCookie = JSON.parse(tbStateCookie);
parsedCookie.widgets = parsedCookie.widgets.filter(state => state.id != 12345);
mtr.set_cookie("triggerbee_widgets_state_121212",JSON.stringify(parsedCookie))
}

Remove specific value from Array

/* remove all objects with id 1234 from array */
Array.filter(object => object.id != 1234);

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 {

    }
})();

Custom Input Field Validation for Campaign Editor

This code sets up customized validation for input fields within a triggerbee form, tailored for use within the "custom code" element of a campaign editor.

const emailValidationMessage = 'Should be your work email';
const phoneValidationMessage = 'Should start with plus followed by 9-11 digits';
const nameValidationMessage = 'First- and lastname, at least three characters each';
const consentValidationMessage = 'Consent please :)';
const onInputScript = 'if(!this.validity.patternMismatch) { this.setCustomValidity(""); }';

//Email
const emailInput = widget.querySelector("#email");
emailInput.setAttribute('pattern','^((?!gmail.com)(?!hotmail).)*$');
emailInput.setAttribute('oninvalid', 'this.setCustomValidity("' + emailValidationMessage + '")');
emailInput.setAttribute('oninput', onInputScript);

//Phone number
const phoneInput = widget.querySelector("#telephone");
phoneInput.setAttribute('pattern','^\\+\\d{10,12}$');
phoneInput.setAttribute('oninvalid', 'this.setCustomValidity("' + phoneValidationMessage + '")');
phoneInput.setAttribute('oninput', onInputScript);

//Name
const nameInput = widget.querySelector("#name");
nameInput.setAttribute('pattern','^([\\w]{3,})+\\s+([\\w\\s]{3,})+$');
nameInput.setAttribute('oninvalid', 'this.setCustomValidity("' + nameValidationMessage + '")');
nameInput.setAttribute('oninput', onInputScript);

//Consent checkbox
const consentInput = widget.querySelector('#triggerbee-consent-checkbox');
consentInput.setAttribute('oninvalid', 'this.setCustomValidity("' + consentValidationMessage + '")');
consentInput.setAttribute('oninput', onInputScript);


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

Still need help? Contact Us Contact Us