How can I make a custom "no results" message with the Swiftype jQuery search plugin?

jquery

#1

To implement your own message to be displayed when there are no results, you can add a custom post-render function. This function is called after the results have been rendered.

The default version (as of this writing) looks like this (look at the source code for the latest):

var defaultPostRenderFunction = function(data) {
  var totalResultCount = 0;
  var $resultContainer = this.getContext().resultContainer;
  if (data['info']) {
    $.each(data['info'], function(index, value) {
      totalResultCount += value['total_result_count'];
    });
  }

  if (totalResultCount === 0) {
    $resultContainer.html("<div id='st-no-results' class='st-no-results'>No results found.</div>");
  }
};

This function replaces the contents of the resultContainer (which serves as the DOM element where the results are rendered when configuring the plugin) with a message if no results were found. That condition is determined by summing up the total_result_count of all the document types.

Note that the post-render function is called with this set to the element thatswiftypeSearch was called on. This method allows you to call this.getContext() in order to gain access to plugin configuration.

To configure your own post-render function, add it to the plugin configuration:

var customPostRenderFunction = function(data) {
  console.log("I'm running after the search!");
  var resultContainer = this.getContext().resultContainer;
  resultContainer.prepend("<h1>Here's some text that will go above the results!</h1>");
  }
}

$("#st-search-input").swiftypeSearch({
  resultContainingElement: "#st-results-container",
  engineKey: "your_engine_key",
  postRenderFunction: customPostRenderFunction
});