Created
July 24, 2023 12:29
-
-
Save mfyz/9c6e9357a64b06a10663d26331c6bfcb to your computer and use it in GitHub Desktop.
Algolia automcomplete.js vanilla
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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