Simple Accessible Autocomplete For Vanilla Javascript | autocomplete.js

autocomplete-javascript

AutoComplete is a feature-rich, customizable, and fully accessible AutoComplete library written in Vanilla JavaScript.

autocomplete js examples, bootstrap 5 autocomplete ajax, how to implement autocomplete, typeahead large dataset, autocomplete javascript

Features

  • Accessible, with full support for ARIA attributes and keyboard interactions
  • Customize your own CSS
  • Support for asynchronous data fetching
  • Move between the records using the arrows  , and confirm by Enter or mouse
  • Grouping of record results
  • Showing ‘no results’
  • Show all values on click
  • No dependencies
  • Very light library, packed gzip only ~3KB
  • And a lot more

How to make use of it:

1. Download and import the autocomplete.css & autocomplete.min.js file into the document.

<link rel="stylesheet" href="/path/to/autocomplete.css" />
<script src="/path/to/autocomplete.min.js"></script>

2. Upload a polyfill for users who are still using old browsers.

if (!('Promise' in window)) {
  var script = document.createElement('script');
  script.src =
    'https://polyfill.io/v3/polyfill.min.js?features=Promise%2CElement.prototype.closest';
  document.getElementsByTagName('head')[0].appendChild(script);
}

3. Configure autocomplete.js in the target input field and fetch data from an external data source as follows:

<input type="text" id="example" placeholder="Type Something" />
new Autocomplete('example', {
    onSearch: ({ currentValue }) => {
      const api = `/path/to/datasource/`;
      return new Promise((resolve) => {
        fetch(api)
          .then((response) => response.json())
          .then((data) => {
            resolve(data);
          })
          .catch((error) => {
            console.error(error);
          });
      });
    },
    onResults: ({ matches }) => {
      return matches
        .map(el => {
          return `
            <li>${el.name}</li>`;
        }).join('');
    }
});

4. The library also supports local data.

new Autocomplete('local', {
    onSearch: ({ currentValue }) => {
      const data = [
        { "name": "JavaScript" },
        { "name": "CSS" },
        { "name": "HTML" },
        { "name": "Python" }
      ];
      return data.sort((a, b) => a.name.localeCompare(b.name))
        .filter(element => {
          return element.name.match(new RegExp(currentValue, 'i'))
        })
    },
    onResults: ({ matches }) => {
      return matches
        .map(el => {
          return `
            <li>${el.name}</li>`;
        }).join('');
    }
});

5. Possible options and functions.

new Autocomplete('example', {

    // search delay
    delay: 500,

    // shows clear button
    clearButton: true,

    // auto select the first result
    selectFirst: false,

    // adds text to the input field as you move through the results with the up/down cursors
    insertToInput: false,

    // the number of characters entered to trigger the search
    howManyCharacters: 1,

    // name of the class by which you will name the group element
    classGroup: 'group-by',

    // disable close on select
    disableCloseOnSelect: false,

    //  toggle showing all values when the input is clicked, like a default dropdown
    showAllValues: false,

    // prevents results from hiding after clicking on element with this class
    classPreventClosing: ``,

    // determine whether to cache characters entered in the input field
    cache: false,

    onResults = () => { },
    onSearch = () => { },
    onSubmit = () => { },
    onOpened = () => { },
    onReset = () => { },
    onRender = () => { },
    noResults = () => { },
    onSelectedItem = () => { },

});

Configuration of the plugin

propstypedefaultrequiredescription
elementstring Input field id
onSearchfunction Function for user input. It can be a synchronous function or a promise
onResultsfunction Function that creates the appearance of the result
onSubmitfunction  Executed on input submission
onOpenedfunction  returns two variables ‘results’ and ‘showItems’, ‘resutls’ first rendering of the results ‘showItems’ only showing the results when clicking on the input field
onSelectedItemfunction  Get index and data from li element after hovering over li with the mouse or using arrow keys ↓/↑
onResetfunction  After clicking the ‘x’ button
onRenderfunction  Possibility to add html elements, e.g. before and after the search results
onClosefunction  e.g. delete class after close results, see example modal
noResultsfunction  Showing information: “no results”
destroymethod  Removes the autocomplete instance and its bindings
clearButtonbooleantrue A parameter set to ‘true’ adds a button to remove text from the input field
selectFirstbooleanfalse Default selects the first item in the list of results
insertToInputbooleanfalse Adding an element selected with arrows to the input field
disableCloseOnSelectbooleanfalse Prevents results from hiding after clicking on an item from the results list
showAllValuesbooleanfalse This option will toggle showing all values when the input is clicked, like a default dropdown
cachebooleanfalse The characters entered in the input field are cached
howManyCharactersnumber1 The number of characters entered should start searching
delaynumber500 Time in milliseconds that the component should wait after last keystroke before calling search function 1000 = 1s
ariaLabelClearstringclear text from input Set aria-label attribute for the clear button
classPreventClosingstring  Prevents results from hiding after clicking on element with this class
classGroupstring  Enter a class name, this class will be added to the group name elements
classPrefixstring  Prefixing all autocomplete css class name, ‘prefix-auto-‘, default ‘auto-‘
instructionstringWhen autocomplete results ... aria-describedby attribute A full text below

Powerful Autocomplete With Asynchronous Data Fetch, autocomplete Plugin/Github


See Demo And Download

Official Website(tomik23): Click Here

This superior jQuery/javascript plugin is developed by tomik23. For extra Advanced Usages, please go to the official website.