Autocomplete
Simple accessible autocomplete for vanilla javacript with support for remote & local data, ~4KB gzip
Install / Use
/learn @tomickigrzegorz/AutocompleteREADME
Demo
See the demo - example
Select2 replacement
This library can serve as a lightweight, zero-dependency alternative to jQuery Select2. Using dropdownParent, showValuesOnClick and classPrefix you can build fully custom select components — including flag-based country selectors and multi-select with chip tags — without pulling in jQuery or any extra dependencies.
See the live examples:
- Country selector — single-select with flag icons
- Country selector multi — multi-select with chips, configurable limit and deselect on click
Features
- You're in full control of the DOM elements to output
- 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 <kbd>↓</kbd> <kbd>↑</kbd>, and confirm by <kbd>Enter</kbd> or mouse
- Grouping of record results
- Showing 'no results'
- Show all values on click
- Multiple choices
- Select2 alternative — build custom searchable selects with flags, chips and multi-select without jQuery
- No dependencies
- Very light library, packed gzip only ~4KB
- And a lot more
Installation
Using npm
Install the library via npm:
npm install @tomickigrzegorz/autocomplete
Or using Yarn:
yarn add @tomickigrzegorz/autocomplete
Import via ES module
After installing via npm or Yarn you can import the library as an ES module:
import Autocomplete from '@tomickigrzegorz/autocomplete';
import '@tomickigrzegorz/autocomplete/css';
Or import CSS separately using the full path:
import 'node_modules/@tomickigrzegorz/autocomplete/dist/css/autocomplete.min.css';
Using a CDN
CSS
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/tomickigrzegorz/autocomplete@3.3.1/dist/css/autocomplete.min.css"/>
JavaScript
<script src="https://cdn.jsdelivr.net/gh/tomickigrzegorz/autocomplete@3.3.1/dist/js/autocomplete.min.js"></script>
-- OR --
Download from dist folder and insert to HTML:
dist/css/autocomplete.cssdist/js/autocomplete.min.js
HTML
Basic code to display autocomplete correctly
<div class="auto-search-wrapper">
<input type="text" id="local" autocomplete="off" placeholder="Enter letter" />
</div>
JavaScript
window.addEventListener('DOMContentLoaded', function () {
// 'local' is the 'id' of input element
new Autocomplete('local', {
onSearch: ({ currentValue }) => {
// local data
const data = [
{ name: 'Walter White' },
{ name: 'Jesse Pinkman' },
{ name: 'Skyler White' },
{ name: 'Walter White Jr.' },
];
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('');
},
});
});
Package Manager
Before the first use, clone this repository and install node dependencies:
git clone https://github.com/tomickigrzegorz/autocomplete.git
yarn
// or
npm install
Run the app
Run the development version:
yarn dev
// or
npm run dev
Run the production version:
yarn prod
// or
npm run prod
Configuration of the plugin
| props | type | default | require | description |
| -------------------- | :--------: | :---------------------------------: | :-----: | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| element | string | | ✔ | Input field id |
| onSearch | function | | ✔ | Function for user input. It can be a synchronous function or a promise |
| onResults | function | | ✔ | Function that creates the appearance of the result |
| onSubmit | function | | | Executed on input submission |
| onOpened | function | | | returns two variables 'results' and 'showItems', 'resutls' first rendering of the results 'showItems' only showing the results when clicking on the input field |
| onSelectedItem | function | | | Get index and data from li element after hovering over li with the mouse or using arrow keys ↓/↑ |
| onReset | function | | | After clicking the 'x' button |
| onRender | function | | | Possibility to add html elements, e.g. before and after the search results |
| onClose | function | | | e.g. delete class after close results, see example modal |
| noResults | function | | | Called when no results are found. Return an HTML string to display: noResults: ({ currentValue }) => \<li>No results for "${currentValue}"</li>`| | onLoading | function | | | Called when an async search starts. Return an HTML string to display in the dropdown while waiting for results (e.g. a spinner or status message). Replaced automatically when results ornoResultsfires:onLoading: ({ currentValue }) => `<li>Searching for "${currentValue}"…</li>`| | destroy | method | | | Clears the input and removes all event listeners. Usereset()if you want to keep the autocomplete functional | | reset | method | | | Clears the input and closes the results list while keeping all event listeners active. Safe alternative todestroy()when you just want to clear the field | | rerender | method | | | This method allows you to re-render the results without modifying the input field. Of course, we can also send the string we want to search for to the method. render(string); | | disable | method | | | This method allows you to disable the autocomplete functionality.const auto = new Autocomplete('id', {...}); auto.disable();then we disable the autocomplete. To remove input value you need to callauto.disable(true); | | enable | method | | | This method allows you to re-enable the autocomplete functionality after it has been disabled.const auto = new Autocomplete('id', {...}); auto.disable(); auto.enable();- now the autocomplete is active again and all event listeners are restored | | clearButton | boolean | true | | A parameter set to 'true' adds a button to remove text from the input field |GitHub Markdown Preview | clearButtonOnInitial | boolean | false | | A parameter set to 'true' adds a button to remove text from the input field visible on initial Autocomplete lib. | | selectFirst | boolean | false`
