Fast Autocomplete & Typeahead Library – autoComplete.js

Category: Form , Javascript , Recommended | June 9, 2021
Author: TarekRaafat
Views Total: 48 views
Official Page: Go to website
Last Update: June 9, 2021
License: Apache-2.0

Preview:

Fast Autocomplete & Typeahead Library – autoComplete.js

Description:

A dynamic, blazing-fast,  dependency-free,  and easy-to-use autocomplete & typeahead JavaScript library for modern web development.

Key features:

  • Auto displays the suggestion list while typing.
  • Fuzzy search is supported.
  • Highlights matched results.
  • Custom placeholder.
  • Limits the maximum number of results to display.

How to use it:

1. Install and import the autoComplete.js.

# Yarn
$ yarn add @tarekraafat/autocomplete.js --save

# NPM
$ npm i @tarekraafat/autocomplete.js --save
// ES6
import autoComplete from "./autoComplete";

// Browser
<link rel="stylesheet" href="dist/css/autoComplete.min.css" />
<script src="dist/js/autoComplete.min.js"></script>

2. Define your own data for the suggestions. Can be

// array of strings
const data = {
      key: ["CSS", "SCRIPT", "COM"]
}

// array of objects
const data = {
      src: [
        { "js": "React" },
        { "js": "Angular" },
        { "css": "LESS" },
        { "css": "SASS" }
      ],
      key: ["js", "css"]
}

// function
const data = {
      src: () => { ... },
      key: ["js"],
      cache: true,
}

// async
const data = {
      src: async (query) => {
        try {
          // Fetch Data from external Source
          const source = await fetch(`https://www.api.com/${query}`);
          // Data is array of `Objects` | `Strings`
          const data = await source.json();
          return data;
        } catch (error) {
          return error;
        }
      },
      // Data 'Object' key to be searched
      keys: ["js"]
},

3. Create an input field or text field with a unique ID ‘autoComplete’.

<input id="autoComplete" type="text">

4. Attach the autoComplete.js to the input field and done.

new autoComplete({

    // global instance name
    name: "autoComplete",

    // Array, Function, Async
    data: data,

    // Event & Condition rules that trigger autoComplete.js engine to start
    trigger: (query) => {
      return query.replace(/ /g, "").length; // Returns "Boolean"
    },

    // object with 1 method manipulate: Function with (query) argument
    query: (input) => {
      return input.replace("js");
    },

    // sort rendered results ascendingly | (Optional)
    sort: (a, b) => {                    
        if (a.match < b.match) return -1;
        if (a.match > b.match) return 1;
        return 0;
    },

    // min character length
    threshold: 1,

    // input field selector
    selector: "#autoComplete",

    // Input field observer | (Optional)
    observer: true,

    // placeholder
    placeHolder: "Type Here ...",

    // minimum duration after typing idle state for engine to kick in
    debounce: 0, 

    // String lowerCase "strict" | "loose"
    // Function with 2 parameters (query, record) returns 1 String of each match individually
    searchEngine: "strict",

    // search engine diacritics handler.
    diacritics: false,

    // rendered results list object
    resultsList: {
      tag: "ul",
      id: "autoComplete_list",
      class: "autoComplete_list",
      destination: "#autoComplete",
      position: "afterend",
      maxResults: 5,
      element: (list, data) => {
        // ...
      },
      tabSelect: false,
      noResults: false,
    },

    // Rendered result item   
    resultItem: {
      tag: "li",
      id: "autoComplete_result_[index]",
      class: "autoComplete_result",
      element: (item, data) => {
        // ...
      },
      highlight: false, // string or boolean
      selected: "", // selected class
    },

    // events
    events: {
      input: {
        focus: (event) => {
          console.log("Input Field in focus!");
        }
      },
      list: {
        scroll: (event) => {
          console.log("Results List scrolled!");
        }
      }
    },
    
});

5. API methods.

// pre-init
autoCompleteJS.preInit();

// initialize
autoCompleteJS.init();

// start
autoCompleteJS.start();

// search
autoCompleteJS.search(query, record, options);

// open
autoCompleteJS.open();

// next resultItem
autoCompleteJS.next();

// prev resultItem
autoCompleteJS.previous();

// goto a specific resultItem
autoCompleteJS.gotTo(1);

6. Event handlers.

document.querySelector("#autoComplete").addEventListener("response", function (event) {
  // "event.detail" carries the returned data values
  console.log(event.detail);
});

document.querySelector("#autoComplete").addEventListener("results", function (event) {
  // after search operation is done and matching results are ready
});

