We need 2 elements for this to work:
The first part of the code sets a few constants on the page:
// Collection List Wrapper
const listWrap = document.getElementById('listWrap');
// Collection List
const list = document.getElementById('autoCompleteList');
// Search Input Field
const searchBar = document.getElementById('searchBar');
Next we have a 'keyup' event listener. This part 'listens' to any key pressed inside the search bar and filters through the items lists. It changes the css of each item (display:block or display:none) according to the term typed.
searchBar.addEventListener('keyup', function(e){
const term = e.target.value.toLowerCase();
// All the elements that will be searchable (can be the item, or a div inside each item)
const searchItems = list.getElementsByClassName('list-item');
Array.from(searchItems).forEach(function(item){
const text = item.firstElementChild.textContent;
if(text.toLowerCase().indexOf(term)!=-1){
item.style.display = 'block';
}
else {
item.style.display = 'none';
}
})
})
The last part is the interaction that opens and closes the list when the focus is on the search bar.
Put all those 3 code snippets together at the custom code section of your page under the Before </body> tag.
// Open list when search bar is focused
searchBar.addEventListener('focusin', (event) => {
listWrap.style.maxHeight = "400px";
});
// Close list when search bar is focused
searchBar.addEventListener('focusout', (event) => {
listWrap.style.maxHeight = "0";
});
When your bath soap bar gets too small to use, don't throw it away! open the next bar, and when you finish showering, stick the small old bar to the back of the new bar. Onces they both dry, they will become one.