9.2.0 • Published 18 days ago

autocompleter v9.2.0

Weekly downloads
18,348
License
MIT
Repository
github
Last release
18 days ago

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

Demo: https://smartscheduling.com/en/documentation/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' }
];

var input = document.getElementById('country');

autocomplete({
    input: input,
    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) {
        input.value = item.label;
    }
});

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 `MyInterface` interface with the interface you want to use with autocomplete
autocomplete<MyInterface>({
    input: document.getElementById('myinputfield'),
    emptyMsg: 'No items found',
    minLength: 1,
    fetch: (text: string, update: (items: MyInterface[]) => void) => {
	...
    },
    onSelect: (item: MyInterface) => {
	...
    }
});

If your custom interface 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 MyItem = Item & AutocompleteItem;

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

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

Options

You can pass the following options to autocomplete:

ParameterDescriptionDefault
onSelectThis method will be called when user choose an item in autocomplete. The selected item will be passed as first parameter.-
inputDOM 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.-
minLengthSpecify the minimum length, when autocomplete should appear on the screen.2
emptyMsgThe message that will be showed when there are no suggestions that match the entered value.undefined
renderThis 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
renderGroupThe 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
classNameThe autocomplete container will have this class name if specified.undefined
fetchThis 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. If you pass false to the callback function, autocomplete will show previous suggestions and will not re-render.-
debounceWaitMsEnforces that the fetch function will only be called once within the specified time frame (in milliseconds) and delays execution. This prevents flooding your server with AJAX requests.0
customizeCallback for additional autocomplete customization after rendering is finished. Use this function if you want to change autocomplete default position.undefined
preventSubmitThis option controls form submission when the ENTER key is pressed in a input field. Three settings are available: Never, Always, and OnSelect. Choose the appropriate setting to customize form submission behavior as per your needs.Never
showOnFocusDisplays suggestions on focus of the input element. Note that if true, the minLength property will be ignored and it will always call fetch.false
disableAutoSelectPrevents the first item in the list from being selected automatically. This option allows you to submit a custom text by pressing ENTER even when autocomplete is displayed.false
containerProvide your own container for the widget. If not specified, a new DIV element will be created.undefined
clickAllows to display autocomplete on mouse clicks or perform some additional actions.undefined
keyupAllows to display autocomplete when a key is pressed that doesn't modify the content.see code

Sample config using all options

autocomplete({
    onSelect: function(item, input) {
        alert(item.value);
    },
    input: document.getElementById('myinput'),
    minLength: 2,
    emptyMsg: 'No elements found',
    render: function(item, currentValue) {
        var div = document.createElement('div');
        div.textContent = item.label;
        return div;
    },
    renderGroup: function(groupName, currentValue) {
        var div = document.createElement('div');
        div.textContent = groupName;
        return div;
    },
    className: 'autocomplete-customizations',
    fetch: function(text, callback, trigger, cursorPos) {
        text = text.toLowerCase();
        var suggestions = [{ label: 'United States', value: 'US' }];
        callback(suggestions);
    },
    debounceWaitMs: 200,
    customize: function(input, inputRect, container, maxHeight) {
        ...
    },
    preventSubmit: PreventSubmit.Always,
    disableAutoSelect: true,
    container: document.createElement('div'),
    click: e => e.fetch(),
    keyup: e => e.fetch()
});

Display autocomplete above the input field

You can use the following snippet to display autocomplete above the input field if there is not enough space for it.

autocomplete({
    ...,
    customize: function(input, inputRect, container, maxHeight) {
        if (maxHeight < 100) {
            container.style.top = '';
            container.style.bottom = (window.innerHeight - inputRect.bottom + input.offsetHeight) + 'px';
            container.style.maxHeight = '200px';
        }
    }
});

If you don't want to pass this function every time, you can also use spread operator to create your own autocomplete version with default implementation:

