I\'m working on a project with an autocomplete searchbox. Now I have the issue that I want to pass the value from the found autocompleteresults to the input box, but on the
My solution in the similar situation was using timeout to temporarily hold off the action taken in blur
event handler. Like this:
$('#search_field').focusout(function() {
window.setTimeout(function() { $('#a_c').hide() }, 100);
});
How about using
:hover
I solved same problem using it.
$('className').on('focusout', function(e) {
if($('.suggestLi' + ':hover').length) {
return;
}
$('.suggestList').empty();
});
The way I solved this was using the mousedown
event instead of click
. The mousedown
event is always triggered before the focusout
event while click
is not.
You can try it out in the little demo below. Focus on the field and then click on the button.
const field = document.getElementById('field');
const btn = document.getElementById('btn');
btn.addEventListener('click', () => console.log('Click'));
btn.addEventListener('mousedown', () => console.log('Mouse down'));
field.addEventListener('focusout', () => console.log('Focus out'));
<input id="field">
<button id="btn">Try it</button>
As you can see the output is in the following order:
This is the most stable solution without using any workaround hacks like timeouts. It also does not depend on jQuery. The only thing worth noting that mousedown
does not wait for the user to release their mouse button, but in terms of user experience that is not really a concern here.