I have a simple input like that
<input id="name-srch" type="text" data-type="string">
And my js (simplified)
$('#name-srch').autocomplete({
source: function (request, response) {
$.ajax({
url: ...,
data: ...,
success: function (data) {
// note that 'data' is the list of elements to display
response(data)
}
});
},
select: function (event, ui) {
// do some stuff
return false
},
focus: function (event, ui) {
console.log(ui.item.Name) // just to see if the focus event is triggered, and it is
return false
}
})
.autocomplete("instance")._renderItem = function (ul, item) {
return $("<li>")
.append("<a>" + item.Name + "</a>")
.appendTo(ul);
};
JQuery Autocomplete fill the <ul>
with the <li>s
as it should and triggers a focus event on mouseover or down/up arrow key as it should.
The problem is that I want to apply a particular style to the focused item, so in my CSS I have something like that
.ui-state-focus {
background-color: red;
font-weight: bold;
}
There is my problem, the focused item never takes the ui-state-focus
class and therefore it never takes the defined style.
What am I doing wrong :( ?
EDIT : I already tried to add in my CSS something like
.ui-menu-item:hover {
background-color: red;
font-weight: bold;
}
Indeed it does the trick for the hover, but not for the focus via down/up arrow key. Moreover, I don't really like it, I would prefer to make it work the way it's meant to if I can...
I managed to make it work.
For some reason JQuery Autocomplete doesn't apply the ui-state-focus
on the focused <li>
but does apply the ui-state-active
class on the <a>
inside the focused <li>
. Therefore I can apply the wanted style via
.ui-state-active {
background-color: red;
font-weight: bold;
}
I still have no idea why it applies a class only on the <a>
inside and not on the <li>
as describe on all the documentations but hey, it works...
try this selector:
.ui-menu .ui-menu-item:hover, .ui-state-hover, .ui-widget-content .ui-state-hover, .ui-state-focus, .ui-widget-content .ui-state-focus {
background-color: red;
font-weight: bold;
}
There is a JSFIDDLE from another question that I've answered. Just check the last line in the CSS definition:
https://jsfiddle.net/g4bvs0we/5/
Update: I've updated the source code and jsfiddle link. I guess there were issue with CSS rule priority and putting more specific rule should help.
Can you please let me know if this works?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With