Awesomplete ES6 Module

2KB minified & gzipped!

Ultra lightweight, customizable, simple autocomplete widget with zero dependencies, built with modern standards for modern browsers. Because <datalist> still doesn’t cut it.

Demo (no JS, minimal options)

Note that by default you need to type at least 2 characters for the popup to show up, though that’s super easy to customize. With Awesomplete, making something like this can be as simple as:

<input class="awesomplete"
       data-list="Ada, Java, JavaScript, Brainfuck, LOLCODE, Node.js, Ruby on Rails" />
// No extra JS needed for basic usage!

Basic usage

Before you try anything, you need to include awesomplete.css and awesomplete.js in your page, via the usual <link rel="stylesheet" href="awesomplete.css" /> and <script src="awesomplete.js" async></script> tags.

For the autocomplete, you just need an <input> text field (might work on <textarea> and elements with contentEditable, but that hasn’t been tested). Add class="awesomplete" for it to be automatically processed (you can still specify many options via HTML attributes), otherwise you can instantiate with a few lines of JS code, which allow for more customization.

There are many ways to link an input to a list of suggestions. The simple example above could have also been made with the following markup, which provides a nice native fallback in case the script doesn’t load:

<input class="awesomplete" list="mylist" />
<datalist id="mylist">
    <option>Ada</option>
    <option>Java</option>
    <option>JavaScript</option>
    <option>Brainfuck</option>
    <option>LOLCODE</option>
    <option>Node.js</option>
    <option>Ruby on Rails</option>
</datalist>
// None!

Or the following, if you don’t want to use a <datalist>, or if you don’t want to use IDs (since any selector will work in data-list):

<input class="awesomplete" data-list="#mylist" />
<ul id="mylist">
    <li>Ada</li>
    <li>Java</li>
    <li>JavaScript</li>
    <li>Brainfuck</li>
    <li>LOLCODE</li>
    <li>Node.js</li>
    <li>Ruby on Rails</li>
</ul>
// None!

Or the following, if we want to instantiate in JS:

<input id="myinput" />
<ul id="mylist">
    <li>Ada</li>
    <li>Java</li>
    <li>JavaScript</li>
    <li>Brainfuck</li>
    <li>LOLCODE</li>
    <li>Node.js</li>
    <li>Ruby on Rails</li>
</ul>
var input = document.getElementById("myinput");
new Awesomplete(input, {list: "#mylist"});

We can use an element reference for the list instead of a selector:

<input id="myinput" />
<ul id="mylist">
    <li>Ada</li>
    <li>Java</li>
    <li>JavaScript</li>
    <li>Brainfuck</li>
    <li>LOLCODE</li>
    <li>Node.js</li>
    <li>Ruby on Rails</li>
</ul>
var input = document.getElementById("myinput");
new Awesomplete(input, {list: document.querySelector("#mylist")});

We can also directly use an array of strings:

<input id="myinput" />
var input = document.getElementById("myinput");
new Awesomplete(input, {
    list: ["Ada", "Java", "JavaScript", "Brainfuck", "LOLCODE", "Node.js", "Ruby on Rails"]
});

We can even set it (or override it) later and it will just work:

<input id="myinput" />
var input = document.getElementById("myinput");
var awesomplete = new Awesomplete(input);

/* ...more code... */

awesomplete.list = ["Ada", "Java", "JavaScript", "Brainfuck", "LOLCODE", "Node.js", "Ruby on Rails"];

Suggestions with different label and value are supported too. The label will be shown in autocompleter and the value will be inserted into the input.

<input id="myinput" />
var input = document.getElementById("myinput");

// Show label but insert value into the input:
new Awesomplete(input, {
    list: [
        { label: "Belarus", value: "BY" },
        { label: "China", value: "CN" },
        { label: "United States", value: "US" }
    ]
});

// Same with arrays:
new Awesomplete(input, {
    list: [
        [ "Belarus", "BY" ],
        [ "China", "CN" ],
        [ "United States", "US" ]
    ]
});

Customize

All settings discussed in this section are settable via either a data- attribute on the <input> element or a JS property on the second argument of the Awesomplete constructor, like so:

new Awesomplete(inputReference, {
    minChars: 3,
    maxItems: 15,
    ...
});

