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 need to be configured based on your specific webpage. They are not one-fits-all.

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) { // check if current time is after given time
        return true;
    }
}

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 if the total sum in cart is less than 300
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

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=="/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

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

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 weekday

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 {

    }
})();

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

Still need help? Contact Us Contact Us