
Before you begin
This tutorial assumes the following requirements:- An installation of the
autocomplete-js
package. - A populated Query Suggestions index. If you don’t have one, create it first: you can use the example application credentials and index provided in this tutorial.
- Existing HTML with an input element where you want to insert the autocomplete drop-down menu.
- Frontend development experience with HTML, CSS, and JavaScript.
Starter code
This tutorial builds an Autocomplete app composed of two columns:- A left column taking one third of the width which displays recent searches and Query Suggestions
- A right column taking up the rest of the space which displays products.
app.js
in your src
directory and add this code to it:
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.
Two-column layout
With therender
function of autocomplete-js
, you can customize the panel rendering to create two or more columns.
Add recent searches and Query Suggestions
Add the recent searches (with a limit of two recent searches) and Query Suggestions plugin (limiting the number of suggestions to seven) to the left column. This gives a total of nine items in the right column. Then, retrieve the recent searches and query suggestions plugins sources in therender
function using elements
and add it to the left column.
Create a “products” source
Add a source to retrieve and display the products in the right column. Create a dynamic source using thegetSources
function and retrieve the products from your Algolia index with the getAlgoliaResults
function.
Display products
Now that you’ve set up your source, you can display products with templates.Create a product item component
Start by creating a file calledProductItem.js
in your src
directory,
then copy and paste the following code (a component used to render each item of your source):
Render each source item
To render each source item, use thetemplates
option in your source with the item
function.
Add styles
Copy and paste the following CSS snippet in yoursrc
directory and call it style.css
.
CSS
app.js
file.
JavaScript
Next steps
This tutorial focuses on building a multi-column layout but you can improve it by:- Adding more sources
- Reshaping and combine your sources
- Adding no-result states