Reputation: 535
Is there any event available for clicking clear button only appears on html5 search input element?
Here is my attempt. But if i use "search", the event is also triggered by pressing enter.
i.e. if i press enter, console prints out search clear
mySearchBar.addEventListener("keydown", (e) => {
if (e.keyCode === ENTER_KEY_CODE) {
console.log("search");
//Display search results
}
});
mySearchBar.addEventListener("search", () => {
console.log("clear");
// Click the cross button of input type=search to Clear the search results and display all
});
};
Upvotes: 0
Views: 1136
Reputation: 1002
You can use eventListener 'input'
to check if input is empty each time something append to input, then if no value that mean the search input was cleared.
EDIT: Added value testing in keydown event
mySearchBar = document.getElementById('search');
mySearchBar.addEventListener("keydown", (e) => {
if (e.key === 'Enter') {
if (!e.currentTarget.value)
console.log('cleared');
else
console.log("search");
}
});
mySearchBar.addEventListener('input', (e) => {
if (!e.currentTarget.value)
console.log('cleared');
})
<input type=search id=search>
Upvotes: 2