Skip to content

Blazing fast and lightweight autocomplete library without dependencies. Only 1KB gzipped. Demo:

Notifications You must be signed in to change notification settings

tiagomsmagalhaes/autocomplete

 
 

Repository files navigation

Blazing fast and lightweight autocomplete widget without dependencies. Only 1KB gzipped.

Demo: https://kraaden.github.io/autocomplete/

Installation

If you want to use the library in browser, just include the autocomplete.js and autocomplete.css into your HTML file.

For node.js:

npm install autocompleter

Then import it into your javascript code:

import autocomplete from 'autocompleter';
// or
var autocomplete = require('autocompleter');

Getting Started

var countries = [
    { label: 'United Kingdom', value: 'UK' },
    { label: 'United States', value: 'US' }
];

autocomplete({
    input: document.getElementById("country"),
    fetch: function(text, update) {
        text = text.toLowerCase();
        // you can also use AJAX requests instead of preloaded data
        var suggestions = countries.filter(n => n.label.toLowerCase().startsWith(text))
        update(suggestions);
    },
    onSelect: function(item) {
        alert(item.value); // will display 'US' or 'UK'
    }
});

Try online

Use with Typescript and Webpack

Simply import the autocompleter in your typescript file:

    import autocomplete from "autocompleter";

and call the autocomplete function as showed below:

    // replace the `Client` class with the class you want to use with autocompleter
    autocomplete<Client>({
        input: document.getElementById("myinputfield"),
        emptyMsg: "No clients found",
        minLength: 1,
        fetch: (text: string, update: (items: Client[]) => void) => {
	...
        },
        onSelect: (client: Client) => {
	...
        }
    });

If your custom class doesn't have the label property, you might get a compilation error from typescript. In this case just add an additional type to your code and pass it to the autocompleter:

    import autocomplete, { AutocompleteItem } from "autocompleter";
    
    // this type will prevent typescript warnings
    type AutocompleteClient = Client & AutocompleteItem;

    autocomplete<AutocompleteClient>({
        input: document.getElementById("myinputfield"),
        emptyMsg: "No clients found",
        minLength: 1,
        fetch: (text: string, update: (items: Client[]) => void) => {
	...
        },
        onSelect: (client: Client) => {
	...
        },
        render: function(item: Client, currentValue: string): HTMLDivElement | undefined {
            const itemElement = document.createElement("div");
            itemElement.textContent = item.FirstName;
            return itemElement;
        }
    });

If your class doesn't have a label property, you also have to provide a custom render function.

Options

You can pass the following options to autocomplete:

Parameter Description Default
onSelect This method will be called when user choose an item in autocomplete. The selected item will be passed as first parameter. -
input DOM input element must be passed with this parameter and autocomplete will attach itself to this field. Selectors are not supported, but you can just use document.querySelector('...') to find the required element. -
minLength Specify the minimum length, when autocomplete should appear on the screen. 2
emptyMsg The message that will be showed when there are no suggestions that match the entered value. undefined
render This method allows you to override the rendering function. It will be called for each suggestion and the suggestion object will be passed as first parameter. The current input field value will be passed as second parameter. This function must return a DIV element or undefined to skip rendering. undefined
renderGroup The same as render, but will be called for each group. The first parameter of the function will be the group name. The current input field value will be passed as second parameter. This function must return a DIV element or undefined to skip rendering. undefined
className The autocomplete container will have this class name if specified. undefined
fetch This method will be called to prepare suggestions and then pass them to autocomplete. The first parameter is the text in the input field. The second parameter is a callback function that must be called after suggestions are prepared with an array as parameter. -

Sample config using all options

autocomplete({
    onSelect: function(item) {
        alert(item.value);
    },
    input: document.getElementById('myinput'),
    minLength: 2,
    emptyMsg: 'No elements found',
    render: function(item, currentValue) {
        var div = doc.createElement("div");
        div.textContent = item.label;
        return div;
    },
    renderGroup: function(groupName, currentValue) {
        var div = doc.createElement("div");
        div.textContent = groupName;
        return div;
    },
    className: 'autocomplete-customizations',
    fetch: function(text, callback) {
        text = text.toLowerCase();
        var suggestions = [{ label: "United States", value: "US" }];
        callback(suggestions);
    }
});

Unload autocomplete

You can call destroy method on the returned object in order to remove event handlers and DOM elements after usage:

var autocompl = autocomplete({ /* options */ });
autocompl.destroy();

Grouping suggestions

You can display suggestions separated into one or multiple groups/categories:

var countries = [
    { label: 'United Kingdom', value: 'UK', group: "North America" },
    { label: 'United States', value: 'US', group: "North America" },
    { label: 'Uzbekistan', value: 'UZ', group: "Asia" },
];

autocomplete({
    minLength: 1,
    input: document.getElementById("country"),
    fetch: function(text, update) {
        text = text.toLowerCase();
        var suggestions = countries.filter(n => n.label.toLowerCase().startsWith(text))
        update(suggestions);
    },
    onSelect: function(item) {
        alert(item.value);
    }
});

Try online

Note: Please make sure that all items are sorted by the group property.

License

Autocomplete is released under the MIT License.

Copyright (c) 2016 - Denys Krasnoshchok

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

About

Blazing fast and lightweight autocomplete library without dependencies. Only 1KB gzipped. Demo:

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • TypeScript 47.0%
  • HTML 43.3%
  • JavaScript 7.5%
  • CSS 2.2%