Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .focusout / .click conflict

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 same time, I want the autocompletebox to hide when the inputfield is not more focused.

Now I have a conflict going on with both of them since the click on the autocompletebox is seen as focusout and hide the box even before it can pass the value. Any pointers or workarounds for this kind of issue? Here a jsfiddle to make it more clear to you.

http://jsfiddle.net/KeGvM/

Or here

CSS:

#a_c {display:none;}​

JS:

$('#search_field').focusout(function() {
    $('#a_c').hide(); // IF I DELETE THIS IT WORKS
});

$('#search_field').focusin(function() {
    $('#a_c').show();
});

$('#a_c a').click(function() {
    $('#search_field').val('');
    var value = $(this).text();
    var input = $('#search_field');
    input.val(input.val() + value);
    $('#a_c').hide();
    return false;
});​

HTML:

<input autocomplete="off" onkeyup="searchFor(this.value);" name="search" id="search_field" class="bold" type="text" placeholder="Search...">
<div id="a_c"><a href="">hello world</a></div>​
like image 976
Johnny000 Avatar asked Dec 20 '12 21:12

Johnny000


3 Answers

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:

  1. Mouse down
  2. Focus out
  3. Click

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.

like image 117
Duncan Luk Avatar answered Nov 16 '22 14:11

Duncan Luk


How about using

:hover

I solved same problem using it.

$('className').on('focusout', function(e) {
    if($('.suggestLi' + ':hover').length) {
        return;
    }
    $('.suggestList').empty();
});
like image 41
keiwt Avatar answered Nov 16 '22 14:11

keiwt


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);
});
like image 32
raina77ow Avatar answered Nov 16 '22 16:11

raina77ow