Fast Autocomplete Dropdown For Input Field – autocomplete.js

Category: Form , Javascript | March 23, 2019
Author: gmurayama
Views Total: 2,053
Official Page: Go to website
Last Update: March 23, 2019
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:

03/23/2019

  • Item selection function moved from constructor

05/30/2018

  • Select item via keyboard

You Might Be Interested In:


One thought on “Fast Autocomplete Dropdown For Input Field – autocomplete.js

  1. Gerald

    Hi, I am trying to develop a Javascript drop down list and your work will help me a lot in getting started. I have downloaded the script but it is not populating the list items in Chrome and Firefox.

    Reply

Leave a Reply