When i type something and then delete it the search bar remains open with no result, even if i click on something else in the same page, how can i make it to auto-close itself after i click somewere else on the screen?
SearchBx.onkeyup = (e)=>{
let userData = e.target.value;
let emptyArray = [];
if(userData){
emptyArray = suggestions.filter((data)=>{
return data.toLocaleLowerCase().startsWith(userData.toLocaleLowerCase());
});
emptyArray = emptyArray.map((data)=>{
return data = '<li>'+ data + '</li>';
});
console.log(emptyArray);
Main.classList.add("show");
}else{
}
showSuggestions(emptyArray);
let allList = AutoBox.querySelectorAll("li");
// for (let i = 0; i < allList.length; i++) {
// allList[i].setAttribute("onclick", "select(this)");
// }
for(const el of allList){ // use for..of instead of indexed for
el.addEventListener('click', (e) => { // attach an event listener instead of using the onclick attribute
SearchBx.value = e.target.textContent; // can be a separate function like 'select', but whatever
ouvrirPage(); // trigger page opening from click event
});
}
}
// function select(element){
// let selectUserData = element.textContent;
// SearchBx.value = selectUserData;
// }
function showSuggestions(list){
let listData;
if(!list.length){
userValue = SearchBx.value;
listData = '<li>'+ userValue +'</li>'
}else{
listData = list.join('');
}
AutoBox.innerHTML = listData;
}