Javascript Snippet Library

This is a collection of Javascript snippets that may be used in full or for inspiration in order to log events to Triggerbee. You will find scripts that cover these areas: 

Campaign Targeting

Target Campaigns based on element CSS

getComputedStyle(document.querySelector(".login-button")).display=="none"

Target Campaigns based on DOM elements

// Check if the user is logged out, based on the string "login" being rendered somewhere.
document.querySelector(".login-button").innerText=="login";

// Check the total sum in cart
document.querySelector(".total").innerText.slice(0, -3);

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


Campaign Design

Change color of copy check mark

document.addEventListener("onTriggerbeeWidgetOpened", function () {
	document.querySelector('triggerbee-widget').shadowRoot.querySelector(".checkmark-circle").style.backgroundColor="#000";
});

Rolling animation (Marquee)

document.addEventListener("onTriggerbeeWidgetOpened", function (event) {
    if (event.detail.campaignName.includes("Marquee")) {
      var sheetMarquee = document.createElement('style');
        sheetMarquee.innerHTML = `
        .marquee {
            height: 30px;
            overflow: hidden;
            position: relative;
            flex-direction: row;
        }

        .marquee p {
            white-space: nowrap;
            position: unset;
            width: 100%;
            height: 100%;
            margin: 0;
            line-height: 30px;
            text-align: center;
            -moz-transform: translateX(100%);
            -webkit-transform: translateX(100%);
            transform: translateX(100%);
            -moz-animation: scroll-left 3s linear infinite;
            -webkit-animation: scroll-left 3s linear infinite;
            animation: scroll-left 45s linear infinite;
        }

        @-moz-keyframes scroll-left {
            0% {
                -moz-transform: translateX(100%);
            }
            100% {
                -moz-transform: translateX(-100%);
            }
        }

        @-webkit-keyframes scroll-left {
            0% {
                -webkit-transform: translateX(100%);
            }
            100% {
                -webkit-transform: translateX(-100%);
            }
        }

        @keyframes scroll-left {
            0% {
                -moz-transform: translateX(100%);
                -webkit-transform: translateX(100%);
                transform: translateX(100%);
            }
            100% {
                -moz-transform: translateX(-100%);
                -webkit-transform: translateX(-100%);
                transform: translateX(-100%);
            }
        }
@media only screen and (max-width: 767px){
	.marquee p {
		animation: scroll-left 25s linear infinite;
	}
}
        `;

var tbWidget=document.querySelector('triggerbee-widget[data-id="'+event.detail.id+'"]');
tbWidget.shadowRoot.appendChild(sheetMarquee);

var tbWrap=tbWidget.shadowRoot.querySelector(".text-content").classList.add("marquee");

var bfElement=tbWidget.shadowRoot.querySelector(".text-content p");

tbWidget.shadowRoot.querySelector(".text-content").appendChild(bfElement.cloneNode(true));
tbWidget.shadowRoot.querySelector(".text-content").appendChild(bfElement.cloneNode(true));
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);
});

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=="/kassan/"){
    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);
    } 

    mtr_custom.session = { cartproducts: JSON.stringify(tbCartProducts)};
    mtr.goal("Påbörjat Köp");
}

Voyado Cart Abandoned

