How To Add a Script To the Page

Find out how to add advanced features to your website
You can add any script to your website. Add a T123 block ("Embed HTML code") from the "Other" category to the page and embed the script in it. Here is a selection of code samples you can use to expand the features on your website.
After transferring it to the Tilda data capture service
Before taking the website visitor from the shopping cart to the payment system's website
Responding to clicks on links or buttons of specific classes
Please note that you might need to modify the code samples from this guide before using them on your website. You may need to understand how JavaScript works to proceed. Unfortunately, Tilda does not provide support on issues related to using third-party code.
Event interception
on the web page
Event interception comes in handy when you need to track pop-up events, link clicks, or data transfers to a third party after a successful form submission and much more, depending on what you need or would like to try.
Script for intercepting link clicks
<script>
  if (document.readyState !== 'loading') {
    us_clickInterception();
  } else {
    document.addEventListener('DOMContentLoaded', us_clickInterception);
  }

  function us_clickInterception() {
    var links = document.querySelectorAll('a');
    Array.prototype.forEach.call(links, function (link) {
      link.addEventListener('click', function () {
        /* write action type */
      });
    });
  }
</script>
Script for intercepting link clicks in a specific block
Here's how you can intercept link clicks in the block #rec123456789
<script>
  if (document.readyState !== 'loading') {
    us_clickInterceptionInBlock();
  } else {
    document.addEventListener('DOMContentLoaded', us_clickInterceptionInBlock);
  }

  function us_clickInterceptionInBlock() {
    var links = document.querySelectorAll('#rec123456789 a');
    Array.prototype.forEach.call(links, function (link) {
      link.addEventListener('click', function () {
        /* write action type */
      });
    });
  }
</script>
where #rec123456789 is the ID of the block where the weather widget will be placed.

You can find the block ID in the Settings panel of the block.
Script for tracking button click events
There are two buttons, one leading to a text block on the same page, the other to a different page. The first button has an anchor for the block #rec12345678, and the second one contains a link to the external page http://help-ru.tilda.ws.
<script> 
$(document).ready(function () {
    $("[href='#rec123456789']").click(function () {
        yaCounterXXXXXX.reachGoal('CLICK1');
    });

    $("[href='http://help-ru.tilda.ws/']").click(function () {
        yaCounterXXXXXX.reachGoal('CLICK2');
    });
});
</script>
where XXXXXX is the counter ID.
Script for sending information about link or button clicks to Google Analytics
You can use this script for tracking clicks on any link or button whose address contains "a value in URL." If such a click occurs, you will be notified about it. Below is a sample code. The values that are to be replaced are in UPPERCASE.
<script>
  if (document.readyState !== 'loading') {
    us_sendGoogleAnalytics();
  } else {
    document.addEventListener('DOMContentLoaded', us_sendGoogleAnalytics);
  }

  function us_sendGoogleAnalytics() {
    var links = document.querySelectorAll('a');
    Array.prototype.forEach.call(links, function (link) {
      link.addEventListener('click', function (e) {
        if (link.href && link.href.indexOf('URL Value') !== -1) {
          e.preventDefault();
          ga('send', {
            'hitType': 'pageview',
            'page': '/click' + window.location.pathname,
            'title': 'Virtual page name',
          });
          setTimeout(function () {
            window.location = link.href;
          }, 200);
        }
      });
    });
  }
</script>
URL VALUE—here should be inserted any word found in the link. For example, when clicking on a button, the visitor is taken to the sign-up page: http://mysite.com/registration. Here you should replace the VALUE IN URL with "registration."

VIRTUAL PAGE NAME. In Google Analytics, information about a button click appears in the virtual page viewing statistics.

LINK—the link found on a button. For example, http://mysite.com/registration.

To track a button click as goal completion, create a new goal in Google Analytics: Custom Goal → Landing Page → Begins with / click /
Script for sending the form data to your resource after transferring it to the Tilda data capture service
Please insert the name of the function that the forms should call after a successful data transfer in all forms on your site.
<script>
function mySuccessFunction(form) {
    if (!form) return;
    if (form instanceof jQuery) {
      form = form.get(0);
    }

    /* Lead ID */
    var leadId = form.tildaTranId;
    var orderId = form.tildaOrderId;

    /* fields in the lead */
    var obj = {};
    var inputs = form.elements;
    Array.prototype.forEach.call(inputs, function (input) {
      obj[input.name] = input.value;
    });
    /*
    to address to field value use:
    obj["Name"]
    obj["Phone"]
    obj["Email"]
    etc. 
    */
  }

  if (document.readyState !== 'loading') {
    us_sendFormAfterSuccess();
  } else {
    document.addEventListener('DOMContentLoaded', us_sendFormAfterSuccess);
  }

  function us_sendFormAfterSuccess() {
    var forms = document.querySelectorAll('.js-form-proccess');
    Array.prototype.forEach.call(forms, function (form) {
      form.addEventListener('tildaform:aftersuccess', function () {
        mySuccessFunction(form);
      });
    });
  }
