user3796786
user3796786

Reputation: 209

missing click event because blur event hiddes element

I'm implementing a "auto suggestion feature". This means:

But if the user want to select an option via mouse, the click event is not firing because the blur event fires earlier and hides the clickable element.

Here is the fiddle: http://jsfiddle.net/km8c0ft1/

Here is some example code: js:

$('#test').blur(function() {
    $('#dropdown').css("display", "none");
});
$('#test').focus(function() {
    $('#dropdown').css("display", "inline");
});

html:

<input id="test" />
<input />
<input />

<ul id="dropdown" style="display: none">
    <li><a onclick="alert('option 1 selected')">option 1</a></li>
    <li><a onclick="alert('option 2 selected')">option 2</a></li>
    <li><a onclick="alert('option 3 selected')">option 3</a></li>
</ul>

I understand the problem. But what is the best practice to solve this Problem? I can implement the setTimeout Function to wait some ms until i hide the menu. But this feels like a hack and not like a clean solution.

Upvotes: 4

Views: 1050

Answers (1)

Bhushan Kawadkar
Bhushan Kawadkar

Reputation: 28513

Try this : You can use show() or hide() instead of changing css values. Bind click event for anchor inside li to set selected value to text box. Bind click event for document and check if target is not input box to hide options.

$('#dropdown li a').click(function(e) {
    $('#test').val($(this).text());
    $('#dropdown').hide();
});

$(document).on("focus click keydown blur","*",function(e){
    var keyCode = e.keyCode || e.which; 
    if(keyCode == 9 || e.target.id!='test')
    $('#dropdown').hide();
});

$('#test').on("focus click",function(e) {
    $('#dropdown').show();
});

DEMO with Single Input
DEMO with Multiple Input

Upvotes: 4

Related Questions