Tiny And Fast Autocomplete JavaScript Library – Autocomp.js

Category: Form , Javascript , Recommended | August 31, 2023
Author:knadh
Views Total:341 views
Official Page:Go to website
Last Update:August 31, 2023
License:MIT

Preview:

Tiny And Fast Autocomplete JavaScript Library – Autocomp.js

Description:

Autocomp.js is a super-tiny and blazing-fast autocomplete JavaScript library for the web.

It can fetch suggestions asynchronously from a local or remote data source and render them inline as the user types. Works with the native input field.

How to use it:

1. Install and import the autocomp.

# NPM
$ npm i @knadh/autocomp
import { autocomp } from './autocomp.min.js';

2. Define the suggestions that you want to show in the autocomplete dropdown menu by passing an array of strings as follows:

const suggestions = ["apple", "banana", "apricot"];

3. Initialize autocomp on an input element and specify the suggestion data source:

<input id="example" />
autocomp(document.querySelector("#example"), {
  onQuery: async (val) => {
    // This callback returns an array of search results.
    // Typically, this will be a server side fetch() request.
    // Example:
    // const resp = await fetch(`/search?q=${query}`);
    // const res = await response.json();  
    // return res;
    const q = val.trim().toLowerCase();
    return suggestions.filter(s => s.startsWith(q)).slice(0, 10);
  },
  onSelect: (val) => {
    // Whatever is returned here is set in the input box.
    return val;
  }
});

4. You can combine multiple suggestion arrays into a JS object and render the results in HTML.

const COLORS = ['#DAA520', '#228B22', '#8B4513'];
const EMOJIS = ['😀', '😍', '🐱'];
autocomp(document.querySelector("#example"), {
  onQuery: async (val) => {
    const q = val.trim().toLowerCase();
    const out = suggestions.filter(s => s.startsWith(q)).slice(0, 10);
    // Results are objects:
    // [{fruit: "apple", color: "..", emoji: ".."} ...]
    return out.map(w => ({
      fruit: w,
      color: COLORS[Math.floor(Math.random() * COLORS.length)],
      emoji: EMOJIS[Math.floor(Math.random() * EMOJIS.length)],
    }))
  },
  onSelect: (o) => {
    document.querySelector("#title").innerHTML = `<span style="color: ${o.color}">${o.emoji} ${o.fruit}</span>`;
    document.querySelector("#object").value = o.fruit;
    // Whatever is returned here is set in the input box.
    return o.fruit;
  },
  // If this callback is set, every search item (string or object) is passed to this function and its return
  // value (DOMNode), is appended to the results box.
  onRender: (o) => {
    const dot = document.createElement("span");
    dot.style = `width: 15px; height: 15px; border-radius: 100%; display: inline-block; margin-right: 10px; float: right; background: ${o.color}`;
    const d = document.createElement("span");
    d.appendChild(dot);
    d.appendChild(document.createTextNode(o.emoji + " "));
    d.appendChild(document.createTextNode(o.fruit));
    return d;
  }
});

You Might Be Interested In:


Leave a Reply