</script>
Script for performing a custom function before taking the website visitor from the shopping cart to the payment system's website
If you need to add information about the contents of the shopping cart to cookies or send eCommerce events to Google Analytics or Yandex.Metrica, use the script described above. The script is called right before the customer is redirected to the payment system's page or the payment widget is launched.
<script>
  window.myAfterSendedFunction = function (form) {
    if (!form) return;
    if (form instanceof jQuery) {
      form = form.get(0);
    }

    /* Lead ID */
    var leadId = form.tildaTranId;
    var orderId = form.tildaOrderId;

    /* fields in the lead */
    var obj = {};
    var inputs = form.elements;
    Array.prototype.forEach.call(inputs, function (input) {
      obj[input.name] = input.value;
    });

    /* here you should write a data sending code to the destination, e.g. data receiving to your script or data adding in cookie */
  };

  if (document.readyState !== 'loading') {
    us_eventFromCartToPayment();
  } else {
    document.addEventListener('DOMContentLoaded', us_eventFromCartToPayment);
  }

  function us_eventFromCartToPayment() {
    var forms = document.querySelectorAll('.js-form-proccess');
    Array.prototype.forEach.call(forms, function (form) {
      form.addEventListener('tildaform:aftersuccess', function () {
        window.myAfterSendedFunction(form);
      });
    });
  }
</script>
How to connect a custom or third-party service
Script for a third-party service responding to clicks on links or buttons of specific classes
For example, if the required service opens a special dialog when clicking on a button, you must apply the service script using the correct method. To avoid errors, specify the classes of the buttons first and embed the script afterward.
<script>
  if (document.readyState !== 'loading') {
    us_customDOMChanges();
  } else {
    document.addEventListener('DOMContentLoaded', us_customDOMChanges);
  }

  function us_customDOMChanges() {
    var buttons = document.querySelectorAll('.t-btn');
    Array.prototype.forEach.call(buttons, function (button) {
      /* add custom class to buttons */
      button.classList.add('superclass');
    });

    /* add service script */
    var service = document.createElement('script');
    service.src = 'https://superservice.com/script.js';
    service.type = 'text/javascript';
    service.charset = 'UTF-8';
    document.documentElement.appendChild(service);
  }
</script>
How to place a special widget over a block
Sometimes you want to add something extra special to the existing blocks, like adding a form to Zero Block or a weather widget to the page cover. Tilda makes even this possible. All you need to do is add an HTML block.
Script for adding a weather widget over a block
Add an HTML block to the page. Go to the website pogoda.yandex.ru, copy the widget code, click on Content and create magic. Embed this code in the specific block (the weather widget), just to the right from the center of the block.
<script>
$(document).ready(function () {
    var widget = $('<a href="https://clck.yandex.ru/redir/dtype=stred/pid=7/cid=1228/*https://pogoda.yandex.ru/213" target="_blank"><img src="//info.weather.yandex.net/213/1_white.ru.png?domain=ru" border="0" alt="Яндекс.Погода"/><img width="1" height="1" src="https://clck.yandex.ru/click/dtype=stred/pid=7/cid=1227/*https://img.yandex.ru/i/pix.gif" alt="" border="0"/></a>');
    widget.attr('style', 'display: block;left: 50%;margin-left: 20%;position: absolute;top: 100px;');
    $('#rec123456789').append(widget);
});
</script>
where #rec123456789 is the ID of the block where the weather widget will be placed.

You can find the block ID in the Settings panel of the block.
Script for launching different widgets on mobile and desktop
Sometimes you need to insert a bulky widget for the desktop version of the website and a small widget for the mobile version. To do this, you need to use the "window.isMobile" variable.
<script>
  if (document.readyState !== 'loading') {
    us_initAdaptiveWidget();
  } else {
    document.addEventListener('DOMContentLoaded', us_initAdaptiveWidget);
  }

  function us_initAdaptiveWidget() {
    if (window.isMobile == true) {
      /* code for mobile devices */
    } else {
      /* code for desktop devices */
    }
  }
