Customize JQuery Autocomplete
A few month ago I wrote a post about “Search Facebook Friends With Jquery Autocomplete”. The problem that after a while it become not relevant due to the changes in the jquery autocomplete API. Due to many requests that I got (in comments,emails, facebook, twitter) I decided to update it. So here we go...
Before I start I have to admit that I don’t like the new API it is too hacky to make a custom autocomplete and it is not documented!.
Before we implements "Search Facebook Friends With jQuery" we need to look at the jQuery autocomplete source code, https://github.com/jquery/jquery-ui/blob/master/ui/jquery.ui.autocomplete.js#L507. The method that render the UI for the autocomplete is called _renderItem
_renderItem: function( ul, item ) {
return $( "<li>" )
.append( $( "<a>" ).text( item.label ) )
.appendTo( ul );
}
Ho snap there is a problem it is private... But don’t worry it seems that there is a “normal” way to override it (again not documented)
in order to override autocomplete internal methods you need to write the code:
.data( "autocomplete" )._renderItem = function( ul, item ) {//write your code here }
So now that we know what to do we can make our own facebook autocomplete
*in my example the input textbox is <input id="autocomplete-input" />
First we need to create an auto complete - you can find many examples of how to do it in the official jQuery Autocomplete site http://jqueryui.com/demos/autocomplete/
Now we need to render the facebook friends URL https://graph.facebook.com/me/friends?access_token={YOUR_ACCESS_TOKEN}&callback=?
You can read more about it here: http://graph.facebook.com/ (you will even get your access token there)
we almost done... we need to override the _renderItem method
$("#autocomplete-input").data("autocomplete")._renderItem = function( ul, item ) {
var image_url = "http://graph.facebook.com/" + item.value +"/picture";
return $( "<li>" ).append($("<img style='float:left'>").attr('src',image_url))
.append( $( "<a>" ).text( item.label ) )
.appendTo( ul );
}
we also need to make sure that we build the item that we get from facebook
success: function( data ) {
res = $.map( data.data, function( item ) {
if (item.name.toLowerCase().indexOf(request.term.toLowerCase()) >= 0){
return {
label: item.name,
value: item.id
}
}
});
response(res);
}
Here is a full example: (just add the jQuery , jQuery UI src file)
https://gist.github.com/2907134
*Note that you can optimize this sample by using “remote with cache” http://jqueryui.com/demos/autocomplete/#remote-with-cache or pre load the data
Good luck
Keep Writing, Compiling, and Debugging
Alon Nativ