document.querySelector("#autoComplete").addEventListener("open", function (event) {
  // after opening the results list
});

document.querySelector("#autoComplete").addEventListener("navigate", function (event) {
  // on every "resultsList" navigation interaction
});

document.querySelector("#autoComplete").addEventListener("close", function (event) {
  // after "resultsList" is closed
});

Changelog:

v10.1.3 (06/09/2021)

  • Fixed: mark tag’s invalid “classes” to “class” attribute

v10.1.2 (06/02/2021)

  • Fixed: Data fetching error handling

v10.1.1 (06/01/2021)

  • Added: wrapper API property controls wrapper rendering
  • Fixed: TypeError: “query” is read-only
  • Fixed: Mouse click item selection error

v10.1.0 (06/01/2021)

  • Fixed: APIs works with the wrong instance

v10.0.4 (05/29/2021)

  • Updated: data.src query parameter to be aligned with the query method value when set

v10.0.3 (05/30/2021)

  • Fixed: Scrolling issue moving the entire page
  • Fixed: Searching Numbers issue

v10.0.2 (05/29/2021)

  • Fixed: Missing Package Files

v10.0.0 (05/29/2021)

  • Added: Automatic field wrapping inside DIV
  • Added: Document readyState listener that initializes the library after DOM content is loaded
  • Added: query value to data.src for easier data fetching
  • Added: resultsList navigation auto scrolling for long lists
  • Added: resultsList.tabSelect API property to control tab button behavior
  • Added: events list API property that holds and assigns events to input & list (Thanks 👍 @stell) #223
  • Added: close API method controls resultsList state
  • Added: open API method controls resultsList state
  • Added: goTo API method controls resultsList navigation by index
  • Added: next API method controls resultsList navigation
  • Added: previous API method controls resultsList navigation
  • Added: select API method controls resultsList selection by index
  • Added: search API method to avail autoComplete.js powerful engine for external use
  • Added: isOpen API boolean property that holds resultsList state true opened false closed
  • Added: list API property holds the entire list html element
  • Added: wrapper API property holds the entire wrapper html element
  • Added: cursor API property holds the index of the current selection or -1 or undefined for idle
  • Added: id API property holds the current instance number
  • Added: name API property that changes all the className properties accordingly
  • Added: options API property that holds all the custom set config options for separation
  • Added: data.src fetching error message/instance to response event detail (Thanks 👍 @folknor) #207
  • Updated: Data caching with a better mechanism
  • Updated: WAI-ARIA configurations for significantly better support
  • Updated: dataFeedback event information
  • Fixed: diacritics highlighting issue in strict mode
  • Fixed: resultsList eventEmitters unexpected behavior which was firing multiple times
  • Fixed: Empty className values do not assign any classes instead of undefined
  • Changed: The core library architecture for an improved performance and code separation
  • Changed: API to only include the used options instead of including unused ones with undefined value
  • Changed: fetch eventEmitter name to response
  • Changed: inputField API property name to input
  • Changed: dataFeedback API property name to feedback
  • Changed: trigger API property type from Object to Function formerly called trigger.condition
  • Changed: data.results API property name to data.filter
  • Changed: noResults API to accept boolean instead of Function to be replaced with resultsList.container
  • Changed: resultItem.highlight API property type from Object to accept Boolean or String formerly called resultItem.highlight.class
  • Changed: resultItem.selected API property type from Object to String formerly called resultItem.selected.class
  • Changed: resultItem.content API parameters order from (data, element) to (element, data) for consistency
  • Changed: resultItem.idName API property name to resultItem.id
  • Changed: resultItem.className API property name to resultItem.class
  • Changed: resultItem.content API property name to resultItem.element
  • Changed: resultsList.idName API property name resultsList.id
  • Changed: resultsList.className API property name resultsList.class
  • Changed: resultsList.container API property name to resultsList.element
  • Changed: Highlighted characters wrapper element to be mark instead of span (Thanks 👍 @aarongerig) #195
  • Changed: query API property type from Object to Function formerly called query.manipulate
  • Changed: observer API property name observe
  • Changed: data.key API property name data.keys
  • Removed: onSelection API method to be replaced with selection eventEmitter
  • Removed: resultsList.render API property to be replaced with resultsList to accept Boolean instead of Object in case of disabling list rendering
  • Removed: trigger.event API property to be replaced with events
  • Removed: feedback API method to be replaced with navigate event
  • Removed: resultsList.navigation API method to be replaced with events
  • Removed: nav API property to be replaced with events
  • Removed: hook API method to be replaced with start API
  • Removed: onSelection API method to be replaced with selection eventEmitter
  • Removed: input property from feedback due to the existence of query already
  • Removed: unInit eventEmitter

