Search code examples
javascriptjquerytrustpilot

Cannot show TrustPilot HTML when inserted with JavaScript (jQuery)


If I added the TrustPilot html code directly on the HTML page, it works fine but I needed to insert it with jQuery. I see the HTML code when inserted but it's not displaying.

  $(window).on('load', function () {
    var el = $('#some-element');

    el.html( trustPilotHtml() );

    function trustPilotHtml() {
      var str = "<div " +
        "class='trustpilot-widget' " +
        "data-locale='en-GB' " +
        "data-template-id='123456' "+
        "data-businessunit-id='123456' " +
        "data-style-height='500px' " +
        "data-style-width='100%' " +
        "data-theme='light' " +
        "data-stars='4,5' " +
        "data-schema-type='Organization'>" +
        "<a " +
        "href='https://some-url.com' target='_blank'>Trustpilot</a> " +
      "</div>";
      return $(str);
    }
});

Is the only way of getting the element to display properly is to directly inserted into the HTML without javascript?


Solution

  • No it's not the only way.

    You should have a bootstrap script in your inside the HEAD part of your HTML (or close to it). This script takes care of initializing all the widgets (TrustBoxes in Trustpilot lingo) that you have in your HTML.

    Of cause that doesn't work if you are injecting the HTML dynmically, so it's also possible to call window.Trustpilot.loadFromElement(trustbox); yourself, when if you need to.

    Here trustbox is a HTMLElement, you could get by using document.getElementById("some-element") or similar.

    Reference: https://support.trustpilot.com/hc/articles/115011421468