Last active
October 6, 2021 18:22
-
-
Save mauricerenck/9bd58fe0f71e52d1367dd4bf7f4d6f8f to your computer and use it in GitHub Desktop.
This file contains 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
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