Accessible Autocomplete Component In Vanilla JavaScript – Autocomplete

Category: Form , Javascript , Recommended | June 29, 2019
Author: trevoreyre
Views Total: 493
Official Page: Go to website
Last Update: June 29, 2019
License: MIT

Preview:

Accessible Autocomplete Component In Vanilla JavaScript – Autocomplete

Description:

A fast, dynamic, accessible (WAI-ARIA) compliant autocomplete component written in vanilla JavaScript.

It is highly customizable via CSS and supports for asynchronous data fetching.

Also can be used as a component for Vue.js apps.

Basic usage:

Install & Download.

# Yarn
$ yarn add @trevoreyre/autocomplete-js

# NPM
$ npm install @trevoreyre/autocomplete-js --save

Or include the stylesheet and JavaScript from a CDN.

<link rel="stylesheet" href="https://unpkg.com/@trevoreyre/autocomplete-js/dist/style.css">
<script src="https://unpkg.com/@trevoreyre/autocomplete-js"></script>

Create an input field and an empty result list for the autocomplete component.

<div id="autocomplete" class="autocomplete">
  <input class="autocomplete-input"
    placeholder="Search for a country"
    aria-label="Search for a country"
  >
  <ul class="autocomplete-results"></ul>
</div>

Initialize the component and specify the target container element.

new Autocomplete('#autocomplete', {
    // options here
}

Use the search function to load and live search the data. Can be a synchronous function or a Promise.

window['countries'] = [
  'Afghanistan',
  'Albania',
  'Algeria',
  'Andorra',
  ...
]
new Autocomplete('#autocomplete', {
    search: input => {
      if (input.length < 1) { return [] }
      return countries.filter(country => {
        return country.toLowerCase()
          .startsWith(input.toLowerCase())
      })
    }
})

More options & functions to customize the autocomplete component.

new Autocomplete('#autocomplete', {

    // fired on submit
    onSubmit: Function,

    // CSS class
    baseClass: 'autocomplete'

    // highlights the first result
    autoSelect: false,

    // executed to get the value of results
    getResultValue Function,
 
    // overrides default rendering of results list
    renderResults Function  

}

Changelog:

v2.0.2 (06/29/2019)

  • Fix: Include extra attributes in inputProps when using default slot
  • Fix: Compute aria-activedescendant attribute properly
  • Changed default class for results list from autocomplete-results to autocomplete-result-list
  • Changed default ID for results list from autocomplete-results-{id} to autocomplete-result-list-{id}
  • Call search function on focus
  • Removed renderResults option and replaced with renderResult, which can be used to control rendering of a single result item. This function can return either a DOM element or an HTML string.

v1.0.2 (05/02/2019)

  • Added support for input events in Vue component.

You Might Be Interested In:


Leave a Reply