Allow use to press enter to open top search result

This commit is contained in:
Akbar Rahman 2021-08-24 14:53:25 +01:00
parent 1c72f127d3
commit 7654745cf0

View File

@ -10,11 +10,14 @@ const fuse = new Fuse(data, {
const searchBar = document.getElementById('search') const searchBar = document.getElementById('search')
const resultsMax = document.getElementById('resultsMax') const resultsMax = document.getElementById('resultsMax')
const results = document.getElementById('results') const resultsDiv = document.getElementById('results')
function callback() { var results = []
results.innerHTML = ''
fuse.search(searchBar.value).slice(0, parseInt(resultsMax.value)).forEach(r => { function updateResults() {
resultsDiv.innerHTML = ''
results = fuse.search(searchBar.value).slice(0, parseInt(resultsMax.value))
results.forEach(r => {
wrapper = document.createElement('div') wrapper = document.createElement('div')
wrapper.className = "article" wrapper.className = "article"
@ -60,12 +63,18 @@ function callback() {
wrapper.appendChild(p) wrapper.appendChild(p)
}) })
results.appendChild(wrapper) resultsDiv.appendChild(wrapper)
}) })
} }
searchBar.addEventListener('keyup', callback) searchBar.addEventListener('keyup', e => {
searchBar.addEventListener('change', callback) // if user pressed enter
resultsMax.addEventListener('keyup', callback) if (e.keyCode === 13) {
resultsMax.addEventListener('change', callback) window.location.href = results[0].item.path
callback() }
updateResults()
})
searchBar.addEventListener('change', updateResults)
resultsMax.addEventListener('keyup', updateResults)
resultsMax.addEventListener('change', updateResults)
updateResults()