Blame | Last modification | View Log | RSS feed
jQuery#typeahead----------------The UI component of typeahead.js is a available as a jQuery plugin. It'sresponsible for rendering suggestions and handling DOM interactions.Table of Contents-----------------* [Features](#features)* [Specification](#specification)* [Usage](#usage)* [API](#api)* [Options](#options)* [Datasets](#datasets)* [Custom Events](#custom-events)* [Look and Feel](#look-and-feel)* [Bloodhound Integration](#bloodhound-integration)Features--------* Displays suggestions to end-users as they type* Shows top suggestion as a hint (i.e. background text)* Supports custom templates to allow for UI flexibility* Works well with RTL languages and input method editors* Highlights query matches within the suggestion* Triggers custom eventsSpecification-------------In an effort to take advantage of the pre-existing knowledge of typeahead.jsusers, the behavior of the typeahead.js UI is modeled after google.com's searchbox. Below is pseudocode that details how the UI reacts to pertinent events.**Input Control Gains Focus**```activate typeahead```**Input Control Loses Focus**```deactivate typeaheadclose dropdown menuremove hintclear suggestions from dropdown menu```**Value of the Input Control Changes**```IF query satisfies minLength requirement THENrequest suggestions for new queryIF suggestions are available THENrender suggestions in dropdown menuopen dropdown menuupdate hintELSEclose dropdown menuclear suggestions from dropdown menuremove hintENDIFELSEclose dropdown menuclear suggestions from dropdown menuremove hintENDIF```**Up Arrow is Keyed**```IF dropdown menu is open THENmove dropdown menu cursor up 1 suggestionELSErequest suggestions for current queryIF suggestions are available THENrender suggestions in dropdown menuopen dropdown menuupdate hintENDIFENDIF```**Down Arrow is Keyed**```IF dropdown menu is open THENmove dropdown menu cursor down 1 suggestionELSErequest suggestions for current queryIF suggestions are available THENrender suggestions in dropdown menuopen dropdown menuupdate hintENDIFENDIF```**Left Arrow is Keyed**```IF detected query language direction is right-to-left THENIF hint is being shown THENIF text cursor is at end of query THENautocomplete query to hintENDIFENDIFENDIF```**Right Arrow is Keyed**```IF detected query language direction is left-to-right THENIF hint is being shown THENIF text cursor is at the end of the query THENautocomplete query to hintENDIFENDIFENDIF```**Tab is Keyed**```IF dropdown menu cursor is on suggestion THENclose dropdown menuupdate query to display key of suggestionremove hintELSIF hint is being shown THENautocomplete query to hintENDIF```**Enter is Keyed**```IF dropdown menu cursor is on suggestion THENclose dropdown menuupdate query to display key of suggestionremove hintprevent default browser action e.g. form submitENDIF```**Esc is Keyed**```close dropdown menuremove hint```**Suggestion is Clicked**```update query to display key of suggestionclose dropdown menuremove hint```Usage-----### API#### jQuery#typeahead(options, [\*datasets])Turns any `input[type="text"]` element into a typeahead. `options` is anoptions hash that's used to configure the typeahead to your liking. Refer to[Options](#options) for more info regarding the available configs. Subsequentarguments (`*datasets`), are individual option hashes for datasets. For moredetails regarding datasets, refer to [Datasets](#datasets).```javascript$('.typeahead').typeahead({minLength: 3,highlight: true,},{name: 'my-dataset',source: mySource});```#### jQuery#typeahead('destroy')Removes typeahead functionality and reverts the `input` element back to itsoriginal state.```javascript$('.typeahead').typeahead('destroy');```#### jQuery#typeahead('open')Opens the dropdown menu of typeahead. Note that being open does not mean thatthe menu is visible. The menu is only visible when it is open and has content.```javascript$('.typeahead').typeahead('open');```#### jQuery#typeahead('close')Closes the dropdown menu of typeahead.```javascript$('.typeahead').typeahead('close');```#### jQuery#typeahead('val')Returns the current value of the typeahead. The value is the text the user hasentered into the `input` element.```javascriptvar myVal = $('.typeahead').typeahead('val');```#### jQuery#typeahead('val', val)Sets the value of the typeahead. This should be used in place of `jQuery#val`.```javascript$('.typeahead').typeahead('val', myVal);```#### jQuery.fn.typeahead.noConflict()Returns a reference to the typeahead plugin and reverts `jQuery.fn.typeahead`to its previous value. Can be used to avoid naming collisions.```javascriptvar typeahead = jQuery.fn.typeahead.noConflict();jQuery.fn._typeahead = typeahead;```### OptionsWhen initializing a typeahead, there are a number of options you can configure.* `highlight` – If `true`, when suggestions are rendered, pattern matchesfor the current query in text nodes will be wrapped in a `strong` element with`tt-highlight` class. Defaults to `false`.* `hint` – If `false`, the typeahead will not show a hint. Defaults to `true`.* `minLength` – The minimum character length needed before suggestions startgetting rendered. Defaults to `1`.### DatasetsA typeahead is composed of one or more datasets. When an end-user modifies thevalue of a typeahead, each dataset will attempt to render suggestions for thenew value.For most use cases, one dataset should suffice. It's only in the scenario whereyou want rendered suggestions to be grouped in the dropdown menu based on somesort of categorical relationship that you'd need to use multiple datasets. Forexample, on twitter.com, the search typeahead groups results into recentsearches, trends, and accounts – that would be a great use case for usingmultiple datasets.Datasets can be configured using the following options.* `source` – The backing data source for suggestions. Expected to be a functionwith the signature `(query, cb)`. It is expected that the function willcompute the suggestion set (i.e. an array of JavaScript objects) for `query`and then invoke `cb` with said set. `cb` can be invoked synchronously orasynchronously. A Bloodhound suggestion engine can be used here, to learnhow, see [Bloodhound Integration](#bloodhound-integration). **Required**.* `name` – The name of the dataset. This will be appended to `tt-dataset-` toform the class name of the containing DOM element. Must only consist ofunderscores, dashes, letters (`a-z`), and numbers. Defaults to a randomnumber.* `displayKey` – For a given suggestion object, determines the stringrepresentation of it. This will be used when setting the value of the inputcontrol after a suggestion is selected. Can be either a key string or afunction that transforms a suggestion object into a string. Defaults to`value`.* `templates` – A hash of templates to be used when rendering the dataset. Notea precompiled template is a function that takes a JavaScript object as itsfirst argument and returns a HTML string.* `empty` – Rendered when `0` suggestions are available for the given query.Can be either a HTML string or a precompiled template. If it's a precompiledtemplate, the passed in context will contain `query`.* `footer`– Rendered at the bottom of the dataset. Can be either a HTMLstring or a precompiled template. If it's a precompiled template, the passedin context will contain `query` and `isEmpty`.* `header` – Rendered at the top of the dataset. Can be either a HTML stringor a precompiled template. If it's a precompiled template, the passed incontext will contain `query` and `isEmpty`.* `suggestion` – Used to render a single suggestion. If set, this has to be aprecompiled template. The associated suggestion object will serve as thecontext. Defaults to the value of `displayKey` wrapped in a `p` tag i.e.`<p>{{value}}</p>`.### Custom EventsThe typeahead component triggers the following custom events.* `typeahead:opened` – Triggered when the dropdown menu of a typeahead isopened.* `typeahead:closed` – Triggered when the dropdown menu of a typeahead isclosed.* `typeahead:cursorchanged` – Triggered when the dropdown menu cursor is movedto a different suggestion. The event handler will be invoked with 3arguments: the jQuery event object, the suggestion object, and the name ofthe dataset the suggestion belongs to.* `typeahead:selected` – Triggered when a suggestion from the dropdown menu isselected. The event handler will be invoked with 3 arguments: the jQueryevent object, the suggestion object, and the name of the dataset thesuggestion belongs to.* `typeahead:autocompleted` – Triggered when the query is autocompleted.Autocompleted means the query was changed to the hint. The event handler willbe invoked with 3 arguments: the jQuery event object, the suggestion object,and the name of the dataset the suggestion belongs to.All custom events are triggered on the element initialized as a typeahead.### Look and FeelBelow is a faux mustache template describing the DOM structure of a typeaheaddropdown menu. Keep in mind that `header`, `footer`, `suggestion`, and `empty`come from the provided templates detailed [here](#datasets).```html<span class="tt-dropdown-menu">{{#datasets}}<div class="tt-dataset-{{name}}">{{{header}}}<span class="tt-suggestions">{{#suggestions}}<div class="tt-suggestion">{{{suggestion}}}</div>{{/suggestions}}{{^suggestions}}{{{empty}}}{{/suggestions}}</span>{{{footer}}}</div>{{/datasets}}</span>```When an end-user mouses or keys over a `.tt-suggestion`, the class `tt-cursor`will be added to it. You can use this class as a hook for styling the "undercursor" state of suggestions.Bloodhound Integration----------------------Because datasets expect their `source` to be a function, you cannot directlypass a Bloodhound suggestion engine in as `source`. Rather, you'll need topass the suggestion engine's typeahead adapter:```javascriptvar engine = new Bloodhound({ /* options */ });engine.initialize();$('.typeahead').typeahead(null, {source: engine.ttAdapter()});```