JavaScript APIs

Autocomplete

The JavaScript API for the Autocomplete component.

The mod.autocomplete() method automatically attaches event listeners for the specified HTML element (a <div class="mod-autocomplete"></div> tag) and handles search and keyboard events for the element.

Method API

// Using mod(-plus).iife.min.js
window.mod.autocomplete(element: HTMLElement, options: object);

// Using mod(-plus).esm.min.js
import { autocomplete } from 'path/to/mod(-plus).esm.min.js';
autocomplete(element: HTMLElement, options: object);

Usage Examples

Use the following usage examples to guide your implementation.

Examples Use Global JavaScript

For simplicity, all usage examples demonstrate usage with Mod's global JavaScript library (mod(-plus).iife.min.js). All documented behavior is identical in the ESM variant of Mod's JavaScript library.

Autocomplete HTML

<div class="mod-autocomplete">
  <div class="mod-autocomplete-icon">
    <i class="mod-icon-search"></i>
  </div>
  <input type="text" class="mod-input" placeholder="Type a fruit..." />
  <div class="mod-autocomplete-dropdown">
    <ul></ul>
  </div>
</div>

Autocomplete JavaScript

const element = document.body.querySelector('.mod-autocomplete');
window.mod.autocomplete(element, {
  items: [
    {"id":"7f1c8e9d6b3a54d2","name":"Apple"},
    {"id":"2c5b1e8a9d4f0h6g","name":"Banana"},
    {"id":"8a1b2c3d4e5f6g7h","name":"Orange"},
    {"id":"1a2b3c4d5e6f7g8h","name":"Mango"},
    {"id":"9a8b7c6d5e4f3g2h","name":"Pineapple"},
    {"id":"1q2w3e4r5t6y7u8i","name":"Grape"},
    {"id":"9o0p1q2w3e4r5t6y","name":"Kiwi"},
    {"id":"7u8i9o0p1q2w3e4r","name":"Strawberry"},
    {"id":"5t6y7u8i9o0p1q2w","name":"Blueberry"},
    {"id":"3e4r5t6y7u8i9o0p","name":"Peach"}
  ],
  searchable_keys: ['name'],
  events: {
    on_select_item: (item_id = '', event_object = {}, node_object = {}) => {
      console.log('on_select_item', { item_id, node_object, event_object });
    },
    on_clear_search: () => {
      console.log('on_clear_search');
    }
  }
});

API

element HTMLElement required
The container element that contains the input and dropdown elements with the required structure.
options object required
Configuration options for the autocomplete functionality.
items array required
Array of items to be searched through. Each item should have at least a 'name' property.
searchable_keys array required
Array of object keys to search through in the items array.
min_characters number
Minimum number of characters required before showing search results.
max_items number
Maximum number of items to show in the dropdown.
events object
Event callbacks for various autocomplete actions.
on_select_item function
Callback function when an item is selected. Receives (item_id, event, selected_node) as parameters.
on_clear_search function
Callback function when the search is cleared.