Full-featured Autocomplete Library For jQuery - Typeahead.js

File Size: 255 KB
Views Total: 15674
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   
Full-featured Autocomplete Library For jQuery - Typeahead.js

Just another jQuery typeahead plugin which provides fully customizable and AJAX-enabled autocomplete functionalities on input fields with flexible APIs.

Key features:

  • Cross browser.
  • Tons of customization options and callback functions.
  • Cross-domain JSONP supported.
  • Loading animations.
  • Search string highlighting.
  • Custom template.
  • Keyboard interactions.
  • Result group with dropdown filter support.
  • 'localStorage' or 'sessionStorage' caching support.
  • Sortable results.

Install it via package managers:

# NPM
$ npm install jquery-typeahead

# Bower
$ bower install jquery-typeahead

Basic usage:

1. First you need to load the following JavaScript and CSS files in your html document.

<link rel="stylesheet" href="jquery.typeahead.css">
<script src="jquery.min.js"></script>
<script src="jquery.typeahead.js"></script>

2. Then create an input field:

<input class="js-typeahead"
       name="q"
       type="search"
       autofocus
       autocomplete="off">

3. Finally, call the main function on the input field and specify the data source you want to fetch.

$('.js-typeahead').typeahead({
  source: {
    // local data
    groupName: {
      data: [ {...}, {...} ]
    }
  }
});

// or
$('.js-typeahead').typeahead({
  source: {
    // remote data
    groupName: {
      ajax: {
        url: "..."
      }
    }
  }
});

4. Config the typeahead/autocomplete plugin with the following options.

// *RECOMMENDED*, jQuery selector to reach Typeahead's input for initialization
input: null,            

// Accepts 0 to search on focus, minimum character length to perform a search
minLength: 2,          

// False as "Infinity" will not put character length restriction for searching results 
maxLength: false,       

// Accepts 0 / false as "Infinity" meaning all the results will be displayed
maxItem: 8,             

// When true, Typeahead will get a new dataset from the source option on every key press
dynamic: false,         

// delay in ms when dynamic option is set to true
delay: 300,             

// "asc" or "desc" to sort results
order: null,            

// Set to true to match items starting from their first character
offset: false,          

// Added support for excessive "space" characters
hint: false,            

// Will allow to type accent and give letter equivalent results, also can define a custom replacement object
accent: false,          

// Added "any" to highlight any word in the template, by default true will only highlight display keys
highlight: true,        

// Improved feature, Boolean,string,object(key, template (string, function))
group: false,           

// New feature, order groups "asc", "desc", Array, Function
groupOrder: null,       

// Maximum number of result per Group
maxItemPerGroup: null,  

// Take group options string and create a dropdown filter
dropdownFilter: false,  

// Filter the typeahead results based on dynamic value, Ex: Players based on TeamID
dynamicFilter: null,    

// Add a backdrop behind Typeahead results
backdrop: false,        

// Display the backdrop option as the Typeahead input is :focused
backdropOnFocus: false, 

// Improved option, true OR 'localStorage' OR 'sessionStorage'
cache: false,           

// Cache time to live in ms
ttl: 3600000,           

// Requires LZString library
compression: false,     

// Display search results on input focus
searchOnFocus: false,   

// Blur Typeahead when Tab key is pressed, if false Tab will go though search results
blurOnTab: true,        

// List the results inside any container string or jQuery object
resultContainer: null,  

// Forces the source to be generated on page load even if the input is not focused!
generateOnLoad: null,   

// The submit function only gets called if an item is selected
mustSelectItem: false,  

// String or Function to format the url for right-click & open in new tab on link results
href: null,             

// Allows search in multiple item keys ["display1", "display2"]
display: ["display"],   

// Display template of each of the result list
template: null,         

// Set the input value template when an item is clicked
templateValue: null,    

// Set a custom template for the groups
groupTemplate: null,    

// Compile display keys, enables multiple key search from the template string
correlativeTemplate: false, 

// Display an empty template if no result
emptyTemplate: false,   

// // If text is detected in the input, a cancel button will be available to reset the input (pressing ESC also cancels)
cancelButton: true,     

// Display a loading animation when typeahead is doing request / searching for results
loadingAnimation: true, 

// Set to false or function to bypass Typeahead filtering. WARNING: accent, correlativeTemplate, offset & matcher will not be interpreted
filter: true,           

// Add an extra filtering function after the typeahead functions
matcher: null,          

// Source of data for Typeahead to filter
source: null,           

// CSS selectors
selector: {
  container: "typeahead__container",
  result: "typeahead__result",
  list: "typeahead__list",
  group: "typeahead__group",
  item: "typeahead__item",
  empty: "typeahead__empty",
  display: "typeahead__display",
  query: "typeahead__query",
  filter: "typeahead__filter",
  filterButton: "typeahead__filter-button",
  dropdown: "typeahead__dropdown",
  dropdownItem: "typeahead__dropdown-item",
  button: "typeahead__button",
  backdrop: "typeahead__backdrop",
  hint: "typeahead__hint",
  cancelButton: "typeahead__cancel-button"
},

// Display debug information (RECOMMENDED for dev environment)
debug: false                    

5. Callback functions.

callback: {

  // When Typeahead is first initialized (happens only once)
  onInit: null,               

  // When the Typeahead initial preparation is completed
  onReady: null,              

  // Called when the layout is shown
  onShowLayout: null,         

  // Called when the layout is hidden
  onHideLayout: null,         

  // When data is being fetched & analyzed to give search results
  onSearch: null,             

  // When the result container is displayed
  onResult: null,             

  // When the result HTML is build, modify it before it get showed
  onLayoutBuiltBefore: null,  

  // Modify the dom right after the results gets inserted in the result container
  onLayoutBuiltAfter: null,   

  // When a key is pressed to navigate the results, before the navigation happens
  onNavigateBefore: null,     

  // When a key is pressed to navigate the results
  onNavigateAfter: null,      

  // When the mouse enter an item in the result list
  onMouseEnter: null,         

  // When the mouse leaves an item in the result list
  onMouseLeave: null,         

  // Possibility to e.preventDefault() to prevent the Typeahead behaviors
  onClickBefore: null,        

  // Happens after the default clicked behaviors has been executed
  onClickAfter: null,         

  // When the dropdownFilter is changed, trigger this callback
  onDropdownFilter: null,     

  // Gets called when the Ajax request(s) are sent
  onSendRequest: null,        

  // Gets called when the Ajax request(s) are all received
  onReceiveRequest: null,     

  // Perform operation on the source data before it gets in Typeahead data
  onPopulateSource: null,     

  // Perform operation on the source data before it gets in Typeahead cache
  onCacheSave: null,          

  // When Typeahead form is submitted
  onSubmit: null,             

  // Triggered if the typeahead had text inside and is cleared
  onCancel: null              
  
}

Changelog:

v2.11.2 (2022-09-17)

v2.11.1 (2020-05-19)

  • Updated

v2.11.0 (2019-11-01)

  • multi source async results

v2.10.7 (2019-10-20)

  • Fix input on Chrome unable to place the cursor
  • Fix sorting when display key value is null
  • Fix first check that we find an input before accessing found elements

2018-07-31

  • Version 2.10.6

This awesome jQuery plugin is developed by running-coder. For more Advanced Usages, please check the demo page or visit the official website.