How To Add Autocomplete For Search Boxes To Your Shopify Store

In this article I will show you how to add/enable autocomplete for your search boxes to your Shopify store. It is easy to do and will be a great feature.

Log in to your Shopify store. From your Shopify admin, go to Online Store > Themes. Click Actions > Edit code.

Step 1: Create new template for search page – search.json.liquid

In the Templates directory, click Add a new template. Choose a type option for your new template. For an alternate search template, select search and give the template a name: json.

Click Create template. Your new template will open in the code editor, and the file will be populated with default code. Replace default code with the below code.

				
					{% layout none %}
{% capture results %}
  {% for item in search.results %}
    {% assign product = item %}
    { 
      "title"    : {{ product.title | json }},
      "url"      : {{ product.url | within: product.collections.last | json }},
      "thumbnail": {{ product.featured_image.src | product_img_url: 'thumb' | json }}
    }
    {% unless forloop.last %},{% endunless %}
  {% endfor %}
{% endcapture %}
{
  "results_count": {{ search.results_count }},
  "results": [{{ results }}]
}
				
			

Step 2: Create search-autocomplete.liquid file

In the Snippets directory, click Add a new snippet. In popup appear: Give your snippet the name search-autocomplete and click Create snippet.

In the online code editor, paste the content from the below text.

				
					{% assign results_box_width = '242px' %}
{% assign results_box_background_color = '#ffffff' %}
{% assign results_box_border_color = '#d4d4d4' %}

<script>
$(function() {
  // Current Ajax request.
  var currentAjaxRequest = null;
  // Grabbing all search forms on the page, and adding a .search-results list to each.
  var searchForms = $('form[action="/search"]').css('position','relative').each(function() {
    // Grabbing text input.
    var input = $(this).find('input[name="q"]');
    // Adding a list for showing search results.
    var offSet = input.position().top + input.innerHeight();
    $('<ul class="search-results"></ul>').css( { 'position': 'absolute', 'left': '0px', 'top': offSet } ).appendTo($(this)).hide();    
    // Listening to keyup and change on the text field within these search forms.
    input.attr('autocomplete', 'off').bind('keyup change', function() {
      // What's the search term?
      var term = $(this).val();
      // What's the search form?
      var form = $(this).closest('form');
      // What's the search URL?
      var searchURL = '/search?type=product&q=' + term;
      // What's the search results list?
      var resultsList = form.find('.search-results');
      // If that's a new term and it contains at least 3 characters.
      if (term.length > 3 && term != $(this).attr('data-old-term')) {
        // Saving old query.
        $(this).attr('data-old-term', term);
        // Killing any Ajax request that's currently being processed.
        if (currentAjaxRequest != null) currentAjaxRequest.abort();
        // Pulling results.
        currentAjaxRequest = $.getJSON(searchURL + '&view=json', function(data) {
          // Reset results.
          resultsList.empty();
          // If we have no results.
          if(data.results_count == 0) {
            // resultsList.html('<li><span class="title">No results.</span></li>');
            // resultsList.fadeIn(200);
            resultsList.hide();
          } else {
            // If we have results.
            $.each(data.results, function(index, item) {
              var link = $('<a></a>').attr('href', item.url);
              link.append('<span class="thumbnail"><img src="' + item.thumbnail + '" /></span>');
              link.append('<span class="title">' + item.title + '</span>');
              link.wrap('<li></li>');
              resultsList.append(link.parent());
            });
            // The Ajax request will return at the most 10 results.
            // If there are more than 10, let's link to the search results page.
            if(data.results_count > 10) {
              resultsList.append('<li><span class="title"><a href="' + searchURL + '">See all results (' + data.results_count + ')</a></span></li>');
            }
            resultsList.fadeIn(200);
          }        
        });
      }
    });
  });
  // Clicking outside makes the results disappear.
  $('body').bind('click', function(){
    $('.search-results').hide();
  });
});
</script>

<!-- Some styles to get you started. -->
<style>
.search-results {
  z-index: 8889;
  list-style-type: none;   
  width: {{ results_box_width }};
  margin: 0;
  padding: 0;
  background: {{ results_box_background_color }};
  border: 1px solid {{ results_box_border_color }};
  border-radius: 3px;
  -webkit-box-shadow: 0px 4px 7px 0px rgba(0,0,0,0.1);
  box-shadow: 0px 4px 7px 0px rgba(0,0,0,0.1);
  overflow: hidden;
}
.search-results li {
  display: block;
  width: 100%;
  height: 38px;
  margin: 0;
  padding: 0;
  border-top: 1px solid {{ results_box_border_color }};
  line-height: 38px;
  overflow: hidden;
}
.search-results li:first-child {
  border-top: none;
}
.search-results .title {
  float: left;
  width: {{ results_box_width | remove: 'px' | to_number | minus: 50 }}px;
  padding-left: 8px;
  white-space: nowrap;
  overflow: hidden;
  /* The text-overflow property is supported in all major browsers. */  text-overflow: ellipsis;
  -o-text-overflow: ellipsis;
  text-align: left;
}
.search-results .thumbnail {
  float: left;
  display: block;
  width: 32px;
  height: 32px;    
  margin: 3px 0 3px 3px;
  padding: 0;
  text-align: center;
  overflow: hidden;
}
</style>
				
			

Step 3: Edit theme.liquid file

In the Layouts folder, locate and click on your theme.liquid file to open it in the online code editor. In the online code editor, scroll down a bit until you see the closing tag. Right before the closing tag, paste the below code.

				
					{% include 'search-autocomplete' %}
				
			

Done! Check it out.

Copy of LogoFinalLargeColor

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.