Using Twitter Typeahead.js Custom Event Triggers
-
typeahead:initialized– Triggered after initialization. If data needs to be prefetched, this event will not be triggered until after the prefetched data is processed. -
typeahead:opened– Triggered when the dropdown menu of a typeahead is opened. -
typeahead:closed– Triggered when the dropdown menu of a typeahead is closed. -
typeahead:selected– Triggered when a suggestion from the dropdown menu is explicitly selected. The datum for the selected suggestion is passed to the event handler as an argument in addition to the name of the dataset it originated from. Triggered when the user hits Tab to complete the text provided in the text box. See comments section below. -
typeahead:autocompleted– Triggered when the query is autocompleted. The datum used for autocompletion is passed to the event handler as an argument in addition to the name of the dataset it originated from. Triggered when the user clicks, or uses the arrow keys, to select an element from the drop down. See comments section below.
$('.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.
Comments
Join the discussionNo comments yet. Be the first to comment.




