Skip to content

Instantly share code, notes, and snippets.

@mauricerenck
Last active October 6, 2021 18:22
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 mauricerenck/9bd58fe0f71e52d1367dd4bf7f4d6f8f to your computer and use it in GitHub Desktop.
Save mauricerenck/9bd58fe0f71e52d1367dd4bf7f4d6f8f to your computer and use it in GitHub Desktop.
inputField.addEventListener('keyup', event => {
// prevent some evil queries
const keyword = inputField.value.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&')
// at least two chars needed to trigger the search
if (keyword.length < 2) {
return false
}
// I use a timeout here, so the search is only then triggered, when the user stops typing for some milliseconds
// this way you don't flood your site with requests
clearTimeout(timer)
timer = setTimeout(() => {
fetch('/YOURSEARCH-PAGE.json?q=' + keyword, {
method: 'GET',
})
.then(response => response.json())
.then(response => {
// Here you can access the json result and create some html,
response.results.forEach((searchResult) => {
// get the fields you want
const title = searchResult.title;
})
// Append the generated html where you want it to be displayed
})
.catch(error => {
console.log(error)
})
}, 300)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment