Skip to content

Instantly share code, notes, and snippets.

@mfyz
Created July 24, 2023 12:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mfyz/9c6e9357a64b06a10663d26331c6bfcb to your computer and use it in GitHub Desktop.
Save mfyz/9c6e9357a64b06a10663d26331c6bfcb to your computer and use it in GitHub Desktop.
Algolia automcomplete.js vanilla
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body {
font: 16px/24px Arial, Helvetica, sans-serif;
}
#content_wrapper {
width: 600px;
margin: 50px auto;
}
#result_wrapper {
margin-top: 20px;
}
.aa-ItemContentTitle mark {
background-color: gold !important;
}
</style>
</head>
<body>
<script src="https://cdn.jsdelivr.net/npm/@algolia/autocomplete-js"></script>
<script src="https://cdn.jsdelivr.net/npm/algoliasearch"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@algolia/autocomplete-theme-classic" />
<div id="content_wrapper">
<div id="naics_wrapper"></div>
<div id="result_wrapper"></div>
</div>
<script>
const { autocomplete, getAlgoliaResults } = window['@algolia/autocomplete-js']
const searchClient = algoliasearch('', '')
alcJsInitAlgoliaSearchRef = autocomplete({
container: '#naics_wrapper',
placeholder: `Business description`,
getSources ({ setQuery, refresh }) {
return [
{
sourceId: 'querySuggestions',
getItemInputValue: ({ item }) => item.query,
onSelect: function(event) {
event.setQuery(event.item.Description)
// refresh();
document.querySelector('#result_wrapper').innerHTML = 'Selected NAICS Code: ' + event.item.Code
},
getItems ({ query }) {
return getAlgoliaResults({
searchClient,
queries: [
{
indexName: 'NAICS',
query,
params: {
hitsPerPage: 10
}
}
]
})
},
templates: {
item ({ item, components, html }) {
return html`<div class="aa-ItemWrapper">
<div class="aa-ItemContent">
<div class="aa-ItemContentBody">
<div class="aa-ItemContentTitle">
${components.Highlight({ hit: item, attribute: 'Description' })}
</div>
</div>
</div>
</div>`
}
}
}
]
}
})
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment