Change background color of jQuery autocomplete item based on state (using CSS)

Chad Decker picture Chad Decker · Feb 21, 2013 · Viewed 43.5k times · Source

The goal is to create a JQuery autocomplete element whose list items have a blue background when they're hovered over or focused via the keyboard. The Facebook search box pulls this off nicely.

Each <li> element contains custom HTML wrapped in an <a>. Each of those <a> tags belongs to the class sbiAnchor. Generating the blue background on hover can be done successfully using the following CSS:

.ui-autocomplete a.ui-corner-all.sbiAnchor:hover{
    background: blue;
}

But how does one apply that same blue background when the user keys up/down the autocomplete list. Changing the CSS code to the following does NOT work:

.ui-autocomplete a.ui-corner-all.sbiAnchor:hover, .ui-autocomplete .ui-state-focus a.ui-corner-all.sbiAnchor{
    background: blue;
}

What's the correct approach here? Keep in mind that this blue background effect should only apply to one specific autocomplete on my page (several of them exist). That's why I'm using sbiAnchor to differentiate its items from those of the other autocomplete elements. The other autocompletes should retain their default behavior so the CSS selectors shouldn't be too broad.

Answer

Alejo JM picture Alejo JM · Oct 31, 2013

This work quite easy

body .ui-autocomplete {
  /* font-family to all */
}

body .ui-autocomplete .ui-menu-item .ui-corner-all {
   /* all <a> */
}

body .ui-autocomplete .ui-menu-item .ui-state-focus {
   /* selected <a> */
}