John Smith
John Smith

Reputation: 85

jQuery autocomplete focus one more time after hide

Does anybody know why after clicking outside the search field and hiding autocomplete results a focus activate one more time? See please at http://layot.prestatrend.com/ Type for example just 3 letters at search field 'ipo'. Thanks for any reply!

Upvotes: 0

Views: 562

Answers (2)

user470370
user470370

Reputation: 572

The only way I found: Destroy the autocomplete on focus event for re initializing it.

function defaultFocusAction(e, options) {
  if($(e.currentTarget).val() == '') {
    $(e.currentTarget).autocomplete('destroy');
    $(e.currentTarget).autocomplete(options);
  }
  $(e.currentTarget).trigger('keydown.autocomplete');
}
var options = {
  autoFocus : false,
  delay : 0,
  minLength: 0,
  source: ['foo', 'bar']
};
$('input.autocomplete').autocomplete(options).focus(function(e) {
  defaultFocusAction(e, options);
});

Upvotes: 0

Didier Ghys
Didier Ghys

Reputation: 30676

I guess it is just the behavior of the plugin to re-focus the input if the suggestion menu was visible.

When you click outside (or use TAB to unfocus) the input, the "blur" event is triggered:

.blur(function() {
    hasFocus = 0;
    if (!config.mouseDownOnSelect) {
        hideResults();
    }
})

Executing hideResults' executes another functionhideResultsNow` which makes this check:

var wasVisible = select.visible();
...
if (wasVisible)
    // position cursor at end of input field
    $.Autocompleter.Selection(input, input.value.length, input.value.length);

wasVisible is true because the suggestion menu is open.

The job of $.Autocompleter.Selection is to set the text selection in the input and at the end, it focuses the input:

$.Autocompleter.Selection = function(field, start, end) {
    if (field.createTextRange) {
        ...
    } else if (field.setSelectionRange) {
        ...
    } else {
        ...
    }
    field.focus();
};

If you click again outside the input, the variable wasVisible is false, because the suggestion menu is not open anymore, and the $.Autocompleter.Selection is not executed so the input is not re-focused.

Upvotes: 1

Related Questions