Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Algolia search from damieng.com
<script src="https://cdn.jsdelivr.net/npm/algoliasearch@3/dist/algoliasearchLite.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/algoliasearch-helper@2.26.0/dist/algoliasearch.helper.min.js"></script>
<script>
let searchForm = document.getElementById('search-form')
let hits = document.getElementById('hits')
let algolia = algoliasearch('{your-site-id}', '{your-search-token}')
let helper = algoliasearchHelper(algolia, '{your-index-name}', { hitsPerPage: 10, maxValuesPerFacet: 1, getRankingInfo: false })
helper.on("result", searchCallback)
function runSearch() {
var term = document.getElementById('s').value
if (term.length > 0)
helper.setQuery(term).search()
else
searchForm.classList.remove('open')
}
function searchCallback(results) {
if (results.hits.length === 0) {
hits.innerHTML = '<li><a>No results!</a></li>'
} else {
renderHits(results)
searchForm.classList.add('open')
}
let credits = document.createElement('li');
credits.innerHTML = "<img src=\"https://www.algolia.com/static_assets/images/press/downloads/search-by-algolia.svg\" onclick=\"window.open('https://www.algolia.com', '_blank')\" />"
hits.appendChild(credits)
}
function renderHits(results) {
hits.innerHTML = ''
for (let i = 0; i < results.hits.length; i++) {
let li = document.createElement('li')
let title = document.createElement('a')
title.innerHTML = results.hits[i]._highlightResult.title.value
title.href = results.hits[i].url
li.appendChild(title)
hits.appendChild(li)
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.