Using Twitter Typeahead.js Custom Event Triggers

By Eric on October 29, 2013

Since Bootstrap dropped support for their typeahead they have since told people to use Twitter's typeahead.js.  It has a lot of great features that I have covered in an older write up about Twitter Typeahead.js.  In this post I wanted to go over the custom events that are triggered and how you can use them to get more out of Twitter Typehead. There are five triggers in the typeahead.js and you can tap into each of these to do what you'd like when these events are triggered.  Below are those events and when they are triggered. All of that information comes directly from the typeahead README.  Now that we know what the events are and when they are triggered we can make custom events that happen by using jQuery and tapping into those events using .on().  Say, for example, I wanted to update a title on a page including the input field that typeahead already does.  You could make an on change event that would listen on that input for a change and then alter the title but in our case we can simplify that by tapping into the typeahead:selected event.
$('.typeahead')
    .typeahead(/* pass in your datasets and initialize the typeahead */)
    .on('typeahead:selected', function($e, datum){
        $("#title").html(datum["value"]);
        }
    );
Now instead of a second listener on your input object you can just have Twitter Typeahead listen for you and make changes where you need.  Play around with the different variations of the events to help you get the most out of Twitter Typeahead.  There is an issue on their GitHub page that explains how to use the custom events and gives a very basic example.  Below is the example and here is the link to Getting a custom event to fire.
$('.typeahead')
    .typeahead(/* pass in your datasets and initialize the typeahead */)
    .on('typeahead:opened', onOpened)
    .on('typeahead:selected', onAutocompleted)
    .on('typeahead:autocompleted', onSelected);

function onOpened($e) {
    console.log('opened');
}

function onAutocompleted($e, datum) {
    console.log('autocompleted');
    console.log(datum);
}

function onSelected($e, datum) {
    console.log('selected');
    console.log(datum);
}
Hope that helps someone as it took me a bit of digging to find the easiest way to use those triggers.  Comment below on other useful ways you've used Twitter Typeahead and the custom event triggers.