From 4f3b78834c5b29791bb768d44b98da5a0bada0c0 Mon Sep 17 00:00:00 2001 From: Gerome Matilla Date: Sat, 6 Jun 2020 09:52:16 +0800 Subject: [PATCH] autogenerate init --- index.html | 1 + js/auto-suggest.js | 54 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+) create mode 100644 js/auto-suggest.js diff --git a/index.html b/index.html index c9c157e..40a0742 100644 --- a/index.html +++ b/index.html @@ -254,5 +254,6 @@ + \ No newline at end of file diff --git a/js/auto-suggest.js b/js/auto-suggest.js new file mode 100644 index 0000000..8498d52 --- /dev/null +++ b/js/auto-suggest.js @@ -0,0 +1,54 @@ +var searchBox = document.getElementById('searchBox'); +var suggestionsUL = document.getElementById('suggestions'); + +const autocompleteCallback = phrase => { + + + var suggestion = phrase.map(i => i.phrase) + .filter(s => !(s.toLowerCase() === String(searchBox.value).toLowerCase())) + .slice(0, 4); + + + // Empty ul on every callback + suggestionsUL.innerHTML = ''; + // console.log(suggestion); + + + for (i=0; i<(suggestion.length); i++) { + + // console.log(suggestion[i]); + + var li = document.createElement('li'); + li.id = 'phrase'; + + var button = document.createElement('button'); + button.type = 'button'; + button.className = 'phraseButton'; + + + button.innerHTML = suggestion[i]; + + + li.appendChild(button); + suggestionsUL.appendChild(li); + + + } + + + +} + + +searchBox.onkeydown = () => { + + if (searchBox.value < 1) { + return; + } + + var script = document.createElement('script'); + script.type = "text/javascript"; + script.src = "https://duckduckgo.com/ac/?callback=autocompleteCallback&q="+String(searchBox.value); + document.querySelector('head').appendChild(script); + +} \ No newline at end of file