How To Add Autocomplete to Webflow

Here we explore to add autocomplete to a search input on a Webflow website that also uses Finsweet's CMS Nest and CMS Filter. This is a great way to improve UX for a search functionality where you might have a large number of predetermined options like tags or categories. We'll use autoComplete.js, which is a free and lightweight 9kb external library and I'll show you how to completely customize the data it pulls from CMS in addition to fully customizing its styling with CSS.

Watch the Tutorial on YouTubeGet the Project Cloneable

Inside <head> tag

<!-- [Attributes by Finsweet] CMS Nest -->
<script async src="https://cdn.jsdelivr.net/npm/@finsweet/attributes-cmsnest@1/cmsnest.js"></script>
<!-- [Attributes by Finsweet] CMS Filter -->
<script async src="https://cdn.jsdelivr.net/npm/@finsweet/attributes-cmsfilter@1/cmsfilter.js"></script>

Inside </body> tag

<script src="https://cdn.jsdelivr.net/npm/@tarekraafat/autocomplete.js@10.2.7/dist/autoComplete.min.js">
</script>
<script>
window.fsAttributes = window.fsAttributes || [];
window.fsAttributes.push([
  "cmsnest",
  (listInstances) => {
    // cmsnest is finished

    // select all the categories
    const categories = document.querySelectorAll(
      '[wb-autocomplete="category"]'
    );

    // duplicates generates by cms nest
    // remove duplicates by creating a set from the cateogories.
    const categorySet = new Set();
    categories.forEach((category) => {
      categorySet.add(category.textContent);
    });

    // set back to array. autoComplete expects an array
    const uniqueCategoriesArray = [...categorySet];

    // create new instance of autoComplete
    const autoCompleteJS = new autoComplete({
      // configuration: https://tarekraafat.github.io/autoComplete.js/#/configuration
      selector: "#autoComplete",
      data: {
        src: uniqueCategoriesArray // the data
      },
      name: "auto-complete",
      threshold: 1,
      debounce: 300,
      searchEngine: "strict",
      resultItem: {
        highlight: true
      },
      maxResults: 5,
      events: {
        input: {
          selection: (event) => {
            const selection = event.detail.selection.value;
            autoCompleteJS.input.value = selection;
            // simulate event so CMS filter registers the change
            const simulatedEvent = new Event("input", { bubbles: true });
            autoCompleteJS.input.dispatchEvent(simulatedEvent);
          }
        }
      }
    });
    autoCompleteJS.start();
  }
]);
</script>