Skip to content

Instantly share code, notes, and snippets.

@chuckmeyer
Created October 12, 2022 14:35
Show Gist options
  • Save chuckmeyer/8660674511aa4edc98026cf6925c9718 to your computer and use it in GitHub Desktop.
Save chuckmeyer/8660674511aa4edc98026cf6925c9718 to your computer and use it in GitHub Desktop.
Embeddable Algolia Autocomplete in 100(ish) lines
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/@algolia/autocomplete-theme-classic"
/>
<style>
:root {
--aa-icon-size: 80px;
}
</style>
<script src="https://cdn.jsdelivr.net/npm/@algolia/autocomplete-js"></script>
<script src="https://cdn.jsdelivr.net/npm/preact/dist/preact.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/algoliasearch@4.5.1/dist/algoliasearch-lite.umd.js"></script>
<script>
const { autocomplete, getAlgoliaResults } = window['@algolia/autocomplete-js'];
const appId = "FMXYI0LKWR";
const apiKey = "15d19a7c0b842b9f627aeb8da4262105";
const indexName = "webflow-blog";
const searchClient = algoliasearch(appId, apiKey);
const { setIsOpen } = autocomplete({
container: "#autocomplete",
placeholder: "Search",
detachedMediaQuery: '',
openOnFocus: true,
getSources({ query, state }) {
if (!query) {
return [];
}
return [
{
sourceId: "blogs",
getItems() {
return getAlgoliaResults({
searchClient,
queries: [
{
indexName: indexName,
query,
params: {
attributesToSnippet: ['name:10', 'summary:35'],
snippetEllipsisText: '…',
hitsPerPage: 5
}
}
]
});
},
templates: {
header() {
return (
"Posts"
);
},
item({ item, components, html }) {
return html`<a class="aa-ItemLink" href="/posts/${item.slug}">
<div class="aa-ItemContent">
<div class="aa-ItemIcon aa-ItemIcon--alignTop">
<a href="/posts/${item.slug}"><img
src="${item.image}"
alt="${item.name}"
width="40"
height="40"
/></a>
</div>
<div class="aa-ItemContentBody">
<div class="aa-ItemContentTitle">
${components.Snippet({
hit: item,
attribute: 'name',
})}
</div>
<div class="aa-ItemContentSubtitle">
Published in <strong>${item.category}</strong>
</div>
<div class="aa-ItemContentDescription">
${components.Snippet({
hit: item,
attribute: 'summary',
})}
</div>
</div>
</div>
</a>`;
},
noResults() {
return "No posts for this query.";
}
},
getItemUrl({ item }) {
return "/posts/" + item.slug;
},
}
];
}
});
document.addEventListener('keydown', (event) => {
if (event.metaKey && event.key.toLowerCase() === 'k') {
setIsOpen(true);
}
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment