How to execute JavaScript code in the instantsearch page

On our instant search page, the search block is rendered with JavaScript.
Most of it is re-rendered every time a query is made.
Depending on what you want to change in the DOM, you’ll need either to use:

  • init, which is called once before the initial render
  • render, which is called at every render

The best way to see how it’s used is to look at our powered by logo code. It’s called both at init and render times.

    // Logo & clear
    instant.search.addWidget({
      init: function (opts) {
        if (!instant.poweredBy) {
          $('.ais-algolia-icon').hide();
        }
        $('.ais-clear-input-icon').on('click', function () {
          opts.helper.setQuery('').search();
          $('.ais-search-box--input').val('').focus();
        });
      },
      render: function (opts) {
        if (!opts.state.query) {
          if (instant.poweredBy) {
            $('.ais-algolia-icon').show();
          }
          $('.ais-clear-input-icon').hide();
        } else {
          $('.ais-clear-input-icon').show();
          $('.ais-algolia-icon').hide();
        }
      }
    });

For render, an alternative to that is to use instantsearch.js's render event, like so:

    instant.search.on('render', function () {
      // Do something
    })

Thanks @p.michael.dy for the question.

Answered in topic post :white_check_mark: