Using Twitter's typeahead.js

Sep 17, 2013

I decided to try out Twitter’s typeahead.js the other day. It was bit confusing at first because I kept finding examples and tutorials that weren’t working. Turns out that typeahead used to be part of Bootstrap, but it was removed in version 3.0 to become its own standalone project. So if you’re looking for documentation on typeahead.js, just be sure that you know which project it’s talking about (the old component under Bootstrap, or the new standalone project), because the implementation is completely different.

Example

The standalone version of typeahead.js is more powerful and flexible. Here’s a quick example of how you can use it:

This example uses a local data source and illustrates how to use a simple template with hogan.js. It also uses one of the custom events provided by the API to run a callback function when an item is selected from the list. In this case we’re simply grabbing the URL of that item and pointing the browser there. Looks like this:

Shows suggestions as you type

Arrow down to choose one

If you saved any custom properties in your datum objects, you can access them later in the template and the callback function. In both cases the datum object is passed as an argument. In the template use the double mustache notation: {{my-property}}. In the callback function just use standard object notation: datum.my-property.

Resources

Download a copy of the script or link to it somewhere. You’ll also need a copy of the CSS file, unless you want to style it from scratch. If you plan to use a custom template for your typeahead suggestions, then you’ll also need a template engine. Twitter has an open-source one called hogan.js that’s pretty easy to use. See the examples page for a sample of how you can use a custom template.