export default function autocompleteCustomized<T extends AutocompleteItem>(settings: AutocompleteSettings<T>): AutocompleteResult {
    return autocomplete({
        ...settings,
        customize: (input: HTMLInputElement, inputRect: ClientRect | DOMRect, container: HTMLDivElement, maxHeight: number): void => {
            if (maxHeight < 100) {
                container.style.top = '';
                container.style.bottom = (window.innerHeight - inputRect.bottom + input.offsetHeight) + 'px';
                container.style.maxHeight = '200px';
            }
        }
    });
}

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: 'Canada', value: 'CA', 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.

Display autocomplete when textbox is clicked by a mouse

The widget offers the ability to display an autocomplete when a user clicks on words or placeholders within a textbox:

function getWord(s, pos) {
    const n = s.substring(pos).match(/^[a-zA-Z0-9-_]+/)
    const p = s.substring(0, pos).match(/[a-zA-Z0-9-_]+$/)
    if (!p && !n) return ''
    return (p || '') + (n || '')
}
autocomplete({
    ...,
    fetch: function(text, update) {
        text = getWord(text, input.selectionStart).toLowerCase();
        var suggestions = countries.filter(n => n.label.toLowerCase().startsWith(text))
        update(suggestions);
    },
    click: e => e.fetch()
});

Try online

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.

9.2.0

18 days ago

9.0.0-alpha.1

9 months ago

9.0.0-alpha.0

9 months ago

9.1.1

6 months ago

9.1.0

8 months ago

9.1.2

5 months ago

9.0.1

9 months ago

8.0.4

10 months ago

8.0.0-alpha.0

1 year ago

8.0.0-alpha.1

1 year ago

8.0.0-alpha.2

1 year ago

8.0.1

1 year ago

8.0.3

1 year ago

8.0.2

1 year ago

7.1.0

1 year ago

7.0.0-alpha.1

1 year ago

7.0.0-alpha.0

1 year ago

7.0.1

1 year ago

6.1.3

2 years ago

6.1.2

3 years ago

6.1.1

3 years ago

6.1.0

3 years ago

6.0.5

3 years ago

6.0.4

3 years ago

6.0.3

4 years ago

6.0.2

4 years ago

6.0.0-alpha.1

4 years ago

6.0.1

4 years ago

5.2.0

4 years ago

5.1.3

4 years ago

5.1.2

4 years ago

5.1.1

4 years ago

5.1.0

5 years ago

5.0.1

5 years ago

5.0.0-alpha.3

5 years ago

5.0.0-alpha.2

5 years ago

5.0.0-alpha.1

5 years ago

4.0.2

5 years ago

4.0.1

5 years ago

4.0.0-alpha.2

5 years ago

4.0.0-alpha.1

5 years ago

4.0.0-alpha.0

5 years ago

3.0.5

5 years ago

3.0.4

5 years ago

3.0.3

5 years ago

3.0.2

5 years ago

3.0.1

5 years ago

2.2.1

5 years ago

2.1.5

6 years ago

2.1.4

6 years ago

2.1.3

6 years ago

2.0.3

6 years ago

2.0.2

6 years ago

2.0.1

6 years ago

2.0.0

6 years ago

1.0.35

6 years ago

1.0.34

6 years ago

1.0.33

6 years ago

1.0.32

6 years ago

1.0.31

6 years ago

1.0.30

6 years ago

1.0.29

7 years ago

1.0.28

7 years ago

1.0.27

7 years ago

1.0.26

7 years ago

1.0.25

7 years ago

1.0.24

7 years ago

1.0.23

7 years ago

1.0.22

7 years ago

1.0.21

7 years ago

1.0.20

7 years ago

1.0.19

7 years ago

1.0.18

7 years ago

1.0.17

7 years ago

1.0.16

7 years ago

1.0.15

7 years ago

1.0.14

7 years ago

1.0.13

7 years ago

1.0.12

7 years ago

1.0.11

7 years ago

1.0.10

7 years ago

1.0.9

7 years ago

1.0.8

7 years ago

1.0.7

7 years ago

1.0.6

7 years ago

1.0.5

7 years ago

1.0.4

7 years ago

1.0.3

7 years ago

1.0.2

7 years ago

1.0.1

7 years ago

1.0.0

7 years ago