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. 

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

Remove Close button on Campaign

window.addEventListener('load', function () {
    var widget = document.querySelector('triggerbee-widget[data-id="1234"]');
    if (widget) {
        widget.shadowRoot.querySelector('.close').style.display = "none";
    }
});

Log goal on a specific state in Onsite Campaigns

document.addEventListener("onTriggerbeeWidgetStateSwitched", function (event) {
    if (event.detail.stateId==1234) {
        mtr.goal("State goal");
    }
});

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

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, "") + ";";
}
<br>// Get Cookies
var tbVisitsCookie=Cookies.get("triggerbee_total_visits");
var tblastVisit=Cookies.get("triggerbee_last_visit");
var todayDate = new Date().toISOString().slice(0,10);
<br>// Check if cookie exists
if (!tbVisitsCookie) {<br>	// 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 ) {<br>	// 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);
    }
}
<br>// 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

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

Store data in cookie

// this particular variable is from GTM, but snippet can be used outside GTM too<br>var productsInCart = {{Checkout - items}};
<br>// 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);<br>}<br>else{
	var cookieArray = JSON.parse(productCookie);
	cookieArray.push(productsInCart[0]);
	Cookies.set("products_in_cart",JSON.stringify(cookieArray),10);
    }<br>
// Get new cookie and log to Triggerbee  
var newProductCookie = Cookies.get("products_in_cart");
window.mtr_custom.session = { products: newProductCookie}

Target Campaigns based on Elements

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

Target Campaigns based on URL

// Domain, ex. google.com
window.location.host == "domain.com"

// Page, ex. /products/t-shirt
window.location.pathname == "path"

// Query, ex. a certain utm-tag
window.location.search == "utm_campaign=wintercampaign"

Add tags based on host  

document.addEventListener("afterTriggerbeeReady", function () {
    if (window.location.host == "yourdomain.com") {
        triggerbee.session.addTags('Yourdomain');
    }
});

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

Change CSS in Mobile devices - 1 slide

window.addEventListener('load', function() {
var widget = document.querySelector('triggerbee-widget');
var widgetwidth = window.innerWidth;
    if(widget && widgetwidth < 767){
        widget.shadowRoot.querySelector('.state').style.marginRight="20px";
              widget.shadowRoot.querySelector('.state').style.marginLeft="20px";
    }
});

Change CSS in Mobile devices - several slides

Use the Triggerbee widget-open event. If the correct widget opens, and its a mobile device - get the shadowRoot of the widget and adjust the desired CSS. 

document.addEventListener("onTriggerbeeWidgetOpened", function (event) {
    var widget = document.querySelector('triggerbee-widget');
    if(event.detail.id==1234 && window.innerWidth < 767){
      setTimeout(function(){ 
        var states = widget.shadowRoot.querySelectorAll('.state');
        for (var index = 0; index < states.length; index++) {
            const state = states[index];
            state.style.marginRight="20px";
            state.style.marginLeft="20px";
        }
        }, 1000);
    }
  });

Open a campaign on click 

This snippet listens to a click on a certain button and opens a specific campaign on that 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);
            })
        }
    }
});

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

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

Check totalSum in Checkout

Gets the sum in the checkout page, and removes the last three characters (in this case 399,00 will 399).

if (window.location.pathname=="/checkout") {
	var tbtotalSum = document.querySelector(".total").innerText.slice(0, -3);
}

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

    });
}

Day and time selector

Used for conditioning campaigns to only display certain days/times. 

var triggerbeeClient = triggerbeeClient || (function () {

    function init() {
            if (dates.isWithinHours(8, 18) && dates.isWeekDay(['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'])) {
	            // Code that should happen on selected day and time. 
            }
	}

    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 {

    }
})();

General Triggerbee Namespace Function  

var triggerbeeClient = triggerbeeClient || (function () {

    function init(){
        myFunction();
    }

    function myFunction(){
      // Code to run
    }

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

    return {

    }
})();
Did this answer your question? Thanks for the feedback! Please reach out to s[email protected] if there's anything you'd like to add. There was a problem submitting your feedback. Please try again later.

Still need help? Contact Us Contact Us