v9.1.1 (05/02/2021)

  • Fixed: Data feedback inputField value was in lowerCase instead of raw
  • Fixed: resultItem.className did not accept except one class instead of multiple

v9.1.0 (05/01/2021)

  • Added: New data parameter to resultsList.container method that contains (input, query, matches, results) values
  • Updated: resultsList.container.className default value to be undefined
  • Updated: Code with some refactoring & cleanup
  • Updated: Development dependencies
  • Fixed: resultsList error on Enter key press with no selection
  • Fixed: Input field aria-activedescendant was not removed on each resultsList regeneration
  • Fixed: noResults error on Enter key press
  • Fixed: Input field aria-expanded set to true even when noResults was not active
  • Fixed: resultsList on close event did not fire when noResults was active
  • Fixed: unInit method did not remove all inputField set event listeners except for input event
  • Fixed: open eventEmitter unexpected behavior that used to fire on each trigger event

v9.0.5 (04/26/2021)

  • Fixed: resultsList.container hierarchy comes after list rendering instead of before

v9.0.4 (04/26/2021)

  • Fixed: resultsList.container is removed on second input

v9.0.3 (04/17/2021)

  • Fixed: TAB button behavior
  • Fixed: resultsList close behavior on inputField double click

v9.0.2 (04/17/2021)

  • Fixed: Unexpected behavior onClick

v9.0.1 (04/16/2021)

  • Fixed: resultItem.idName issue
  • Updated: Tab button behavior

v9.0.0 (03/11/2021)

  • Fixed: esc button not working with noResults in some cases
  • Added: selection & highlight custom className API methods
  • Added: eventEmitter for resultsList fires on list close event
  • Added: event parameter to trigger.event API method
  • Changed: maxResults API moved under resultsList
  • Changed: noResults API moved under resultsList
  • Changed: highlight API moved under resultItem
  • Changed: selection API moved under resultItem with the name of selected
  • Changed: rendered eventEmitter name to open
  • Changed: navigation eventEmitter name to navigate
  • Changed: closeAllLists refactored and renamed to closeList
  • Changed: generateList stage with some refactoring
  • Changed: start stage with some refactoring
  • Changed: noResults API method with some refactoring details
  • Changed: highlight API from String to Object details
  • Removed: sort API
  • Removed: connect eventEmitter from the preInit stage

v8.3.2 (03/11/2021)

  • Fix: selector as a function breaks when observer is true
  • Custom selected item and highlighted text classes

v8.3.1 (02/09/2021)

  • Fix: Keyboard navigation selection reset

v8.3.0 (01/30/2021)

  • Added: event object to the onSelection data feedback

v8.2.3 (01/27/2021)

  • Fix: resultItem ID setAttribute to be idName instead of className

v8.2.2 (01/22/2021)

  • Fix: diacritics composite characters do not match

v8.2.1 (12/30/2020)

  • Package updated

v8.2.0 (12/27/2020)

  • Added: data.results API to access and manipulate data feedback matching results
  • Fixed: resultItem.content API data params to pass the entire item data

v8.1.1 (12/23/2020)

  • Fixed: selector API to accept function
  • Fixed: resultsList destination API to accept function

v8.1.0 (12/12/2020)

  • Added: observer Controller API [Turned off by default]
  • Added: New Light Style [autoComplete.02.css]
  • Fixed: Main build live reload issue

v8.0.4 (12/11/2020)

  • Fix: Error when using multiple instances

v8.0.3 (12/10/2020)

  • Fixed: Custom results list rendering destination

v8.0.1 (12/05/2020)

  • Build Update

v8.0.0 (12/05/2020)

  • Whole New More Modern Architecture Design
  • Added: High Quality Accessibility (WAI-ARIA 1.2) Support
  • Added: Life Cycle Events
  • Added: init/unInit methods
  • Added: Input Field Observing Functionality
  • Added: Diacritics 2 way Support
  • Added: API for Controlling Classes & IDs
  • Added: New neutral/non-opinionated Style
  • Enhanced: autoComplete.js Internal Flow
  • Enhanced: data Fetching
  • Enhanced: data Storing
  • Enhanced: resultsList Navigation
  • Enhanced: resultsList Rendering
  • Fixed: resultsList element visibility in idle state
  • Fixed: query threshold length accuracy
  • Fixed: Calling dataSrc on each trigger
  • Fixed: Right-click behavior on resultsList
  • Fixed: Cursor relocation on keyboard keyUp or keyDown
  • Fixed: data as a Number parsing issue
  • Fixed: autoComplete.js interference with native keyboard events
  • Fixed: Keyboard events stops working when onSelection not defined

