Press "Enter" to skip to content

Simple Accessible Autocomplete With Asynchronous Data Fetch for Vanilla Javascript

Simple autocomplete with asynchronous data fetch. A feature-rich, highly customizable, fully accessible library written in vanilla JavaScript.

Features:

  • Accessible, with full support for ARIA themes and keyboard interactions.
  • Customize your own CSS.
  • Support asynchronous data fetch.
  • Navigate between records using the arrows ↓ ↑, and confirm by entering or the mouse
  • Collecting benchmark results
  • Show “no results”
  • no dependencies
  • Very light library, packed in gzip format only ~3KB

How to make use of it:

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

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

2. Load the polyfills for customers who’re nonetheless utilizing the legacy 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. Initialize the autocomplete.js on the goal input subject and fetch information from an exterior information supply 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 additionally helps native information.

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 choices and features.

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,

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

    onResults = () => { },
    onSearch = () => { },
    onSubmit = () => { },
    onOpened = () => { },
    onReset = () => { },
    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
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 list
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
classGroupstring  Enter a class name, this class will be added to the group name elements
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.

Be First to Comment

    Leave a Reply

    Your email address will not be published.