jQuery: fire click() before blur() event
Solution 1
Listen to mousedown
instead of click
.
The mousedown
and blur
events occur one after another when you press the mouse button, but click
only occurs when you release it.
Solution 2
You can preventDefault()
in mousedown
to block the dropdown from stealing focus. The slight advantage is that the value will be selected when the mouse button is released, which is how native select components work. JSFiddle
$('input').on('focus', function() {
$('ul').show();
}).on('blur', function() {
$('ul').hide();
});
$('ul').on('mousedown', function(event) {
event.preventDefault();
}).on('click', 'li', function() {
$('input').val(this.textContent).blur();
});
$(document).on('blur', "#myinput", hideResult);
$(document).on('mousedown', "#myresults ul li", function(){
$(document).off('blur', "#myinput", hideResult); //unbind the handler before updating value
$("#myinput").val($(this).html()).blur(); //make sure it does not have focus anymore
hideResult();
$(document).on('blur', "#myinput", hideResult); //rebind the handler if needed
});
function hideResult() {
$("#myresults").hide();
}
FIDDLE