Fast Autocomplete Dropdown For Input Field – autocomplete.js

Category: Form , Javascript | May 30, 2018
Author: gmurayama
Views Total: 655
Official Page: Go to website
Last Update: May 30, 2018
License: MIT

Preview:

Fast Autocomplete Dropdown For Input Field – autocomplete.js

Description:

A vanilla JavaScript autocomplete library that attaches a blazing fast autocomplete dropdown list to your input field while typing.

How to use it:

Prepare your dataset for the autocomplete list. Specify an array of suggestions in any file such as JSON, HTML, JS, etc.

// list.html
[
  "JavaScript",
  "JavaScript Vanilla"
  "JavaScript Plugin"
  ...
]

Place the main JavaScript file ‘autocomplete.js’ at the bottom of the document.

<script src="src/autocomplete.js"></script>

Add the required attribute ‘data-autocomplete’ to your input field and specify the data source you want to fetch.

<input type="text" 
       data-autocomplete 
       data-autocomplete-source="list.html" 
       placeholder="Try to type &quot;JavaScript&quot;"
>

Initialize the autocomplete library on the input field and get the suggestion list on keyup event.

var element = document.querySelector('input');
var autoComplete = new AutoComplete(element);

element.onkeyup = function () {
  autoComplete.getSuggestionList();
}

To specify the minimum text length to execute the autocomplete:

<input type="text" 
       data-autocomplete 
       data-autocomplete-source="list.html" 
       autocomplete-minlength="3"
       placeholder="Try to type &quot;JavaScript&quot;"
>

The example CSS to style the autocomplete list.

.autocomplete.dropdown {
  background-color: #F8F8F8;
  position: absolute;
  box-shadow: 0 1px 3px 0px;
  border-radius: 3px;
  border: 1px solid #FAFAFA;
  z-index: 100;
  max-height: 250px;
  overflow-y: auto;
}

.autocomplete.dropdown ul {
  list-style: none;
  margin: 0;
  padding: 0;
}

.autocomplete.dropdown ul li {
  padding: 4px 12px;
}

.autocomplete.dropdown ul li:focus,
.autocomplete.dropdown ul li:hover {
  background-color: #F0F0F0;
  cursor: pointer;
}

Changelog:

05/30/2018

  • Select item via keyboard

You Might Be Interested In:

Leave a Reply