Before you begin
This guide assumes that you know HTML, CSS, and JavaScript and that you have existing HTML with an input element where you want to implement an autocomplete drop-down menu. Using this plugin doesn’t require an Algolia application. If you plan on including other sections in your autocomplete such as suggested searches, you do need an Algolia application with the Query Suggestions feature enabled.Get started
Begin with the following code. Create a file calledindex.js in your src directory:
JavaScript
autocomplete as an id.
Change the container to match your markup.
Setting openOnFocus to true ensures that the drop-down menu appears as soon as a user focuses the input.
For now, plugins is an empty array, but you’ll learn how to add the Recent Searches plugin next.
Add recent searches
The Autocomplete library provides thecreateLocalStorageRecentSearchesPlugin function for creating a recent searches plugin out-of-the-box. To use it, you need to provide a key and limit.
The key can be any string and is required to differentiate search histories if you have multiple Autocomplete UI elements on one page.
The limit defines the maximum number of recent searches to display.
JavaScript
recentSearchesPlugin reads from localStorage, you won’t see any recent searches in your implementation until you’ve made some searches.
To submit a search, be sure to press Enter on the query.
Once you do, you’ll see it appear as a recent search.
Customize recent searches
ThecreateLocalStorageRecentSearchesPlugin function
creates a functional plugin out of the box.
You may want to customize some aspects of it,
depending on your use case.
To change templates or other source configuration options, you can use transformSource. The function includes the original source, which you should return along with any options you want to add or overwrite.
For example, if you use Autocomplete as an entry point to a search results page,
you can turn recent searches into links by modifying getItemUrl and the item template.
onSelect:
JavaScript
Use your own storage
Sometimes, you may not want to use local storage for your recent search data. You may want to use session storage or handle recent searches on your backend. If so, you can use thecreateRecentSearchesPlugin to implement your own storage:
JavaScript