Icons in jQuery UI Autocomplete Items
Extending the jQuery UI autocomplete widget to render icons for each item.
HTML
<div id="lib-label">Lib:</div>
<input id="lib"/>
CSS
/*
* Common CSS properties for any menu item with a logo.
*
*/
.ui-menu .ui-menu-item .ui-menu-item-icon {
background-repeat: no-repeat;
background-position: 2px, 0;
background-size: 40px;
padding-left: 45px;
font-size:40px;
}
JavaScript
(function( $ ) {
// Extend the autocomplete widget, using our own application namespace.
$.widget( "app.autocomplete", $.ui.autocomplete, {
// The _renderItem() method is responsible for rendering each
// menu item in the autocomplete menu.
_renderItem: function( ul, item ) {
// We want the rendered menu item generated by the default implementation.
var result = this._super( ul, item );
// If there is logo data, add our custom CSS class, and the specific
// logo URL.
if ( item.logo ) {
result.find( "a" )
.addClass( "ui-menu-item-icon" )
.css( "background-image", "url(" + item.logo + ")" );
}
return result;
}
});
})( jQuery );
$(function() {
// Build our autocomplete widget using a source array. Notice that each object
// in the array has a "logo" property? We can add any properties we want here.
$( "#lib" ).autocomplete({
source: [
{
label: "jQuery",
logo: "http://jquery.com/favicon.ico",
},
{
label: "jQuery UI",
logo: "http://jqueryui.com/favicon.ico"
},
{
label: "Backbone",
logo: "http://backbonejs.org/docs/images/favicon.ico"
},
{
label: "Lodash",
logo: "http://lodash.com/favicon.ico"
}
]
});
});