### Quick Start Example
Source: https://github.com/tarekraafat/autocomplete.js/blob/master/llms-full.txt
A basic example demonstrating how to implement autoComplete.js in an HTML page.
```APIDOC
## Quick Start
```html
```
```
--------------------------------
### Basic autoComplete.js Implementation
Source: https://github.com/tarekraafat/autocomplete.js/blob/master/llms-full.txt
A quick start example demonstrating the basic setup of autoComplete.js with an input field and data source.
```html
```
--------------------------------
### Installation
Source: https://github.com/tarekraafat/autocomplete.js/blob/master/llms-full.txt
Instructions for installing autoComplete.js using various package managers and CDNs.
```APIDOC
## Installation
### npm
```bash
npm i @tarekraafat/autocomplete.js
```
### yarn
```bash
yarn add @tarekraafat/autocomplete.js
```
### CDN (jsDelivr)
```html
```
### CDN (cdnjs)
```html
```
### CDN (unpkg)
```html
```
### ES module import
```js
import autoComplete from "@tarekraafat/autocomplete.js";
```
### CommonJS require
```js
const autoComplete = require("@tarekraafat/autocomplete.js");
```
```
--------------------------------
### Install with npm
Source: https://github.com/tarekraafat/autocomplete.js/blob/master/docs/installation.md
Use npm to install the Autocomplete.js package. This is the recommended method for most projects.
```shell
npm i @tarekraafat/autocomplete.js
```
--------------------------------
### Install via Package Manager
Source: https://github.com/tarekraafat/autocomplete.js/blob/master/README.md
Use npm or Yarn to add the library to your project dependencies.
```shell
npm i @tarekraafat/autocomplete.js
```
```shell
yarn add @tarekraafat.js
```
--------------------------------
### start(query)
Source: https://github.com/tarekraafat/autocomplete.js/blob/master/docs/configuration.md
Triggers the search process for the autocomplete instance.
```APIDOC
## start(query)
### Description
Runs the core search function which fetches data, matches results, and renders the list if enabled.
### Parameters
- **query** (String) - Optional - The search query string. If not provided, the current input value is used.
### Request Example
autoCompleteJS.start("tea");
```
--------------------------------
### Basic Setup with HTML and JavaScript
Source: https://context7.com/tarekraafat/autocomplete.js/llms.txt
Integrate autoComplete.js into an HTML page by including the script and initializing it with basic configuration.
```html
```
--------------------------------
### Programmatically Trigger Search with start(query)
Source: https://context7.com/tarekraafat/autocomplete.js/llms.txt
The start() method programmatically triggers the autocomplete search. You can optionally pass a query string to search for specific terms. It can also be used to open the list on focus if the input has a value.
```javascript
const autoCompleteJS = new autoComplete({
selector: "#autoComplete",
data: {
src: ["Pizza", "Burger", "Sushi"]
}
});
// Trigger search with current input value
autoCompleteJS.start();
// Trigger search with specific query
autoCompleteJS.start("piz");
// Open list on focus
document.querySelector("#autoComplete").addEventListener("focus", () => {
if (autoCompleteJS.input.value.length) {
autoCompleteJS.start();
}
});
```
--------------------------------
### Initialize Google Analytics
Source: https://github.com/tarekraafat/autocomplete.js/blob/master/docs/demo/index.html
Standard Google Analytics tracking code setup.
```javascript
window.dataLayer = window.dataLayer || []; function gtag() { dataLayer.push(arguments); } gtag("js", new Date()); gtag("config", "G-H6GSXJ5HZZ");
```
--------------------------------
### Initialize autoComplete.js
Source: https://github.com/tarekraafat/autocomplete.js/blob/master/llms.txt
Basic setup including an input element and the JavaScript configuration for a simple data source.
```html
```
--------------------------------
### Basic autocomplete initialization
Source: https://github.com/tarekraafat/autocomplete.js/blob/master/docs/how-to-guides.md
Standard setup for an autocomplete input field.
```javascript
const autoCompleteJS_03 = new autoComplete({
selector: "#autoComplete_03",
placeHolder,
data,
resultsList,
resultItem,
events: {
input: {
selection(event) {
const selection = event.detail.selection.value;
autoCompleteJS_03.input.value = selection;
}
}
}
});
```
--------------------------------
### Install autoComplete.js via Package Manager
Source: https://github.com/tarekraafat/autocomplete.js/blob/master/llms.txt
Use npm or yarn to add the library to your project dependencies.
```bash
npm i @tarekraafat/autocomplete.js
```
```bash
yarn add @tarekraafat/autocomplete.js
```
--------------------------------
### Install with Yarn
Source: https://github.com/tarekraafat/autocomplete.js/blob/master/docs/installation.md
Use Yarn to add the Autocomplete.js package to your project dependencies.
```shell
yarn add @tarekraafat/autocomplete.js
```
--------------------------------
### Basic autocomplete.js Implementation
Source: https://github.com/tarekraafat/autocomplete.js/blob/master/docs/usage.md
A minimal setup including the required CSS and JS files with a basic data source and selection event.
```html
```
--------------------------------
### Include autoComplete.js via CDN
Source: https://github.com/tarekraafat/autocomplete.js/blob/master/README.md
Add the library script and stylesheet to your HTML document to get started.
```html
```
```html
```
--------------------------------
### Start autocomplete search
Source: https://github.com/tarekraafat/autocomplete.js/blob/master/docs/configuration.md
Triggers the search process with an optional query string.
```js
autoCompleteJS.start("tea");
```
--------------------------------
### Show all results on focus
Source: https://github.com/tarekraafat/autocomplete.js/blob/master/docs/faq.md
Set the threshold to 0 and trigger the start method within the input focus event.
```js
const autoCompleteJS = new autoComplete({
data: {
src: ["Apple", "Banana", "Cherry"],
cache: true,
},
threshold: 0,
events: {
input: {
focus() {
autoCompleteJS.start();
},
},
},
});
```
--------------------------------
### Configure Custom Event Handlers with 'events'
Source: https://context7.com/tarekraafat/autocomplete.js/llms.txt
Use the 'events' option to add custom handlers or override default behaviors for input and list elements. The example shows how to open the list on input focus if a value exists and log when the results list is scrolled.
```javascript
const autoCompleteJS = new autoComplete({
selector: "#autoComplete",
data: {
src: ["Pizza", "Burger", "Sushi"]
},
events: {
input: {
focus: (event) => {
// Open list on focus if there's a value
if (autoCompleteJS.input.value.length) {
autoCompleteJS.start();
}
},
selection: (event) => {
const selection = event.detail.selection.value;
autoCompleteJS.input.value = selection;
}
},
list: {
scroll: (event) => {
console.log("Results list scrolled");
}
}
}
});
```
--------------------------------
### Configure Query Manipulation: Basic Sanitization
Source: https://context7.com/tarekraafat/autocomplete.js/llms.txt
Sanitize input values before searching using the query option. This example trims whitespace and normalizes spaces.
```javascript
const autoCompleteJS = new autoComplete({
selector: "#autoComplete",
data: {
src: ["Pizza", "Burger", "Sushi"]
},
query: (input) => {
// Remove extra spaces and convert to lowercase
return input.trim().replace(/\s+/g, " ");
}
});
```
--------------------------------
### Configure Result Item Customization
Source: https://context7.com/tarekraafat/autocomplete.js/llms.txt
Customize individual result items, including highlighting matched text and adding custom attributes, using the resultItem option. This example shows custom styling and displaying category information.
```javascript
const autoCompleteJS = new autoComplete({
selector: "#autoComplete",
data: {
src: [
{ name: "Pizza", category: "Food" },
{ name: "Burger", category: "Food" },
{ name: "Sushi", category: "Food" }
],
keys: ["name"]
},
resultItem: {
tag: "li",
class: "autoComplete_result",
highlight: "autoComplete_highlight",
selected: "autoComplete_selected",
element: (item, data) => {
// Customize each result item
item.style = "display: flex; justify-content: space-between;";
item.innerHTML = `
${data.match}
${data.value.category}
`;
}
}
});
```
--------------------------------
### Filter and Sort Results with 'data.filter'
Source: https://context7.com/tarekraafat/autocomplete.js/llms.txt
The 'data.filter' option allows you to filter and sort matching results before they are displayed. This example filters results to only show items starting with the input value and then sorts them alphabetically.
```javascript
const autoCompleteJS = new autoComplete({
selector: "#autoComplete",
data: {
src: ["Pizza", "Burger", "Sushi", "Pasta", "Salad"],
filter: (list) => {
// Filter to only show results that start with the query
const results = list.filter((item) => {
const inputValue = autoCompleteJS.input.value.toLowerCase();
const itemValue = item.value.toLowerCase();
return itemValue.startsWith(inputValue);
});
// Sort alphabetically
return results.sort((a, b) => a.value.localeCompare(b.value));
}
}
});
```
--------------------------------
### Filter Results to Start With Input Value
Source: https://github.com/tarekraafat/autocomplete.js/blob/master/docs/how-to-guides.md
This configuration option filters the search results to only include items that start with the current input value. It converts both the input and item values to lowercase for case-insensitive matching.
```javascript
// autoComplete.js Config Options
filter: (list) => {
const results = list.filter((item) => {
const inputValue = autoCompleteJS.input.value.toLowerCase();
const itemValue = item.value.toLowerCase();
if (itemValue.startsWith(inputValue)) {
return item.value;
}
});
return results;
},
```
--------------------------------
### init()
Source: https://github.com/tarekraafat/autocomplete.js/blob/master/docs/configuration.md
Initializes the autocomplete instance by setting up the input field, wrapper, list, data caching, and event listeners.
```APIDOC
## init()
### Description
Runs the core initialization function which sets up input attributes, creates the wrapper and list elements, caches data, attaches event listeners, and emits the init event.
### Request Example
autoCompleteJS.init();
```
--------------------------------
### Initialize autoComplete.js and Listen for 'init' Event
Source: https://context7.com/tarekraafat/autocomplete.js/llms.txt
Initialize autoComplete.js with basic configuration and listen for the 'init' event to confirm the engine is ready. The event detail provides initialization data.
```javascript
const autoCompleteJS = new autoComplete({
selector: "#autoComplete",
data: {
src: ["Pizza", "Burger", "Sushi"]
}
});
document.querySelector("#autoComplete").addEventListener("init", (event) => {
console.log("autoComplete.js initialized");
console.log(event.detail);
});
```
--------------------------------
### new autoComplete(config)
Source: https://github.com/tarekraafat/autocomplete.js/blob/master/llms.txt
Initializes the autoComplete instance with a configuration object.
```APIDOC
## new autoComplete(config)
### Description
Initializes a new instance of the autoComplete library on a specified input element.
### Parameters
#### Request Body
- **selector** (String/Function) - Optional - Points to the input element. Default: "#autoComplete"
- **data.src** (Array/Function) - Required - The data source to search.
- **data.keys** (Array) - Required - Which keys to search (for object arrays).
- **placeHolder** (String) - Optional - Placeholder text for the input.
- **threshold** (Integer) - Optional - Minimum characters to trigger search. Default: 1
- **debounce** (Integer) - Optional - Delay in ms after typing. Default: 0
- **searchEngine** (String/Function) - Optional - "strict", "loose", or custom function. Default: "strict"
### Request Example
const autoCompleteJS = new autoComplete({
placeHolder: "Search...",
data: {
src: ["Apple", "Banana"],
cache: true
}
});
```
--------------------------------
### Initialize autocomplete instance
Source: https://github.com/tarekraafat/autocomplete.js/blob/master/docs/configuration.md
Runs the core initialization tasks including attribute setting, wrapper creation, and event attachment.
```js
autoCompleteJS.init();
```
--------------------------------
### Initialize multiple instances
Source: https://github.com/tarekraafat/autocomplete.js/blob/master/docs/faq.md
Create separate instances with unique selectors to support multiple autocomplete inputs on one page.
```js
const searchOne = new autoComplete({
selector: "#search-one",
data: { src: ["Apple", "Banana"] },
});
const searchTwo = new autoComplete({
selector: "#search-two",
data: { src: ["Red", "Blue", "Green"] },
});
```
--------------------------------
### Initialize autoComplete.js Instance
Source: https://github.com/tarekraafat/autocomplete.js/blob/master/docs/usage.md
Create a new instance of the engine after the library is loaded.
```html
```
```javascript
// CommonJS
const autoComplete = require("@tarekraafat/autocomplete.js");
const autoCompleteJS = new autoComplete({ config });
/* OR */
// ES6 modules
import autoComplete from "@tarekraafat/autocomplete.js";
const autoCompleteJS = new autoComplete({ config });
```
--------------------------------
### Set Minimum Search Threshold
Source: https://github.com/tarekraafat/autocomplete.js/blob/master/docs/configuration.md
Configure the minimum number of characters the user must type before the autoComplete.js engine starts searching.
```javascript
threshold: 2,
```
--------------------------------
### autoComplete.js Configuration Options
Source: https://github.com/tarekraafat/autocomplete.js/blob/master/docs/configuration.md
Configuration options for initializing the autoComplete.js instance.
```APIDOC
## autoComplete.js Configuration
### Description
Configuration options used to define the behavior of the autoComplete.js instance.
### Parameters
- **name** (String) - Optional - Global instance naming. Default: "autoComplete"
- **selector** (String|Function) - Optional - Input element selector. Default: "#autoComplete"
- **wrapper** (Boolean) - Optional - Whether to render a wrapper div. Default: true
- **data** (Object) - Required - Data source configuration.
- **src** (Array|Function) - Required - Data source.
- **keys** (Array) - Required (if src is Array of Objects) - Keys to search.
- **cache** (Boolean) - Optional - Enable caching. Default: false
- **trigger** (Function) - Optional - Logic to trigger the engine.
- **query** (Function) - Optional - Query interception and manipulation.
- **placeHolder** (String) - Optional - Input placeholder text.
- **threshold** (Integer) - Optional - Minimum characters to start. Default: 1
- **debounce** (Integer) - Optional - Delay in milliseconds. Default: 0
- **searchEngine** (String|Function) - Optional - Search mode ("strict"|"loose") or custom function. Default: "strict"
- **diacritics** (Boolean) - Optional - Enable diacritics support. Default: false
```
--------------------------------
### Download Latest Release
Source: https://github.com/tarekraafat/autocomplete.js/blob/master/docs/installation.md
Instructions for obtaining the latest release package directly from GitHub, including the JavaScript, CSS, and search icon files.
```text
1. [Download](https://github.com/TarekRaafat/autoComplete.js/releases/latest) latest release package
2. Get `javascript` file from `/dist/js` folder
3. Get `stylesheet` file from `/dist/css` folder
4. Get `search` icon from `/dist/css/images` folder
```
--------------------------------
### Handle User Selection Event
Source: https://github.com/tarekraafat/autocomplete.js/blob/master/llms-full.txt
The 'selection' event is fired when a user selects an item from the results list via Enter, Tab, or mouse click. This example updates the input field with the selected value.
```javascript
document.querySelector("#autoComplete").addEventListener("selection", function (event) {
const feedback = event.detail;
autoCompleteJS.input.value = feedback.selection.value;
console.log("Selected:", feedback.selection);
});
```
--------------------------------
### Configure Data Source (Array of Objects)
Source: https://github.com/tarekraafat/autocomplete.js/blob/master/docs/configuration.md
Use an array of objects as the data source and specify the key to be searched within each object.
```javascript
data: {
src: [
{ "food": "Sauce - Thousand Island" },
{ "food": "Wild Boar - Tenderloin" },
{ "food": "Goat - Whole Cut" }
],
// Data source 'Object' key to be searched
keys: ["food"]
},
```
--------------------------------
### Initialize with Async Data Source
Source: https://github.com/tarekraafat/autocomplete.js/blob/master/llms-full.txt
Configure autocomplete.js to fetch data asynchronously from a specified URL. Includes error handling and disabling cache.
```javascript
const autoCompleteJS = new autoComplete({
data: {
src: async (query) => {
try {
const response = await fetch(`https://api.example.com/search?q=${query}`);
const data = await response.json();
return data;
} catch (error) {
return error;
}
},
keys: ["name"],
cache: false,
},
debounce: 300,
resultItem: {
highlight: true
}
});
```
--------------------------------
### Configure Data Source (Function with Cache)
Source: https://github.com/tarekraafat/autocomplete.js/blob/master/docs/configuration.md
Utilize a function to dynamically fetch data and enable caching for improved performance. The function receives the query and should return an array of results.
```javascript
data: {
src: (query) => { ... },
// Data source 'Object' key to be searched
keys: ["food"],
cache: true
},
```
--------------------------------
### Initialize autoComplete.js with Focus Trigger
Source: https://github.com/tarekraafat/autocomplete.js/blob/master/docs/how-to-guides.md
Sets up an autoComplete instance that triggers the search process immediately upon input focus, with no limit on the number of results.
```javascript
const autoCompleteJS_07 = new autoComplete({
selector: "#autoComplete_07",
placeHolder,
data,
threshold: 0,
resultsList: {
maxResults: undefined
},
resultItem,
events: {
input: {
focus (event) {
autoCompleteJS_07.start();
},
selection (event) {
const selection = event.detail.selection.value;
autoCompleteJS_07.input.value = selection;
}
},
},
});
```
--------------------------------
### Navigate Results List with next(), previous(), goTo(index)
Source: https://context7.com/tarekraafat/autocomplete.js/llms.txt
These methods provide programmatic navigation through the results list. You can move to the next or previous result, or directly to a specific index. Custom keyboard navigation can also be implemented.
```javascript
const autoCompleteJS = new autoComplete({
selector: "#autoComplete",
data: {
src: ["Pizza", "Burger", "Sushi"]
}
});
// Navigate to next result
autoCompleteJS.next();
// Navigate to previous result
autoCompleteJS.previous();
// Navigate to specific index (0-based)
autoCompleteJS.goTo(2); // Go to third result
// Custom keyboard navigation
document.addEventListener("keydown", (event) => {
if (event.key === "j") autoCompleteJS.next();
if (event.key === "k") autoCompleteJS.previous();
});
```
--------------------------------
### API: init() and unInit()
Source: https://context7.com/tarekraafat/autocomplete.js/llms.txt
The init() method initializes the autoComplete.js instance, setting up event listeners and DOM elements. The unInit() method removes all event listeners for cleanup.
```APIDOC
## API: init() and unInit()
The init() method initializes the autoComplete.js instance, setting up event listeners and DOM elements. The unInit() method removes all event listeners for cleanup.
### Example Usage
```javascript
const autoCompleteJS = new autoComplete({
selector: "#autoComplete",
data: {
src: ["Pizza", "Burger", "Sushi"]
}
});
// Re-initialize after configuration change
autoCompleteJS.unInit();
autoCompleteJS.data.src = ["Coffee", "Tea", "Juice"];
autoCompleteJS.init();
// Clean up when component is destroyed
function cleanup() {
autoCompleteJS.unInit();
}
```
```
--------------------------------
### Include autoComplete.js via unpkg CDN
Source: https://github.com/tarekraafat/autocomplete.js/blob/master/llms-full.txt
Link to the autoComplete.js JavaScript and CSS files using the unpkg CDN.
```html
```
--------------------------------
### Import autoComplete.js Library
Source: https://github.com/tarekraafat/autocomplete.js/blob/master/docs/usage.md
Include the library via CDN or module import systems.
```html
```
```javascript
// CommonJS
const autoComplete = require("@tarekraafat/autocomplete.js");
/* OR */
// ES6 modules
import autoComplete from "@tarekraafat/autocomplete.js";
```
--------------------------------
### Listen for Results List Open Event
Source: https://github.com/tarekraafat/autocomplete.js/blob/master/llms-full.txt
Use the 'open' event to run code immediately after the results list becomes visible.
```javascript
document.querySelector("#autoComplete").addEventListener("open", function (event) {
console.log("Results list opened");
});
```
--------------------------------
### Include via UNPKG CDN
Source: https://github.com/tarekraafat/autocomplete.js/blob/master/docs/installation.md
Link to the Autocomplete.js JavaScript and CSS files hosted on UNPKG. Replace {{version}} with the desired version number.
```html
```
```html
```
--------------------------------
### API: Navigation - next(), previous(), goTo(index)
Source: https://context7.com/tarekraafat/autocomplete.js/llms.txt
These methods provide programmatic navigation through the results list.
```APIDOC
## API: Navigation - next(), previous(), goTo(index)
These methods provide programmatic navigation through the results list.
### Example Usage
```javascript
const autoCompleteJS = new autoComplete({
selector: "#autoComplete",
data: {
src: ["Pizza", "Burger", "Sushi"]
}
});
// Navigate to next result
autoCompleteJS.next();
// Navigate to previous result
autoCompleteJS.previous();
// Navigate to specific index (0-based)
autoCompleteJS.goTo(2); // Go to third result
// Custom keyboard navigation
document.addEventListener("keydown", (event) => {
if (event.key === "j") autoCompleteJS.next();
if (event.key === "k") autoCompleteJS.previous();
});
```
```
--------------------------------
### Include Stylesheet
Source: https://github.com/tarekraafat/autocomplete.js/blob/master/docs/usage.md
Add the required CSS file to the document head.
```html
```
```html
```
--------------------------------
### Configure Data Source: Array of Objects
Source: https://context7.com/tarekraafat/autocomplete.js/llms.txt
Use an array of objects for the data source and specify the key to use for selections. Caching is enabled.
```javascript
// Array of objects with key selection
const autoCompleteJS = new autoComplete({
selector: "#autoComplete",
data: {
src: [
{ food: "Sauce - Thousand Island", category: "Condiment" },
{ food: "Wild Boar - Tenderloin", category: "Meat" },
{ food: "Goat - Whole Cut", category: "Meat" }
],
keys: ["food"],
cache: true
}
});
```
--------------------------------
### Configure Data Source: Array of Strings
Source: https://context7.com/tarekraafat/autocomplete.js/llms.txt
Initialize autoComplete.js with a simple array of strings as the data source. Caching is enabled by default.
```javascript
// Array of strings
const autoCompleteJS = new autoComplete({
selector: "#autoComplete",
data: {
src: ["Sauce - Thousand Island", "Wild Boar - Tenderloin", "Goat - Whole Cut"],
cache: true
}
});
```
--------------------------------
### Initialize autoComplete.js with custom event handling
Source: https://github.com/tarekraafat/autocomplete.js/blob/master/docs/how-to-guides.md
Configures the autocomplete instance with custom focus and selection event logic.
```javascript
const autoCompleteJS_01 = new autoComplete({
selector: "#autoComplete_01",
placeHolder,
data,
resultsList,
resultItem,
events: {
input: {
focus() {
if (autoCompleteJS_01.input.value.length) autoCompleteJS_01.start();
},
selection(event) {
const selection = event.detail.selection.value;
autoCompleteJS_01.input.value = selection;
}
},
},
});
```
--------------------------------
### API: open(), close(), and isOpen
Source: https://context7.com/tarekraafat/autocomplete.js/llms.txt
The open() and close() methods control the results list visibility, and isOpen property indicates current state.
```APIDOC
## API: open(), close(), and isOpen
The open() and close() methods control the results list visibility, and isOpen property indicates current state.
### Example Usage
```javascript
const autoCompleteJS = new autoComplete({
selector: "#autoComplete",
data: {
src: ["Pizza", "Burger", "Sushi"]
}
});
// Programmatically open/close list
document.querySelector("#openBtn").addEventListener("click", () => {
autoCompleteJS.open();
});
document.querySelector("#closeBtn").addEventListener("click", () => {
autoCompleteJS.close();
});
// Check if list is open
if (autoCompleteJS.isOpen) {
console.log("Results list is visible");
}
```
```
--------------------------------
### Input and Search Behavior
Source: https://github.com/tarekraafat/autocomplete.js/blob/master/llms-full.txt
Configure input placeholder, search threshold, debouncing, and search engine.
```APIDOC
## Input and Search Behavior
### Description
Configure input placeholder, search threshold, debouncing, and search engine.
### `placeHolder` (String)
- Optional
- Default: none
- Placeholder text for the input element.
### `threshold` (Integer)
- Optional
- Default: `1`
- Minimum number of characters required before triggering a search. Set to `0` to allow triggering with an empty input.
### `debounce` (Integer)
- Optional
- Default: `0`
- Delay in milliseconds after typing stops before triggering a search. Useful for reducing API calls with async data sources.
```javascript
debounce: 300, // Wait 300ms after last keystroke
```
### `searchEngine` (String or Function)
- Optional
- Default: `"strict"`
- Specifies the search algorithm. Built-in modes include `"strict"` (substring matching) and `"loose"` (scattered character matching). Can also be a custom function.
```javascript
searchEngine: (query, record) => {
// Return the record string if it matches, or undefined if not
if (record.toLowerCase().startsWith(query.toLowerCase())) {
return record;
}
},
```
```
--------------------------------
### Initialize and Clean Up with init() and unInit()
Source: https://context7.com/tarekraafat/autocomplete.js/llms.txt
Use init() to initialize the autoComplete.js instance and unInit() to remove all event listeners for cleanup. This is useful for re-initializing after configuration changes or when destroying the component.
```javascript
const autoCompleteJS = new autoComplete({
selector: "#autoComplete",
data: {
src: ["Pizza", "Burger", "Sushi"]
}
});
// Re-initialize after configuration change
autoCompleteJS.unInit();
autoCompleteJS.data.src = ["Coffee", "Tea", "Juice"];
autoCompleteJS.init();
// Clean up when component is destroyed
function cleanup() {
autoCompleteJS.unInit();
}
```
--------------------------------
### Configure autoComplete.js Instance
Source: https://github.com/tarekraafat/autocomplete.js/blob/master/docs/usage.md
Define the configuration object, ensuring the data.src property is provided.
```javascript
// API Basic Configuration Object
{
placeHolder: "Search for Food...",
data: {
src: ["Sauce - Thousand Island", "Wild Boar - Tenderloin", "Goat - Whole Cut"]
},
resultItem: {
highlight: true,
}
}
```
```javascript
// API Advanced Configuration Object
{
selector: "#autoComplete",
placeHolder: "Search for Food...",
data: {
src: ["Sauce - Thousand Island", "Wild Boar - Tenderloin", "Goat - Whole Cut"],
cache: true,
},
resultsList: {
element: (list, data) => {
if (!data.results.length) {
// Create "No Results" message element
const message = document.createElement("div");
// Add class to the created element
message.setAttribute("class", "no_result");
// Add message text content
message.innerHTML = `Found No Results for "${data.query}"`;
// Append message element to the results list
list.prepend(message);
}
},
noResults: true,
},
resultItem: {
highlight: true,
}
}
```
--------------------------------
### Async Data Source Initialization
Source: https://github.com/tarekraafat/autocomplete.js/blob/master/llms.txt
Initialize Autocomplete.js with an asynchronous data source using fetch. Ensure the API endpoint is correctly specified and error handling is in place. The `keys` property specifies which data field to use for matching.
```javascript
const autoCompleteJS = new autoComplete({
data: {
src: async (query) => {
try {
const response = await fetch(`https://api.example.com/search?q=${query}`);
const data = await response.json();
return data;
} catch (error) {
return error;
}
},
keys: ["name"],
cache: false,
},
resultItem: {
highlight: true
}
});
```
--------------------------------
### Configure autoComplete.js with History and Selection Handling
Source: https://github.com/tarekraafat/autocomplete.js/blob/master/docs/how-to-guides.md
Initializes an autoComplete instance that tracks user selections in a history array and updates the input field accordingly.
```javascript
recentItem.setAttribute("style", "display: flex; margin: .2rem; color: rgba(0, 0, 0, .2);");
recentItem.innerHTML = item;
historyBlock.append(recentItem);
});
const separator = document.createElement("hr");
separator.setAttribute("style", "margin: 5px 0 0 0;");
historyBlock.append(separator);
list.prepend(historyBlock);
}
},
},
resultItem,
events: {
input: {
selection(event) {
const feedback = event.detail;
const input = autoCompleteJS_05.input;
// Get selected Value
const selection = feedback.selection.value;
// Add selected value to "history" array
history.push(selection);
autoCompleteJS_05.input.value = selection;
}
}
}
});
```
--------------------------------
### ES6 Module and CommonJS Imports
Source: https://context7.com/tarekraafat/autocomplete.js/llms.txt
Demonstrates how to import autoComplete.js using ES6 modules and CommonJS syntax. Includes basic configuration for creating an instance with search suggestions.
```javascript
// ES6 module import
import autoComplete from "@tarekraafat/autocomplete.js";
// CommonJS import
const autoComplete = require("@tarekraafat/autocomplete.js");
// Create instance
const autoCompleteJS = new autoComplete({
selector: "#autoComplete",
placeHolder: "Search...",
data: {
src: ["Pizza", "Burger", "Sushi"],
cache: true
},
resultItem: {
highlight: true
},
events: {
input: {
selection: (event) => {
autoCompleteJS.input.value = event.detail.selection.value;
}
}
}
});
```
--------------------------------
### Listen for init event
Source: https://github.com/tarekraafat/autocomplete.js/blob/master/docs/configuration.md
The 'init' event fires after the autocomplete engine has been successfully initialized. The event detail object contains initialization data.
```javascript
document.querySelector("#autoComplete").addEventListener("init", function (event) {
// "event.detail" carries the returned data values
console.log(event);
});
```
--------------------------------
### Configure Data Source (Array of Strings)
Source: https://github.com/tarekraafat/autocomplete.js/blob/master/docs/configuration.md
Provide a simple array of strings as the data source for autoComplete.js.
```javascript
data: {
src: ["Sauce - Thousand Island", "Wild Boar - Tenderloin", "Goat - Whole Cut"]
},
```
--------------------------------
### Configure autoComplete.js Documentation
Source: https://github.com/tarekraafat/autocomplete.js/blob/master/docs/index.html
Initializes the Docsify configuration object for the autoComplete.js documentation site.
```javascript
const date = new Date().getFullYear(); window.$docsify = { // GENERAL // ----------------------------------------------------------------- name: "autoComplete.js", logo: "./img/autoComplete.js.svg", repo: "https://github.com/TarekRaafat/autoComplete.js", homepage: "index.md", themeColor: "#64CEAA", loadSidebar: true, autoHeader: true, onlyCover: true, notFoundPage: true, // NAVIGATION // ----------------------------------------------------------------- auto2top: true, maxLevel: 6, subMaxLevel: 4, externalLinkTarget: "\_blank", // PLUGINS // ----------------------------------------------------------------- executeScript: true, ga: "G-H6GSXJ5HZZ", search: { placeholder: "Search...", maxAge: 86400000, depth: 6, noData: "No results found!", hideOtherSidebarContent: true, }, tabs: { persist: true, sync: true, theme: "classic", tabComments: true, tabHeadings: true }, pagination: { crossChapter: true, crossChapterText: true, }, mustache: { data: ["../package.json", { minVersion: "10.2", version: "10.2.10" }] } }
```
--------------------------------
### Control List Visibility with open(), close(), and isOpen
Source: https://context7.com/tarekraafat/autocomplete.js/llms.txt
Use the open() and close() methods to programmatically control the results list visibility. The isOpen property indicates the current state of the results list.
```javascript
const autoCompleteJS = new autoComplete({
selector: "#autoComplete",
data: {
src: ["Pizza", "Burger", "Sushi"]
}
});
// Programmatically open/close list
document.querySelector("#openBtn").addEventListener("click", () => {
autoCompleteJS.open();
});
document.querySelector("#closeBtn").addEventListener("click", () => {
autoCompleteJS.close();
});
// Check if list is open
if (autoCompleteJS.isOpen) {
console.log("Results list is visible");
}
```
--------------------------------
### Show All Results on Focus
Source: https://github.com/tarekraafat/autocomplete.js/blob/master/llms.txt
Configure the input to display all results when it gains focus by setting `threshold` to 0 and calling `autoCompleteJS.start()` within the `focus` event handler. Caching is enabled for performance.
```javascript
const autoCompleteJS = new autoComplete({
data: {
src: ["Apple", "Banana", "Cherry", "Date", "Elderberry"],
cache: true,
},
resultItem: {
highlight: true
},
events: {
input: {
focus() {
autoCompleteJS.start();
},
},
},
threshold: 0,
});
```
--------------------------------
### Instance Methods
Source: https://github.com/tarekraafat/autocomplete.js/blob/master/llms.txt
Methods available on an initialized autocomplete.js instance to control behavior and navigation.
```APIDOC
## Instance Methods
### Description
Methods to programmatically control the autocomplete instance.
### Methods
- **init()**: Re-initialize the instance.
- **start(query)**: Trigger search with optional custom query string.
- **unInit()**: Destroy instance, remove events and DOM elements.
- **open()**: Open the results list.
- **close()**: Close the results list.
- **goTo(index)**: Navigate to a specific result by index.
- **next()**: Navigate to the next result.
- **previous()**: Navigate to the previous result.
- **select(index)**: Select a result by index (defaults to current cursor).
- **search(query, record, options)**: Direct access to the search engine.
```
--------------------------------
### Lifecycle Methods
Source: https://github.com/tarekraafat/autocomplete.js/blob/master/docs/configuration.md
Methods for managing the component state.
```APIDOC
## Lifecycle Methods
### close()
Closes the resultsList if opened.
### unInit()
Removes all event listeners on the events list.
```
--------------------------------
### Navigate to specific result by index
Source: https://github.com/tarekraafat/autocomplete.js/blob/master/docs/configuration.md
Use the goTo method to navigate to a specific result item in the list using its index. The index is zero-based.
```javascript
autoCompleteJS.goTo(1);
```
--------------------------------
### Listen for Initialization Complete Event
Source: https://github.com/tarekraafat/autocomplete.js/blob/master/llms-full.txt
Use the 'init' event to execute code after autocomplete.js has finished its initialization process.
```javascript
document.querySelector("#autoComplete").addEventListener("init", function (event) {
console.log("autoComplete.js is ready");
});
```
--------------------------------
### Show All Items on Click/Focus
Source: https://context7.com/tarekraafat/autocomplete.js/llms.txt
Configure autoComplete.js to display all available options upon focus or click, without requiring any input. Set `threshold` to 0 and `resultsList.maxResults` to `undefined`.
```javascript
const autoCompleteJS = new autoComplete({
selector: "#autoComplete",
placeHolder: "Click to see all options...",
data: {
src: ["Pizza", "Burger", "Sushi", "Coffee", "Soda", "Fresh Juice"]
},
threshold: 0, // No minimum characters required
resultsList: {
maxResults: undefined // Show all results
},
resultItem: {
highlight: true
},
events: {
input: {
focus: (event) => {
autoCompleteJS.start();
},
selection: (event) => {
autoCompleteJS.input.value = event.detail.selection.value;
}
}
}
});
```
--------------------------------
### Data Source Configuration
Source: https://github.com/tarekraafat/autocomplete.js/blob/master/llms-full.txt
Configure the data source for autocomplete suggestions. Supports static arrays, dynamic functions, and caching.
```APIDOC
## Data Source Configuration (`data`)
### Description
Configure the data source for autocomplete suggestions. Supports static arrays, dynamic functions, and caching.
### Properties
- **`src`** (Array or Function) - Required - The data source. If a function, it receives the current query as a parameter and must return an Array.
- **`keys`** (Array of strings) - Required for object arrays - Specifies which object keys to search within.
- **`cache`** (Boolean) - Optional - Default: `false`. If true, fetches data once at initialization and reuses it. If false, calls `data.src` on every search trigger.
- **`filter`** (Function) - Optional - Receives an Array of matches and must return an Array. Used for custom filtering or sorting before rendering.
### Request Example
```json
{
"data": {
"src": ["Apple", "Banana", "Cherry"],
"keys": ["name", "category"]
}
}
```
### Response Example
```json
{
"data": {
"src": async (query) => {
const response = await fetch(`https://api.example.com/search?q=${query}`);
return await response.json();
},
"keys": ["name"],
"cache": false
}
}
```
```
--------------------------------
### Configuration Options
Source: https://github.com/tarekraafat/autocomplete.js/blob/master/llms-full.txt
Configuration options for customizing the behavior and appearance of autocomplete.js.
```APIDOC
## Configuration Options
### resultItem (optional)
Configuration for each result item element.
- Type: `Object`
Properties:
- `tag`: `String`. Default: `"li"`. HTML tag for each result.
- `id`: `String`. Default: `"autoComplete_result"`. ID prefix (appended with _0, _1, etc.).
- `class`: `String`. CSS class(es) for each result item.
- `element`: `Function(item, data)`. Callback to modify each item before display. `data` contains `{ match, value, key }`.
- `highlight`: `Boolean` or `String`. Default: `false`. Set to `true` to wrap matching characters in `` elements, or provide a CSS class string for the mark elements.
- `selected`: `String`. CSS class(es) added to the item currently highlighted via keyboard navigation.
### submit (optional)
Controls whether pressing Enter submits the form or is intercepted by autoComplete.js.
- Type: `Boolean`
- Default: `false` (Enter is intercepted and selects the highlighted item)
Set to `true` to allow default Enter behavior (form submission).
### events (optional)
Custom event handlers for the input element and results list. Can add new events or override internal defaults.
- Type: `Object`
- Default internal events:
- input: `input` (triggers search), `keydown` (keyboard navigation), `blur` (closes list)
- list: `mousedown` (prevents blur), `click` (item selection)
```js
events: {
input: {
focus: (event) => {
console.log("Input focused!");
},
},
list: {
scroll: (event) => {
console.log("List scrolled!");
},
},
},
```
If you provide a handler with the same name as an internal event (e.g., `keydown`), your handler replaces the internal one.
```
--------------------------------
### Event: init
Source: https://context7.com/tarekraafat/autocomplete.js/llms.txt
The 'init' event fires after autoComplete.js engine is initialized and ready to use.
```APIDOC
## Event: init
### Description
The `init` event fires after autoComplete.js engine is initialized and ready.
### Event Listener Example
```javascript
const autoCompleteJS = new autoComplete({
selector: "#autoComplete",
data: {
src: ["Pizza", "Burger", "Sushi"]
}
});
document.querySelector("#autoComplete").addEventListener("init", (event) => {
console.log("autoComplete.js initialized");
console.log(event.detail); // Contains initialization details
});
```
### Event Detail
- **object** - Contains details about the initialization.
```
--------------------------------
### Include via JSDELIVR CDN
Source: https://github.com/tarekraafat/autocomplete.js/blob/master/docs/installation.md
Link to the Autocomplete.js JavaScript and CSS files hosted on JSDELIVR. Replace {{version}} with the desired version number.
```html
```
```html
```
--------------------------------
### Show All Results on Input Focus
Source: https://github.com/tarekraafat/autocomplete.js/blob/master/llms-full.txt
Configure autocomplete.js to display all available results when the input field gains focus. This is achieved by setting the 'threshold' to 0 and calling autoCompleteJS.start() in the 'focus' event.
```javascript
const autoCompleteJS = new autoComplete({
data: {
src: ["Apple", "Banana", "Cherry", "Date", "Elderberry"],
cache: true,
},
threshold: 0,
resultItem: {
highlight: true
},
events: {
input: {
focus() {
autoCompleteJS.start();
},
},
},
});
```