Last active
November 4, 2022 11:50
-
-
Save d3ep4k/1816f47fb9949d565bde11ee9b18cc61 to your computer and use it in GitHub Desktop.
Autocomplete Input in pure javascript https://metamug.com/article/html5/autocomplete-ajax.html
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
const searchBox = document.getElementById('searchbox'); | |
const dropdownMenu = document.getElementById('dropdown-menu'); | |
const searchBoxContainer = document.getElementById('searchbox-container'); | |
searchBox.addEventListener("keyup", function(event) { | |
const timer = setTimeout(function () { | |
var sr = event.target.value; | |
if(!sr) return; //Do nothing for empty value | |
searchBoxContainer.classList.add("control", "is-loading"); | |
const request = new Request('https://api.metamug.com/covid/v1.1/city?q='+sr+'&limit=7'); | |
fetch(request) | |
.then((response) => response.json()) | |
.then((data) => { | |
if (searchBox.value) { //sr not cleaned, backspace removed | |
dropdownMenu.replaceChildren(searchResult(data)); | |
//dropdownMenu.innerHTML = ''; dropdownMenu.appendChild(searchResult(srdata)); | |
} | |
searchBoxContainer.classList.remove("is-loading"); | |
}); | |
}, 500); | |
}); | |
function clearDropdown(){ | |
//dropdownMenu.replaceChildren(); https://stackoverflow.com/a/65413839/1097600 | |
dropdownMenu.innerHTML = ''; | |
searchBoxContainer.classList.remove("is-loading"); | |
} | |
//keep checking for empty searchbox every 5 seconds | |
setInterval(function() { | |
if (!searchBox.value) { //empty search box | |
clearDropdown() | |
} | |
}, 500); | |
function searchResult(result){ | |
const root = document.createElement('ul') | |
root.classList.add('box', 'has-text-black', 'mt-1' ); | |
const loc = result.loc1.concat(result.loc2); | |
loc.forEach((x)=>{ | |
if(!x)return; | |
root.appendChild(createListItem(x)) | |
}) | |
return root; | |
} | |
function createListItem(x){ | |
const li = document.createElement('li') | |
li.classList.add('py-1'); | |
li.innerText = x.name | |
const selectEvent = function(event){ | |
event.stopPropagation(); //parent elements will not have the same event | |
const li = event.target | |
clearDropdown(); | |
searchBox.value = x.name; | |
}; | |
li.addEventListener('click', selectEvent) | |
li.addEventListener('touchstart', selectEvent) | |
return li | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment