Monday, October 21, 2013

Icons in jQuery UI Autocomplete Items

Adding custom display data to jQuery UI autocomplete items is easy. All we need is a basic CSS class with some custom properties, and the willingness to override the default implementation of the _renderItem() method. It's one thing to include some meta data about each item in the autocomplete drop-down. It's much more interesting, I think, when you display icons beside each item. Ready?

The idea of this extension is that we want the autocomplete widget to understand some additional icon data we pass into the data source. Imagine, each object in the source array had a logo property, pointing to an icon URL. When the drop-down menu renders, we want the items with logo data to display those icons to the left of the text.

Logos are almost always a good idea to display for the user when feasible — instant recognition. User's expect this capability now, so where it makes sense, why not use it? Here's the code that illustrates how to extend the accordion widget.

The only changes we need to make to the menu item involve CSS properties — no structural DOM manipulation. We can get the menu item by calling the _super() method. This just calls the original implementation of _renderItem(), which creates the menu item and inserts it into the DOM. But before we return the menu item in our implementation of the method, we first check to see if the item data has a logo URL. If so, it's a simple CSS property change for background-image. We then add the ui-menu-item-logo class which holds all the static CSS properties for men items with logos.

No comments :

Post a Comment