'Search bar remains open with empty result
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;
}
Solution 1:[1]
Add one onblur event to your search bar and remove the .show class from the search-bar
something like the below:
SearchBx.onblur = () => {
Main.classList.remove('show');
}
Since the above solution closes the dropdown on selecting, here is another working solution -
Select your wrapper element and add an event to remove the show class when clicking on it.
let wrapper = document.querySelector('.wrapper');
wrapper.onclick = () => {
Main.classList.remove('show');
}
Solution 2:[2]
the solution to my problem was adding this
SearchBx.onclick = () => {
Main.classList.remove('show');
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | GGalusca |