v7.2.0 (03/24/2020)

  • Threshold Limit Fix & Added Diacritics Handling

v7.2.0 (11/10/2019)

  • Added support to textarea input field

v7.1.3 (11/03/2019)

  • Enhanced mouse selection

v7.1.2 (10/30/2019)

  • Fixed error behavior occurs when searching (Empty, False, Null) record

v7.1.1 (10/21/2019)

  • resList now is fully created in DocumentFragment before rendering for better performance
  • config parameters restructure
  • Reduced autoComplete.js weight

v7.1.0 (10/07/2019)

  • New improved Navigation logic
  • Enhanced resList.navigation API data feedback
  • Major code Refactor & Optimizations

v7.0.3 (09/26/2019)

  • Duplicate values selection bugfix

v7.0.2 (09/26/2019)

  • Data Promise bug fix
  • Remote API duplicate calls fix
  • trigger.condition enhancement
  • Code Refactor for faster performance and lighter weight

v7.0.0 (09/17/2019)

  • api multiple calls issue fix

v7.0.0 (09/01/2019)

  • New API for results list navigation resultsList.navigation
  • New API for autoComplete.js engine trigger.event
  • New API for autoComplete.js engine trigger.condition
  • Added Support to Shadow DOM expanding customizability
  • Node Element Support for Input Selector
  • Empty record issue fix
  • customEngine API [Removed]
  • customEngine merged with searchEngine API key for more convenience [Changed]
  • Code Optimizations

v6.0.0 (06/15/2019)

  • CustomEvent & Closest method IE compatibility
  • Query interception
  • Simplified resultsList & resultItem
  • EventEmitter fires on clearing input field
  • EventEmitter now has input method for row user’s input
  • EventEmitter now has query method for intercepted user’s input

v5.3.0 (06/05/2019)

  • Get results from eventEmitter without rendering list through resultsList.render API
  • EventEmitter name type changed to autoComplete [Changed]

v5.2.0 (06/02/2019)

  • Added Event Emitter on noResults event

v5.1.1 (05/31/2019)

  • UpperCase query bug fix
  • Added noResults open API for No Results
  • HTML elements ContentEditable Input Support

v5.0.0 (05/07/2019)

  • Large datasets handling
  • API Data fetching & Dynamic Data reloading
  • Debouncing API Calls
  • Custom resultsList & resultItem Elements
  • Bug fixes
  • Code Clean Up

v4.0.0 (03/01/2019)

  • Multiple searchable keys for data src
  • Rendered results in original case
  • Improved Development Environment
  • IE 11 fix
  • Improved returned data object onSelection
  • Sort rendered results API
  • Enhanced results navigation adding ArrowRight key for selection
  • Added event emitter on input field type name type returns
  • Code Clean Up

v3.2.2 (02/06/2019)

  • Fixed bug with hightlight API default value during strict engine mode
  • Fixed bug with resultsList API default value when not configured

v3.2.1 (01/09/2018)

  • Isolated resultsList value for multiple instances

v2.1.0 (01/06/2018)

  • Updated

v2.0.0 (12/23/2018)

  • Updated options.

v1.5.4 (12/21/2018)

  • Gzipped options for both builds & style issue fixed.

v1.5.3 (12/20/2018)

  • Added “threshold” option, code optimizations

v1.5.2 (12/19/2018)

  • Fixed onSelection null action issue & Optimized the code.

v1.4.1 (12/11/2018)

  • Updated Presentation Layer.
  • Code Cleanup.

v1.4.0 (12/09/2018)

  • Added searchEngine mode switcher to presentation layer for better demonstration.
  • Optimized “autoComplete.js”, changed input style in “autoComplete.css” sheet and updated build dependencies.

v1.3.1 (12/03/2018)

  • Update styles

v1.3.0 (12/02/2018)

  • Added new “datasrc” as a function returns “Array”.

v1.2.1 (11/27/2018)

  • Added maximum Placeholder text length feature.

v1.2.0 (11/26/2018)

  • Redesigned the entire search engine for better experience and results, added support for multi-keywords search.

v1.1.0 (11/25/2018)

  • Refactored & Optimized the whole library for lighter weight and better performance.

11/23/2018

  • Optimization Reduced the library weight by 1KB.

You Might Be Interested In:


One thought on “Fast Autocomplete & Typeahead Library – autoComplete.js

Leave a Reply