Missing click event because element hudes blur event
I am implementing an auto suggestion feature. It means:
- input element gets focus -> display suggestions
- input element loses focus -> hides suggestions
But if the user wants to select an option with the mouse, the click event does not fire because the blur event fires earlier and hides the clickable element.
Here is a fiddle: http://jsfiddle.net/km8c0ft1/
Here's some sample 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 for solving this problem? I can implement a function setTimeout
to wait a few ms until I hide the menu. But this seems like a hack and not a clean solution.
source to share
Try this, you can use show()
or hide()
instead of changing the css values. Bind an anchor click event inside li
to set the selected value to the textbox. Bind a click event for the document and check if the input field is for hiding 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();
});
source to share