Mar25


Auto Suggest with Typeahead image

Many times, you might have seen on various social networking sites like Twitter where you type some characters of a user name (or handle) into their search bar and you get an auto-suggesting drop-down list of users, related to your query. Not only in social networking sites, these auto-suggesting dropdown are versatilely used in various websites as their search bars.

The purest example of this is our website:
 
myPHPnotes Search Bar
Search bar with Autosuggest

 

Auto-suggesting is one of the most important ways to enhance the user interaction.

How to integrate dropdown autosuggest

 For integrating a drop-down autosuggest, we will use Twitter's Typeahead javascript library. 

There are two main parts of this integration

  1. A source where we perform AJAX requests to fetch JSON type results.
  2. Sorting these results according to the query.
 

Fetching data through AJAX

 var results = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('username'),
queryTokenizer: Bloodhound.tokenizers.whitespace,

remote: {
url: '/search?query={query}',
wildcard: '{query}'
}

});
results.initialize();

Setting up Typeahead


$('#search').typeahead(
{
hint: true,
highlight: true,
minLength:2,
maxItem: 5,


},
{
name: 'user',
displayKey: 'username',
source: results.ttAdapter(),

templates: {
empty: function() { return [
'<p class="tt-suggestion-link center tt-notfound" >',
'Nothing Found.',
'</p>'
].join('\n')}
,
suggestion: function(posts){
var string = '<a class="tt-suggestion-link" href="/user/' + user.username+ '">' + user.username + '</a>';

return string;
}
}


}
);
//typeahead end

For complete reference, go through the video provided below.


|0 |67

Ads By Google - Turn it Off

jQuery and Typeahead Library

CSS for styling dropdown

Twitter Typeahead Homepage

Ads By Google - Turn it Off

Leave a Comment


gfhdg