</script>
Script for adding a mixed widget
Instead of window.isMobile, you can use screen sizes, for example, $(window).width () <960
<div id="widgetbox" style="text-align: center;">
    <div class="left" id="_bn_widget_"><a href="http://bnovo.ru/" id="_bnovo_link_" target="_blank">Bnovo</a></div>
    <script type="text/javascript" src="http://widget.bnovo.ru/v2/js/bnovo.js"></script>
</div>

<script>
  if (document.readyState !== 'loading') {
    us_appendMixedWidget();
  } else {
    document.addEventListener('DOMContentLoaded', us_appendMixedWidget);
  }

  function us_appendMixedWidget() {
    var html = '';
    if (window.isMobile == true) {
      /* code for mobile devices */
      html = '<script>';
      html += 'Bnovo_Widget.init(function(){Bnovo_Widget.open("_bn_widget_", {type: "vertical",lcode: "1234567890",lang: "ru",width: "230",background: "#ffda4a",bg_alpha: "100",padding: "18",font_type: "arial",font_color: "#222222",font_size: "16",title_color: "#222222",title_size: "18",inp_color: "#222222",inp_bordhover: "#3796e5",inp_bordcolor: "#cccccc",inp_alpha: "100",btn_background: "#f8f8f8",btn_background_over: "#ffffff",btn_textcolor: "#222222",btn_textover: "#222222",btn_bordcolor: "#cccccc",btn_bordhover: "#cccccc"});});';
      html += '</script' + '>';
    } else {
      /* code for desktop devices */
      html = '<script>' +
        'Bnovo_Widget.init(function(){Bnovo_Widget.open("_bn_widget_", {type: "horizontal",lcode: "1234567890",lang: "ru",width: "960",background: "#ffda4a",bg_alpha: "100",padding: "20",font_type: "arial",font_color: "#222222",font_size: "16",title_color: "#222222",title_size: "18",inp_color: "#222222",inp_bordhover: "#3796e5",inp_bordcolor: "#cccccc",inp_alpha: "100",btn_background: "#f8f8f8",btn_background_over: "#ffffff",btn_textcolor: "#222222",btn_textover: "#222222",btn_bordcolor: "#cccccc",btn_bordhover: "#cccccc"});});' +
        '</script' + '>';
    }
    var widgetBox = document.querySelector('#widgetbox');
    if (widgetBox) widgetBox.insertAdjacentHTML('beforeend', html);
  }
</script>
How to create a menu in Zero Block
For the menu created in Zero Block to behave like a regular menu, that is, superimposed on the next block and fixed on scroll, you need to add this code to the page, replacing rec000000000 with the ID of your Zero Block.
<style>
    /* Replace rec00000000 with Zero block ID */
    #rec00000000 {
        width: 100%;
        position: fixed;
        top: 0;
        z-index: 9998;
    }
</style>
Script for enabling interaction between a third-party script and a form in Zero Block
<script>
  function t396_onSuccess(form) {
    if (!form) return;
    if (form instanceof jQuery) {
      form = form.get(0);
    }

    /* Lead ID */
    var leadId = form.tildaTranId;
    var orderId = form.tildaOrderId;

    /* all lead fields */
    var obj = {};
    var inputs = form.elements;
    Array.prototype.forEach.call(inputs, function (input) {
      obj[input.name] = input.value;
    });

    /* Send data via POST-request */
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'https://yourwebhook.ru/form.php');
    xhr.send(JSON.stringify(obj));
    xhr.onload = function () {
      if (xhr.response) {
        /* Actions if data was received successfully */

        /* Redirection to the success page */
        var successUrl = form.getAttribute('data-success-url');
        if (successUrl) window.location.href = successUrl;
      }
    };
  }
</script>
Script for disabling automatic lead data transfers to Facebook Pixel
If you install Facebook Pixel, an fbq object will appear on the page that sends you information on the Lead event when the form data is transferred to Facebook. If you need a custom Facebook Pixel, you can disable this behavior using this code:
  <script>
        document.addEventListener('DOMContentLoaded', function() {
            var allRec = document.getElementById('allrecords');
            if (allRec) allRec.setAttribute('data-fb-event', 'nosend');
        });
  </script>
Please note that you are responsible for modifying the code samples used above. Using these samples requires understanding how JavaScript works. Unfortunately, we do not provide support on issues related to using third-party code.
Made on
Tilda