if(window.location.pathname=="/kassan/"){
    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);
    } 

    mtr_custom.session = { products: JSON.stringify(tbCartProducts), time: time};
    mtr.goal("Påbörjat Köp");
}

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=="/kassa") {
    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("Påbörjat Köp");
}

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("Loggat 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

Randomize number 1-100 for AB-testing

var testNumber=Math.floor((Math.random() * 100) + 1);

General Triggerbee Namespace Function  

var triggerbeeClient = triggerbeeClient || (function () {

    function init(){
        myFunction();
    }

    function myFunction(){
      // Code to run
    }

    window.addEventListener('load', function() {
        init();       
    });

    return {

    }
})();

Advanced Cookies

Cookie for counting total pageviews

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

// Get Cookie
var tbPageViewCookie=Cookies.get("triggerbee_total_pageviews");

// Check if cookie exists
if (!tbPageViewCookie) {
    // if not - create new cookie with value 1
    setCookie("triggerbee_total_pageviews",1,365);
}else{
    // else get cookie and update value +1
    tbPageViewCookie = parseInt(tbPageViewCookie)+1;
    setCookie("triggerbee_total_pageviews",tbPageViewCookie,365);
}

// Get new cookie and log to Triggerbee namespace
var newtbPageViewCookie = Cookies.get("triggerbee_total_pageviews");
window.triggerbee=window.triggerbee || {};
window.triggerbee.totalPageviews=parseInt(newtbPageViewCookie);

Cookie for counting total visits (one per day)

// Create cookie function<br>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, "") + ";";
}
// Get Cookies
var tbVisitsCookie=Cookies.get("triggerbee_total_visits");
var tblastVisit=Cookies.get("triggerbee_last_visit");
var todayDate = new Date().toISOString().slice(0,10);
// Check if cookie exists
if (!tbVisitsCookie) {	// if not - set cookie A with todays date, and cookie B with value 1
    setCookie("triggerbee_last_visit",todayDate,365);
    setCookie("triggerbee_total_visits",1,365);
}else{
	// check if todays date is later than last visit
    if (todayDate != tblastVisit ) {	// if yes - update cookie A value with todays date, and update cookie B with +1
        tbVisitsCookie = parseInt(tbVisitsCookie)+1;
        setCookie("triggerbee_last_visit",todayDate,365);
        setCookie("triggerbee_total_visits",tbVisitsCookie,365);
    }
}
// Get new cookie and log to Triggerbee namespace
var tbTotalVisits=Cookies.get("triggerbee_total_visits");
window.triggerbee=window.triggerbee || {};
window.triggerbee.totalPageviews=parseInt(tbTotalVisits);

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

Trigger Campaign based on time or week day

var triggerbeeClient = triggerbeeClient || (function () {

    function init() {
      console.log("init");
        var tbLocation = window.location.pathname;
        var tbInvoiceLinks = document.querySelectorAll(".invoice-link");

        if (tbLocation === "/minasidor/fakturor" && tbInvoiceLinks) {
            if (dates.isWithinHours(8, 18) && dates.isWeekDay(['Monday', 'Tuesday','Wednesday', 'Thursday', 'Friday'])) { // Inom öppetiderna
                for (var index = 0; index < tbInvoiceLinks.length; index++) {
                    const tbInvoiceLink = tbInvoiceLinks[index];
                    tbInvoiceLink.addEventListener("click", function () {
                        triggerbee.widgets.api.open(2655);
                    })
                }
            }
        }
    }

    var dates = dates || (function () {

        // Whether current hour is whitin a specific range
        function isWithinHours(startHour, endHour) {
            var now = new Date();
            var nowHour = now.getHours();

            // Check if current hour equals or is higher than provided AND current hour is LOWER than provided
            // Example: 9 and 11 is provided - 11:05 doesn't match the end hour
            // Example: 9 and 11 is provided - 10:59 in whitin both
            if (nowHour >= startHour && nowHour < endHour) {
                return true;
            } else {
                return false;
            }
        }

        // Whether today is one of the provided weekdays or not
        function isWeekDay(weekDays) {
            var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
            var now = new Date();
            var nowDayIndex = now.getDay();

            // Go through all provided weekdays
            for (var i = 0; i < weekDays.length; i++) {
                var weekDay = weekDays[i];
                // Check if today is one of current provided weekdays
                if (weekDay.toLowerCase() === days[nowDayIndex].toLowerCase()) {
                    // Yepp, it is!
                    return true;
                }
            }

            // Today doesn't match any provided weekday
            return false;
        }

        return {
            isWithinHours: isWithinHours,
            isWeekDay: isWeekDay
        }
    })(); // dates namespace


    window.addEventListener('load', function () {
        init();
    });

    return {

    }
})();

Still need help? Contact Us Contact Us