Accessible Autocomplete Component In Vanilla JavaScript – Autocomplete

Category: Form , Javascript , Recommended | May 2, 2019
Author: trevoreyre
Views Total: 234
Official Page: Go to website
Last Update: May 2, 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:

v1.0.2 (05/02/2019)

  • Added support for input events in Vue component.

You Might Be Interested In:


Leave a Reply