Meet Meet - 7 months ago 12
Javascript Question

JqueryUI Autocomplete item focus does not work using arrow keys

In my jQuery Autocomplete widget, for some reason, the list items are selected properly using mouse and the mouse hover event also works to apply the CSS and change item background appropriately. But when using arrow keys to navigate the Autocomplete list the item is not focused. It does do the default action and populates the input box with the value of the item (I have prevented this default action so as to not populate the input box) But the item is not focused (see screenshot).

CSS:

.ui-menu-item:hover{
cursor: pointer;
background: #D6DFF2;
}


Javascript:

$.widget("ui.autocomplete", $.ui.autocomplete, {
options: {
maxItems: 2
},
_renderMenu: function (ul, items) {
var that = this,
count = 0;
$.each(items, function (index, item) {
if (count < that.options.maxItems) {
that._renderItemData(ul, item);
}
count++;
});
}
});

var initializeAutoComplete = function () {
$('#example-links').autocomplete({
source: $('#hidden-action-autoComplete').val(),
maxItems: 10,
delay: 750,
minLength :1,
select: function (event, ui) {
event.preventDefault();
$(this).val(ui.item.label);
window.location = '/path/to/be/shown/' + ui.item.value;
},
focus: function (event, ui) {
event.preventDefault();
$('.ui-autocomplete > li').attr('title', ui.item.label + '(' + ui.item.value + ')');
}

});
}


In the screenshot, I have pressed down arrow key 3 times and currently the third item should have been focused, but it's not.

Autocomplete not focussed

Answer

By default, Autocomplete uses the following CSS to highlight the active element:

.ui-state-hover, .ui-widget-content .ui-state-hover, .ui-widget-header .ui-state-hover, .ui-state-focus, .ui-widget-content .ui-state-focus, .ui-widget-header .ui-state-focus {
    border: 1px solid #999999;
    background: #dadada url("images/ui-bg_glass_75_dadada_1x400.png") 50% 50% repeat-x;
    font-weight: normal;
    color: #212121;
}

Try adding all those classes to your own CSS. In your case:

.ui-state-hover, .ui-widget-content .ui-state-hover, .ui-widget-header .ui-state-hover, .ui-state-focus, .ui-widget-content .ui-state-focus, .ui-widget-header .ui-state-focus {
    cursor: pointer;
    background: #D6DFF2;
}