Top

Usage

A type ahead (also known as an autocomplete) attempts to predict and suggest a list of items based on the current input from a user. The data used to generate suggestions can be packaged in multiple ways, as well as be sorted and grouped.

A type ahead component must be initialized on an input field, so that key press events can be monitored.

<input type="text" id="input" class="input" name="term">
$('#input').typeAhead();
A data source must be defined to query against. Continue reading for more information on data sources.

Data Source

There are 3 ways to retrieve data for the lookup system. The first is through a literal array, which will be used as the data.

$('#input').typeAhead({
    source: [
        { title: 'Finn', description: 'Hero' },
        { title: 'Jake' },
        { title: 'Princess Bubblegum' }
    ]
});

The second is through a function, which should return an array of data.

$('#input').typeAhead({
    source: function() {
        return [
            ...
        ];
    }
});

The third is through a string, which should point to a URL to query against. This URL will be requested on every lookup unless prefetch is enabled. More information on pre-fetching can be found in the next chapter.

$('#input').typeAhead({
    source: '/api/search'
});
When using the remote HTTP request approach, we suggest that sorting, matching, and filtering be done on the remote end, and sorter and matcher be set to false on the front end.

Category Grouping

Items can be grouped and rendered into categories by defining the category field in the data set.

return [
   { title: 'Finn', category: 'Adventurer', description: 'Hero' },
   { title: 'Jake', category: 'Adventurer' },
   { title: 'Princess Bubblegum', category: 'Princess' },
   { title: 'Lumpy Space Princess', category: 'Princess' },
]

Data Structure

The following fields are available for each item in the data set. Custom fields can also be defined and used within builder callbacks, and when an item is selected.

Field Type Default Description
title string The title for the item within the menu.
description string An optional description for the item.
category string An optional category to group items.

Prefetching

When prefetch is enabled, data will be fetched and processed on initialization, which will prevent additional HTTP requests for every lookup. Fetching will use the source option as the URL to request, and the JSON response as the data.

$('#input').typeAhead({
    source: '/api/data',
    prefetch: true
});

Shadow Text

The shadow text feature will display the title behind the input field, for the first item in the data set if it matches the current term. For a better understanding of how this works, take a look at Google search.

$('#input').typeAhead({
    shadow: true
});

When enabled, the input markup will be changed to the following.

<div class="type-ahead-shadow">
    <!-- The shadow input -->
    <input type="text" class="input is-shadow" readonly>
    <!-- The original input -->
    <input type="text" id="input" class="input not-shadow">
</div>

Sorters, Matchers & Builders

Custom sorter, matcher, and builder functions can be defined to modify and hook into the type ahead process. If no function is defined, it will fall back to the class implementation.

The sorter receives an array of items, and should return the array sorted.

function sort(items) {
    return items.sort();
}

The matcher receives an item title and the current term, and should return a boolean if a match is found.

function match(item, term) {
    return (item.title.indexOf(term) >= 0);
}

The builder receives an item object, and should return an element to render in the dropdown menu.

function build(item) {
    return $('<a/>', {
        href: 'javascript:;',
        html: this.highlight(item.title)
    });
}

Once our functions are defined, we pass them through the constructor.

$('#input').typeAhead({
    sorter: sort,
    matcher: match,
    builder: build
});
The "this" context for all callbacks point to the type ahead instance.
If false is defined for an option, no callback or fallback will be used. This is useful for data sets that are processed remotely.

Notes

  • The currently selected item in the list will have an .is-active class on the parent li.
Top

ARIA

The combobox, listbox, and option roles, and the appropriate aria-* attributes are required when supporting ARIA.

<input type="text" id="input" class="input" name="term" role="combobox" aria-autocomplete="off">

<div class="type-ahead" role="listbox">
    <ul>
        <li><a href="javascript:;" role="option">Item</a></li>
    </ul>
</div>
The JavaScript component will automatically map all ARIA attributes.
Top

Variables

Variable Default Description
$typeAhead-class .type-ahead CSS class name for the type ahead wrapper.
$typeAhead-class-description .type-ahead-desc CSS class name for the type ahead item description element.
$typeAhead-class-highlight .type-ahead-highlight CSS class name for the highlighted term in the type ahead list.
$typeAhead-class-heading .type-ahead-heading CSS class name for the type ahead heading element.
$typeAhead-class-shadow .type-ahead-shadow CSS class name for the type ahead shadow text wrapper.
$typeAhead-transition .3s The transition time for all type ahead animations.
$typeAhead-zindex 500 The z-index for the type ahead element.
Top

Options

Inherits all options from the parent Component.

Option Type Default Description
builder function The function to use for building menu items. Will fallback to build().
descTemplate string <span class="type-ahead-desc"></span> The list item description markup.
headingTemplate string <li class="type-ahead-heading"></li> The heading markup for list items.
highlightTemplate string <mark class="type-ahead-highlight"></mark> The highlighted term markup.
itemLimit int 15 The max number of items to display in the type ahead drop down menu.
matcher function The function to use for matching results against the keyword. Will fallback to match().
minLength int 1 The minimum character count to trigger a lookup.
prefetch bool false Whether to prefetch all data from source on initialization, instead of querying each lookup.
query object An object of key value pairs to include in the query string for AJAX requests.
shadow bool false Whether to render shadow text below the input field for the 1st matching item in the menu.
shadowTemplate string <div class="type-ahead-shadow"></div> The shadow input wrapping markup.
sorter function The function to use for sorting results. Will fallback to sort().
source array|string|function The source data to match and sort against. Learn more about this option in the data source chapter.
template string <div class="type-ahead"></div> The type ahead drop menu markup.
titleTemplate string <span class="type-ahead-title"></span> The list item title markup.
throttle int 250 The time in milliseconds to throttle lookup events.
Top

Events

Inherits all events from the parent Component.

Event Arguments Description
cycle object:item, int:index Triggered when cycling through the menu items using keyboard events.
select object:item, int:index Triggered when an item is selected within the menu.
reset Triggered when the type ahead is reset, either when the keyword is cleared, or nothing is selected.
Top

Properties

Inherits all properties from the parent Component.

Property Type Description
cache object A cache of lookups indexed by the term used to query with.
index int The current item index when cycling with keyboard events.
input element The input element to monitor keyup events on. Is the input passed through the constructor.
items array The list of data returned from source. This data will be sorted and matched against.
shadow element The shadow text input element when shadow is enabled.
term string The keyword from input to query with.
wrapper element The element that wraps the inputs when shadow is enabled.
Top

Methods

Inherits all methods from the parent Component.

Method Description
build(object:item) Build the anchor link that will be rendered in the drop down menu. By default, will create an a tag with the title and description wrapped in spans.
highlight(string:title) Highlight all occurrences of the term found within the item title.
lookup(string:term) Trigger a lookup within the data source using the defined term. Results will be set to items.
match(string:item, string:term) Return true if the item contains or matches the term. By default, will do a string indexOf() comparison.
rewind() Rewind the index and cycle pointer to the start.
sort(array:items) Sort the list of items before matching and processing. By default, will do an array sort() coupled with a string localeCompare().
source(array:data) Set the array of data as the list of items to query against. The data will be immediately sorted, matched, categorized, and processed.