You can of course combine both HTML attributes and JS properties. In case of conflict (e.g. you’ve specified both a data-minchars on the text field and a minChars JS property, the HTML attribute wins. You can also use the JS properties to change a parameter after the object has been created, in which case the change will apply even if there is a conflicting HTML attribute.

JS property HTML attribute Description Value Default
list data-list Where to find the list of suggestions. Described in more detail in the “Basic usage” section above.
  • Array of strings
  • HTML element
  • CSS selector (no groups, i.e. no commas)
  • String containing a comma-separated list of items
N/A
minChars data-minchars Minimum characters the user has to type before the autocomplete popup shows up. Number 2
maxItems data-maxitems Maximum number of suggestions to display. Number 10
autoFirst data-autofirst Should the first element be automatically selected? Demo: Boolean false

Extend

The following JS properties do not have equivalent HTML attributes, because their values are functions. They allow you to completely change the way Awesomplete works:

Property Description Value Default
filter Controls how entries get matched. By default, the input can match anywhere in the string and it’s a case insensitive match. Function that takes two parameters, the first one being the current suggestion text that’s being tested and the second a string with the user’s input it’s matched against. Returns true if the match is successful and false if it is not. For example, to only match strings that start with the user’s input, case sensitive, we can do this:
filter: function (text, input) {
    return text.indexOf(input) === 0;
}
For case-insensitive matching from the start of the word, there is a predefined filter that you can use, Awesomplete.FILTER_STARTSWITH
Awesomplete.FILTER_CONTAINS: Text can match anywhere, case insensitive.
sort Controls how list items are ordered. Sort function (will be passed directly to Array.prototype.sort()) to sort the items after they have been filtered and before they are truncated and converted to HTML elements. If value is false, sorting will be disabled. Sorted by length first, order second.
container Controls how list container element is generated. Function that takes one parameter, the user’s input and returns an element. Generates <div> with class awesomplete
item Controls how list items are generated. Function that takes two parameters, the first one being the suggestion text and the second one the user’s input and returns a list item. Generates list items with the user’s input highlighted via <mark>.
replace Controls how the user’s selection replaces the user’s input. For example, this is useful if you want the selection to only partially replace the user’s input. Function that takes one parameter, the text of the selected option, and is responsible for replacing the current input value with it.
function (text) {
    this.input.value = text;
}
data Controls suggestions' label and value. This is useful if you have list items in custom format, or want to change list items based on user's input. Function that takes two parameters, the first one being the original list item and the second a string with the user’s input and returns a list item in one of supported by default formats:
  • "JavaScript"
  • { label: "JavaScript", value: "JS" }
  • [ "JavaScript", "JS" ]
To use objects without label or value properties, e.g. name and id instead, you can do this:
data: function (item, input) {
    return { label: item.name, value: item.id };
}
You can use any object for label and value and it will be converted to String where necessary:
list: [ new Date("2015-01-01"), ... ] 
Original list items as Date objects will be accessible in filter, sort, item and replace functions, but by default we'll just see Date objects converted to strings in autocompleter and the same value will be inserted to the input.
We can also generate list items based on user's input. See E-mail autocomplete example in Advanced Examples section.
Awesomplete.DATA: Identity function which just returns the original list item.

Events

Custom events are thrown in several places and are often cancellable. To avoid conflicts, all custom events are prefixed with awesomplete-.

Note: If you are using jQuery and want to access text, selectedIndex and selectedItem on events that passes these along, look into e.originalEvent.

Name Description event.preventDefault()?
awesomplete-select The user has made a selection (either via pressing enter or clicking on an item), but it has not been applied yet. Callback will be passed an object with text (selected suggestion), selectedIndex and selectedItem object and origin (DOM element) properties. Yes. The selection will not be applied and the popup will not close.
awesomplete-selectcomplete The user has made a selection (either via pressing enter or clicking on an item), and it has been applied. Callback will be passed an object with a text property containing the selected suggestion, selectedIndex and selectedItem object. No
awesomplete-open The popup just appeared. No
awesomplete-close The popup just closed. Callback will be passed an object with a reason property that indicates why the event was fired. Reasons include "blur", "esc", "submit", "select", and "nomatches". No
awesomplete-highlight The highlighted item just changed (in response to pressing an arrow key or via an API call). Callback will be passed an object with a text property containing the highlighted suggestion, selectedIndex and selectedItem object. No

API

There are several methods on every Awesomplete instance that you can call to customize behavior:

Method Description
open() Opens the popup.
close() Closes the popup.
next() Highlights the next item in the popup.
previous() Highlights the previous item in the popup.
goto(i) Highlights the item with index i in the popup (-1 to deselect all). Avoid using this directly and try to use next() or previous() instead when possible.
select() Selects the currently highlighted item, replaces the text field’s value with it and closes the popup.
evaluate() Evaluates the current state of the widget and regenerates the list of suggestions or closes the popup if none are available. You need to call it if you dynamically set list while the popup is open.
destroy() Clean up and remove the instance from the input.

Advanced Examples

These examples show how powerful Awesomplete’s minimal API can be.

E-mail autocomplete

<input type="email" />

Multiple values

<input data-list="CSS, JavaScript, HTML, SVG, ARIA, MathML" data-multiple />
        
            
        
    

Ajax example (restcountries.eu api)

Combobox dropdown

<input data-list="CSS, JavaScript, HTML, SVG, ARIA, MathML" class="dropdown-input" />

Download!

Pull requests are very welcome, as long as you maintain the code style and ask before adding tons of LOCs to the codebase!

Tweet