### Install Project Dependencies
Source: https://github.com/leaverou/awesomplete/blob/gh-pages/CONTRIBUTING.md
Installs all necessary project dependencies using npm. This command should be run after cloning the repository.
```bash
npm install
```
--------------------------------
### Install Awesomplete via Package Managers
Source: https://github.com/leaverou/awesomplete/blob/gh-pages/README.md
Use yarn or npm to add the library to your project dependencies.
```sh
yarn add awesomplete
```
```sh
npm install awesomplete --save
```
--------------------------------
### Advanced Example: Combobox Dropdown
Source: https://github.com/leaverou/awesomplete/blob/gh-pages/index.html
Example of using Awesomplete to create a combobox dropdown interface.
```APIDOC
## Combobox Dropdown
### Endpoint
N/A (Client-side JavaScript)
### Description
Implements a combobox dropdown where users can type to filter options or click a button to reveal all options.
### Request Example
```html
```
```javascript
var comboplete = new Awesomplete('input.dropdown-input', {
minChars: 0,
});
Awesomplete.$('.dropdown-btn').addEventListener("click", function() {
comboplete.minChars = 0; // Allow showing all items
comboplete.evaluate();
});
```
### Response
N/A (Client-side interaction)
```
--------------------------------
### Install Node.js with Homebrew
Source: https://github.com/leaverou/awesomplete/blob/gh-pages/CONTRIBUTING.md
Installs Node.js on macOS using Homebrew. Ensure Node.js and npm are installed before proceeding.
```bash
brew install node
```
--------------------------------
### Advanced Example: E-mail Autocomplete
Source: https://github.com/leaverou/awesomplete/blob/gh-pages/index.html
Example demonstrating how to create an email autocomplete using a predefined list of domains and a custom data function.
```APIDOC
## E-mail Autocomplete
### Endpoint
N/A (Client-side JavaScript)
### Description
Provides email domain suggestions as the user types an email address.
### Request Example
```html
```
```javascript
new Awesomplete('input[type="email"]', {
list: ["aol.com", "att.net", "comcast.net", "facebook.com", "gmail.com", "gmx.com", "googlemail.com", "google.com", "hotmail.com", "hotmail.co.uk", "mac.com", "me.com", "mail.com", "msn.com", "live.com", "sbcglobal.net", "verizon.net", "yahoo.com", "yahoo.co.uk"],
data: function (text, input) {
return input.slice(0, input.indexOf("@")) + "@" + text;
},
filter: Awesomplete.FILTER_STARTSWITH
});
```
### Response
N/A (Client-side interaction)
```
--------------------------------
### Advanced Example: Multiple Values (Tags)
Source: https://github.com/leaverou/awesomplete/blob/gh-pages/index.html
Example for creating a tag input where values are comma-separated.
```APIDOC
## Multiple Values (Tags)
### Endpoint
N/A (Client-side JavaScript)
### Description
Allows users to input multiple values, typically separated by commas, functioning like tags.
### Request Example
```html
```
```javascript
new Awesomplete('input[data-multiple]', {
filter: function(text, input) {
return Awesomplete.FILTER_CONTAINS(text, input.match(/[^,]*$/)[0]);
},
item: function(text, input) {
return Awesomplete.ITEM(text, input.match(/[^,]*$/)[0]);
},
replace: function(text) {
var before = this.input.value.match(/^.+, *| *$/)[0];
this.input.value = before + text + ", ";
}
});
```
### Response
N/A (Client-side interaction)
```
--------------------------------
### Advanced Example: Ajax Data Fetching
Source: https://github.com/leaverou/awesomplete/blob/gh-pages/index.html
Demonstrates fetching autocomplete suggestions from a remote API (restcountries.eu).
```APIDOC
## Ajax Example (restcountries.eu API)
### Endpoint
N/A (Client-side JavaScript making an AJAX request)
### Description
Fetches a list of countries from the restcountries.eu API and uses them for autocomplete suggestions.
### Request Example
```html
```
```javascript
var ajax = new XMLHttpRequest();
ajax.open("GET", "https://restcountries.eu/rest/v1/lang/fr", true);
ajax.onload = function() {
var list = JSON.parse(ajax.responseText).map(function(i) { return i.name; });
new Awesomplete(document.querySelector("#ajax-example input"),{ list: list });
};
ajax.send();
```
### Response
N/A (Client-side interaction)
```
--------------------------------
### Advanced Example: Custom List based on User Input
Source: https://github.com/leaverou/awesomplete/blob/gh-pages/index.html
Shows how to dynamically update the autocomplete list based on user input.
```APIDOC
## Custom List Example (based on user input)
### Endpoint
N/A (Client-side JavaScript)
### Description
Dynamically generates and updates the autocomplete list based on the current input value.
### Request Example
```html
```
```javascript
const queryInput = document.querySelector("#query");
const awesomplete = new Awesomplete(queryInput, {
filter: () => { // We will provide a list that is already filtered ...
return true;
},
sort: false, // ... and sorted.
list: []
});
queryInput.addEventListener("input", (event) => {
const inputText = event.target.value;
// Process inputText as you want, e.g. make an API request.
awesomplete.list = ["my"+inputText, "custom"+inputText, "list"+inputText];
awesomplete.evaluate();
});
```
### Response
N/A (Client-side interaction)
```
--------------------------------
### Control Awesomplete via API Methods
Source: https://context7.com/leaverou/awesomplete/llms.txt
Provides examples of programmatic control over the autocomplete instance, including navigation, selection, and state management.
```javascript
var input = document.getElementById("myinput");
var awesomplete = new Awesomplete(input, {
list: ["Ada", "Java", "JavaScript", "Python", "Ruby"]
});
// Open the suggestions popup
awesomplete.open();
// Close the suggestions popup
awesomplete.close();
// Navigate to next suggestion
awesomplete.next();
// Navigate to previous suggestion
awesomplete.previous();
// Jump to specific index (0-based, -1 to deselect)
awesomplete.goto(2); // Select third item
// Select the currently highlighted item
awesomplete.select();
// Re-evaluate suggestions (call after changing list dynamically)
awesomplete.list = ["New", "Updated", "List"];
awesomplete.evaluate();
// Check if popup is open
if (awesomplete.opened) {
console.log("Popup is visible");
}
// Check if an item is selected
if (awesomplete.selected) {
console.log("Current index:", awesomplete.index);
}
// Clean up and remove instance
awesomplete.destroy();
```
--------------------------------
### Custom Filter Function for Awesomplete
Source: https://github.com/leaverou/awesomplete/blob/gh-pages/index.html
Implement a custom filter function to control how suggestions are matched against user input. This example performs a case-sensitive match from the start of the string.
```javascript
filter: function (text, input) {
return text.indexOf(input) === 0;
}
```
--------------------------------
### Custom Item Rendering with Icons
Source: https://context7.com/leaverou/awesomplete/llms.txt
Customize how suggestions appear in the dropdown by providing a custom item function. This example creates list items with icons and labels.
```javascript
new Awesomplete(input, {
list: [
{ label: "JavaScript", value: "js", icon: "🟨" },
{ label: "Python", value: "py", icon: "🐍" }
],
item: function(text, input, item_id) {
// Create custom list item with icon
var li = document.createElement("li");
li.innerHTML = text.icon + " " + text.label;
li.setAttribute("role", "option");
li.setAttribute("aria-selected", "false");
return li;
}
});
```
--------------------------------
### Run Tests Continuously
Source: https://github.com/leaverou/awesomplete/blob/gh-pages/CONTRIBUTING.md
Starts Karma in continuous mode. Tests will automatically re-run whenever source or test files change.
```bash
karma start
```
--------------------------------
### Custom Item Rendering with Highlight
Source: https://context7.com/leaverou/awesomplete/llms.txt
Override the default list item generation to customize how suggestions appear. This example highlights the matching portion of the text with bold tags.
```javascript
new Awesomplete(input, {
list: ["JavaScript", "Java", "Python"],
item: function(text, input, item_id) {
var html = input.trim() === ""
? text
: text.replace(RegExp(Awesomplete.$.regExpEscape(input.trim()), "gi"), "$&");
return Awesomplete.$.create("li", {
innerHTML: html,
role: "option",
"aria-selected": "false"
});
}
});
```
--------------------------------
### Custom Replace Function: Insert Label
Source: https://context7.com/leaverou/awesomplete/llms.txt
Control how the selected suggestion replaces the input value. This example inserts the suggestion's label instead of its value.
```javascript
new Awesomplete(input, {
list: [{ label: "United States", value: "US" }],
replace: function(suggestion) {
this.input.value = suggestion.label;
}
});
```
--------------------------------
### Custom Sort Function Examples
Source: https://context7.com/leaverou/awesomplete/llms.txt
Control the order of suggestions by providing a custom sort function or disable sorting entirely by setting sort: false. Default sort is by length first, then alphabetically.
```javascript
new Awesomplete(input, {
list: ["Zebra", "Apple", "Mango"],
sort: false
});
```
```javascript
new Awesomplete(input, {
list: ["Zebra", "Apple", "Mango"],
sort: function(a, b) {
return a.label.localeCompare(b.label);
}
});
```
```javascript
new Awesomplete(input, {
list: ["Zebra", "Apple", "Mango"],
sort: function(a, b) {
return b.label.localeCompare(a.label);
}
});
```
--------------------------------
### Custom Filter Function Examples
Source: https://context7.com/leaverou/awesomplete/llms.txt
Override the default filtering behavior to control how suggestions are matched against user input. Built-in filters include FILTER_CONTAINS (default) and FILTER_STARTSWITH.
```javascript
new Awesomplete(input, {
list: ["JavaScript", "Java", "Python"],
filter: Awesomplete.FILTER_STARTSWITH
});
```
```javascript
new Awesomplete(input, {
list: ["JavaScript", "Java", "Python"],
filter: function(text, input) {
return text.indexOf(input) === 0; // Case-sensitive startsWith
}
});
```
```javascript
new Awesomplete(input, {
list: ["JavaScript", "Java", "Python"],
filter: function(text, input) {
return text.indexOf(input) > -1;
}
});
```
--------------------------------
### Basic Jasmine Test Structure
Source: https://github.com/leaverou/awesomplete/blob/gh-pages/CONTRIBUTING.md
A simple example of a Jasmine test case. It defines a 'describe' block for a test suite and an 'it' block for a specific test, using 'expect' for assertions.
```javascript
describe("A fact", function(){
it("is always true",function(){
var fact = true;
expect(fact).toBe(true);
});
});
```
--------------------------------
### Custom Item Generation Function for Awesomplete
Source: https://github.com/leaverou/awesomplete/blob/gh-pages/index.html
Define a custom item function to control how individual suggestion items are generated. This example highlights the user's input within the suggestion text.
```javascript
item: function (text, input) {
return (
'
' + text.replace(
/(input)/gi, "$1"
) + '
'
);
}
```
--------------------------------
### Custom Replace Function: Append to Content
Source: https://context7.com/leaverou/awesomplete/llms.txt
Control how the selected suggestion replaces the input value. This example appends the suggestion to existing content, suitable for multi-value inputs.
```javascript
new Awesomplete(input, {
list: ["CSS", "JavaScript", "HTML", "SVG"],
replace: function(text) {
var before = this.input.value.match(/^.+,\\s*|/)[0];
this.input.value = before + text + ", ";
}
});
```
--------------------------------
### Custom Input Replacement Function for Awesomplete
Source: https://github.com/leaverou/awesomplete/blob/gh-pages/index.html
Implement a custom replace function to control how the selected suggestion updates the input field. This example directly sets the input value to the selected text.
```javascript
replace: function (text) {
this.input.value = text;
}
```
--------------------------------
### Custom Data Function for Object Transformation
Source: https://context7.com/leaverou/awesomplete/llms.txt
Transform list items before they're processed using the data function. Useful for converting custom objects or generating suggestions based on user input. This example transforms objects with different property names.
```javascript
new Awesomplete(input, {
list: [
{ name: "John Smith", id: "user_123" },
{ name: "Jane Doe", id: "user_456" }
],
data: function(item, input) {
return { label: item.name, value: item.id };
}
});
```
--------------------------------
### Awesomplete Constructor Configuration
Source: https://github.com/leaverou/awesomplete/blob/gh-pages/index.html
Initialize the Awesomplete instance with configuration options.
```APIDOC
## Constructor Configuration
### Description
Initialize a new Awesomplete instance with specific settings. Settings can be provided as JS properties or HTML data- attributes.
### Parameters
#### Request Body
- **list** (Array/Element/String) - Optional - Where to find the list of suggestions.
- **minChars** (Number) - Optional - Minimum characters to trigger popup (Default: 2).
- **maxItems** (Number) - Optional - Maximum number of suggestions to display (Default: 10).
- **autoFirst** (Boolean) - Optional - Automatically select the first element (Default: false).
- **tabSelect** (Boolean) - Optional - Select first element on TAB key (Default: false).
- **listLabel** (String) - Optional - aria-label for the generated list (Default: "Results List").
### Request Example
new Awesomplete(inputReference, {
minChars: 3,
maxItems: 15
});
```
--------------------------------
### Initialize Awesomplete with JavaScript
Source: https://context7.com/leaverou/awesomplete/llms.txt
Create instances programmatically using arrays, CSS selectors, or element references, and update lists dynamically.
```javascript
// Basic initialization with array of strings
var input = document.getElementById("myinput");
var awesomplete = new Awesomplete(input, {
list: ["Ada", "Java", "JavaScript", "Brainfuck", "LOLCODE", "Node.js", "Ruby on Rails"]
});
// Initialization with CSS selector for list
new Awesomplete(input, { list: "#mylist" });
// Initialization with element reference
new Awesomplete(input, { list: document.querySelector("#mylist") });
// Set or update list dynamically after initialization
var awesomplete = new Awesomplete(input);
// Later in code...
awesomplete.list = ["Option A", "Option B", "Option C"];
```
--------------------------------
### JavaScript Initialization with Array of Strings
Source: https://github.com/leaverou/awesomplete/blob/gh-pages/index.html
Configure Awesomplete using a JavaScript array of strings as the suggestion list. This is a direct and flexible way to provide options.
```javascript
var input = document.getElementById("myinput");
new Awesomplete(input, {
list: ["Ada", "Java", "JavaScript", "Brainfuck", "LOLCODE", "Node.js", "Ruby on Rails"]
});
```
--------------------------------
### Configure Combobox Dropdown
Source: https://github.com/leaverou/awesomplete/blob/gh-pages/index.html
Sets up a dropdown-style input that shows all options when clicked.
```html
```
```javascript
var comboplete = new Awesomplete('input.dropdown-input', {
minChars: 0,
});
Awesomplete.$('.dropdown-btn').addEventListener("click", function() {
```
--------------------------------
### Include Awesomplete Assets
Source: https://github.com/leaverou/awesomplete/blob/gh-pages/README.md
Add the required CSS and JS files to your HTML document.
```html
```
--------------------------------
### Handle Awesomplete Lifecycle Events
Source: https://context7.com/leaverou/awesomplete/llms.txt
Demonstrates how to listen for custom events like selection, popup visibility changes, and item highlighting.
```javascript
var input = document.getElementById("myinput");
var awesomplete = new Awesomplete(input, {
list: ["Ada", "Java", "JavaScript"]
});
// Before selection is applied (cancellable)
input.addEventListener("awesomplete-select", function(e) {
console.log("Selected:", e.text.label, e.text.value);
console.log("Origin element:", e.origin);
console.log("Original event:", e.originalEvent);
// Prevent selection if needed
// e.preventDefault();
});
// After selection is applied
input.addEventListener("awesomplete-selectcomplete", function(e) {
console.log("Selection complete:", e.text.value);
// Trigger form submission, API call, etc.
});
// Popup opened
input.addEventListener("awesomplete-open", function() {
console.log("Autocomplete popup opened");
});
// Popup closed (with reason)
input.addEventListener("awesomplete-close", function(e) {
// Reasons: "blur", "esc", "submit", "select", "nomatches"
console.log("Popup closed. Reason:", e.reason);
});
// Item highlighted (arrow keys or API)
input.addEventListener("awesomplete-highlight", function(e) {
console.log("Highlighted:", e.text.label);
});
```
--------------------------------
### Build Awesomplete Project
Source: https://github.com/leaverou/awesomplete/blob/gh-pages/CONTRIBUTING.md
Runs the Gulp build process. This command minifies JavaScript and merges CSS files.
```bash
gulp
```
--------------------------------
### Initialize Awesomplete with Options
Source: https://github.com/leaverou/awesomplete/blob/gh-pages/index.html
Configure Awesomplete using JS properties in the constructor. HTML attributes can also be used, but JS properties override them after initialization.
```javascript
new Awesomplete(inputReference, {
minChars: 3,
maxItems: 15,
...
});
```
--------------------------------
### Load Suggestions from API on Page Load
Source: https://context7.com/leaverou/awesomplete/llms.txt
Initializes Awesomplete with a list of suggestions fetched from a remote API when the page loads. Ensure the API returns a JSON array of objects, each with a 'name' property.
```javascript
// Load suggestions from API on page load
var ajax = new XMLHttpRequest();
ajax.open("GET", "https://api.example.com/countries", true);
ajax.onload = function() {
var countries = JSON.parse(ajax.responseText);
var list = countries.map(function(country) {
return country.name;
});
new Awesomplete(document.querySelector("#country-input"), {
list: list
});
};
ajax.send();
```
--------------------------------
### JavaScript Initialization with Datalist
Source: https://github.com/leaverou/awesomplete/blob/gh-pages/index.html
Instantiate Awesomplete programmatically using JavaScript, referencing a datalist by its ID. This offers more control over initialization.
```javascript
var input = document.getElementById("myinput");
new Awesomplete(input, {list: "#mylist"});
```
--------------------------------
### Suggestions with Label and Value
Source: https://github.com/leaverou/awesomplete/blob/gh-pages/index.html
Configure Awesomplete to display labels while inserting corresponding values into the input field. This is useful for presenting user-friendly options with distinct underlying data.
```javascript
var input = document.getElementById("myinput");
// Show label but insert value into the input:
new Awesomplete(input, {
list: [
{ label: "Belarus", value: "BY" },
{ label: "China", value: "CN" },
{ label: "United States", value: "US" }
]
});
// Same with arrays:
new Awesomplete(input, {
list: [
[ "Belarus", "BY" ],
[ "China", "CN" ],
[ "United States", "US" ]
]
});
```
--------------------------------
### Dynamically Updating Suggestion List
Source: https://github.com/leaverou/awesomplete/blob/gh-pages/index.html
Demonstrates how to update the suggestion list for an existing Awesomplete instance after initialization. The list can be reassigned to the 'list' property.
```javascript
var input = document.getElementById("myinput");
var awesomplete = new Awesomplete(input);
/* ...more code... */
awesomplete.list = ["Ada", "Java", "JavaScript", "Brainfuck", "LOLCODE", "Node.js", "Ruby on Rails"];
```
--------------------------------
### Initialize Awesomplete Widget
Source: https://github.com/leaverou/awesomplete/blob/gh-pages/README.md
Add the class 'awesomplete' to an input element to enable automatic processing. Suggestions can be provided directly via the data-list attribute.
```html
```
--------------------------------
### Initialize Awesomplete with HTML Attributes
Source: https://context7.com/leaverou/awesomplete/llms.txt
Configure autocomplete behavior directly in HTML using the awesomplete class and data attributes or standard datalist elements.
```html
Ada
Java
JavaScript
```
--------------------------------
### Accessing Awesomplete Static Properties and Helpers
Source: https://context7.com/leaverou/awesomplete/llms.txt
Demonstrates how to access all active Awesomplete instances, built-in filter and sort functions, default data/item/replace/container generators, and utility helper functions like querySelector shorthands and regex escaping.
```javascript
// Access all active Awesomplete instances
console.log(Awesomplete.all); // Array of all instances
// Built-in filter functions
Awesomplete.FILTER_CONTAINS // Match anywhere (default)
Awesomplete.FILTER_STARTSWITH // Match from beginning
// Built-in sort function
Awesomplete.SORT_BYLENGTH // Sort by string length
// Default functions (can be used in custom implementations)
Awesomplete.DATA // Identity function for data transformation
Awesomplete.ITEM // Default list item generator
Awesomplete.REPLACE // Default replace function
Awesomplete.CONTAINER // Default container generator
// Helper functions
Awesomplete.$("selector"); // querySelector shorthand
Awesomplete.$$("selector"); // querySelectorAll shorthand
Awesomplete.$.regExpEscape("string"); // Escape regex special chars
Awesomplete.$.create("tag", { options }); // Create DOM element
```
--------------------------------
### Use Datalist for Suggestions
Source: https://github.com/leaverou/awesomplete/blob/gh-pages/README.md
Link an input to a datalist element for a native fallback if the script fails to load.
```html
```
--------------------------------
### Run Tests Once
Source: https://github.com/leaverou/awesomplete/blob/gh-pages/CONTRIBUTING.md
Executes all project tests one time and then exits. Useful for a quick check of the current state.
```bash
npm test
```
--------------------------------
### Dynamic Loading Based on User Input
Source: https://context7.com/leaverou/awesomplete/llms.txt
Implements dynamic suggestion loading where Awesomplete fetches results from a search API as the user types. Requires server-side filtering and sorting. Set 'filter' to a function that always returns true and 'sort' to false when the server handles these.
```javascript
// Dynamic loading based on user input
var input = document.querySelector("#search-input");
var awesomplete = new Awesomplete(input, {
filter: function() { return true; }, // Server already filtered
sort: false, // Server already sorted
list: []
});
input.addEventListener("input", function(event) {
var query = event.target.value;
if (query.length < 2) return;
fetch("https://api.example.com/search?q=" + encodeURIComponent(query))
.then(function(response) { return response.json(); })
.then(function(results) {
awesomplete.list = results.map(function(r) { return r.name; });
awesomplete.evaluate();
});
});
```
--------------------------------
### Awesomplete Instance Methods
Source: https://context7.com/leaverou/awesomplete/llms.txt
Methods available on an Awesomplete instance to programmatically control the autocomplete behavior, navigation, and lifecycle.
```APIDOC
## Instance Methods
### Description
Methods to control the autocomplete popup, navigation, and instance lifecycle.
### Methods
- **open()**: Opens the suggestions popup.
- **close()**: Closes the suggestions popup.
- **next()**: Navigates to the next suggestion.
- **previous()**: Navigates to the previous suggestion.
- **goto(index)**: Jumps to a specific index (0-based, -1 to deselect).
- **select()**: Selects the currently highlighted item.
- **evaluate()**: Re-evaluates suggestions (useful after dynamic list updates).
- **destroy()**: Cleans up and removes the instance.
### Properties
- **opened** (boolean): Returns true if the popup is visible.
- **selected** (boolean): Returns true if an item is currently selected.
- **index** (number): Returns the current selection index.
```
--------------------------------
### Configure Awesomplete Options
Source: https://context7.com/leaverou/awesomplete/llms.txt
Customize widget behavior such as minimum character triggers and display limits using JavaScript objects or equivalent HTML data attributes.
```javascript
// Full configuration example
var awesomplete = new Awesomplete(input, {
// Minimum characters before autocomplete appears (default: 2)
minChars: 1,
// Maximum number of suggestions to display (default: 10)
maxItems: 15,
// Automatically highlight the first suggestion (default: false)
autoFirst: true,
// Allow Tab key to select highlighted item (default: false)
tabSelect: true,
// Aria-label for the suggestions list (default: "Results List")
listLabel: "Programming Languages",
// List of suggestions
list: ["Ada", "Java", "JavaScript", "Python", "Ruby"
});
// HTML attribute equivalent:
//
```
--------------------------------
### JavaScript Initialization with UL Element Reference
Source: https://github.com/leaverou/awesomplete/blob/gh-pages/index.html
Initialize Awesomplete by providing a direct DOM element reference to the suggestion list (UL) instead of a CSS selector. This is an alternative to using selectors.
```javascript
var input = document.getElementById("myinput");
new Awesomplete(input, {list: document.querySelector("#mylist")});
```
--------------------------------
### Initialize Email Autocomplete
Source: https://github.com/leaverou/awesomplete/blob/gh-pages/index.html
Configures an email domain autocomplete using a custom data function and prefix filtering.
```html
```
```javascript
new Awesomplete('input[type="email"]', {
list: ["aol.com", "att.net", "comcast.net", "facebook.com", "gmail.com", "gmx.com", "googlemail.com", "google.com", "hotmail.com", "hotmail.co.uk", "mac.com", "me.com", "mail.com", "msn.com", "live.com", "sbcglobal.net", "verizon.net", "yahoo.com", "yahoo.co.uk"],
data: function (text, input) {
return input.slice(0, input.indexOf("@")) + "@" + text;
},
filter: Awesomplete.FILTER_STARTSWITH
});
```
--------------------------------
### Fetch Suggestions via AJAX
Source: https://github.com/leaverou/awesomplete/blob/gh-pages/index.html
Populates the suggestion list dynamically using an XMLHttpRequest.
```javascript
var ajax = new XMLHttpRequest();
ajax.open("GET", "https://restcountries.eu/rest/v1/lang/fr", true);
ajax.onload = function() {
var list = JSON.parse(ajax.responseText).map(function(i) { return i.name; });
new Awesomplete(document.querySelector("#ajax-example input"),{ list: list });
};
ajax.send();
```
--------------------------------
### Create Custom List from User Input
Source: https://github.com/leaverou/awesomplete/blob/gh-pages/index.html
Updates the suggestion list manually in response to input events.
```html
```
```javascript
const queryInput = document.querySelector("#query");
const awesomplete = new Awesomplete(queryInput, {
filter: () => { // We will provide a list that is already filtered ...
return true;
},
sort: false, // ... and sorted.
list: []
});
queryInput.addEventListener("input", (event) => {
const inputText = event.target.value;
// Process inputText as you want, e.g. make an API request.
awesomplete.list = ["my"+inputText, "custom"+inputText, "list"+inputText];
awesomplete.evaluate();
});
```
--------------------------------
### Awesomplete Functional Overrides
Source: https://github.com/leaverou/awesomplete/blob/gh-pages/index.html
Advanced configuration using function properties to customize behavior.
```APIDOC
## Functional Overrides
### Description
Advanced JS properties that allow complete customization of matching, sorting, and rendering logic.
### Parameters
#### Request Body
- **filter** (Function) - Optional - Controls how entries are matched.
- **sort** (Function) - Optional - Controls how list items are ordered.
- **container** (Function) - Optional - Controls how the container element is generated.
- **item** (Function) - Optional - Controls how list items are generated.
- **replace** (Function) - Optional - Controls how selection replaces input value.
- **data** (Function) - Optional - Controls suggestion label and value mapping.
### Request Example
{
filter: function (text, input) {
return text.indexOf(input) === 0;
}
}
```
--------------------------------
### Awesomplete API Methods
Source: https://github.com/leaverou/awesomplete/blob/gh-pages/index.html
Public methods available on every Awesomplete instance to control its behavior.
```APIDOC
## API Methods
### `open()`
**Description**: Opens the popup.
### `close()`
**Description**: Closes the popup.
### `next()`
**Description**: Highlights the next item in the popup.
### `previous()`
**Description**: Highlights the previous item in the popup.
### `goto(i)`
**Description**: Highlights the item with index `i`. Use `-1` to deselect all. Avoid direct use; prefer `next()` or `previous()`.
### `select()`
**Description**: Selects the currently highlighted item, updates the input field's value, and closes the popup.
### `evaluate()`
**Description**: Re-evaluates the widget's state, regenerates suggestions, or closes the popup if no matches are found. Call this if you dynamically change the `list` while the popup is open.
### `destroy()`
**Description**: Cleans up and removes the instance from the input. The container is removed only if it was created by Awesomplete.
```
--------------------------------
### Implement Combobox Dropdown Pattern
Source: https://context7.com/leaverou/awesomplete/llms.txt
Combines an input field with a button trigger to show all available options regardless of current input.
```javascript
// HTML:
//
var comboplete = new Awesomplete('input.dropdown-input', {
minChars: 0 // Show suggestions even with empty input
});
document.querySelector('.dropdown-btn').addEventListener('click', function() {
if (comboplete.ul.childNodes.length === 0) {
// First click: evaluate and show all options
comboplete.minChars = 0;
comboplete.evaluate();
} else if (comboplete.ul.hasAttribute('hidden')) {
// Popup hidden: open it
comboplete.open();
} else {
// Popup visible: close it
comboplete.close();
}
});
```
--------------------------------
### Custom Data Formatting for Awesomplete
Source: https://github.com/leaverou/awesomplete/blob/gh-pages/index.html
Use the data function to customize how suggestion items are represented, especially when dealing with objects that have non-standard properties like 'name' and 'id'.
```javascript
data: function (item, input) {
return { label: item.name, value: item.id };
}
```
--------------------------------
### Use Unordered List for Suggestions
Source: https://github.com/leaverou/awesomplete/blob/gh-pages/README.md
Use a CSS selector in the data-list attribute to point to an unordered list of suggestions.
```html
Ada
Java
JavaScript
Brainfuck
LOLCODE
Node.js
Ruby on Rails
```
--------------------------------
### Google Analytics Initialization
Source: https://github.com/leaverou/awesomplete/blob/gh-pages/index.html
This JavaScript code initializes Google Analytics tracking. It defines a global function for analytics calls and sends an initial pageview event.
```javascript
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-25106441-4', 'auto'); ga('send', 'pageview');
```
--------------------------------
### Twitter Widgets Initialization
Source: https://github.com/leaverou/awesomplete/blob/gh-pages/index.html
This JavaScript code initializes the Twitter widgets script. It dynamically creates a script tag and appends it to the document's head to load the Twitter widgets functionality.
```javascript
!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');
```
--------------------------------
### Custom Data Function for Email Autocomplete
Source: https://context7.com/leaverou/awesomplete/llms.txt
Generate email suggestions based on user input by combining the username with selected domains. Requires FILTER_STARTSWITH for accurate matching.
```javascript
new Awesomplete(document.querySelector('input[type="email"]'), {
list: ["gmail.com", "yahoo.com", "hotmail.com", "outlook.com"],
data: function(text, input) {
// text = domain, input = user's email input
var username = input.slice(0, input.indexOf("@"));
return username + "@" + text;
},
filter: Awesomplete.FILTER_STARTSWITH
});
```
--------------------------------
### Awesomplete Event Handling
Source: https://context7.com/leaverou/awesomplete/llms.txt
Custom events fired by Awesomplete during the autocomplete lifecycle, prefixed with 'awesomplete-'.
```APIDOC
## Event Handling
### Description
Listen for lifecycle events to trigger custom logic during selection, popup state changes, or highlighting.
### Events
- **awesomplete-select**: Fired before selection is applied. Cancellable via e.preventDefault().
- **awesomplete-selectcomplete**: Fired after selection is applied.
- **awesomplete-open**: Fired when the popup is opened.
- **awesomplete-close**: Fired when the popup is closed. Includes a 'reason' property (blur, esc, submit, select, nomatches).
- **awesomplete-highlight**: Fired when an item is highlighted via keyboard or API.
```
--------------------------------
### Awesomplete Custom Events
Source: https://github.com/leaverou/awesomplete/blob/gh-pages/index.html
Custom events are prefixed with `awesomplete-` and can be cancelled using `event.preventDefault()` where applicable.
```APIDOC
## Custom Events
All custom events are prefixed with `awesomplete-`.
### `awesomplete-select`
**Description**: The user has made a selection, but it has not been applied yet.
**Can be cancelled**: Yes. Calling `event.preventDefault()` will prevent the selection from being applied and the popup from closing.
**Callback arguments**: An object with `text` (selected suggestion), `origin` (DOM element), and `originalEvent` (the original triggering DOM event).
### `awesomplete-selectcomplete`
**Description**: The user has made a selection, and it has been applied.
**Can be cancelled**: No.
**Callback arguments**: An object with a `text` property (selected suggestion) and `originalEvent` (the original triggering DOM event).
### `awesomplete-open`
**Description**: The popup just appeared.
**Can be cancelled**: No.
### `awesomplete-close`
**Description**: The popup just closed.
**Can be cancelled**: No.
**Callback arguments**: An object with a `reason` property indicating why the event was fired (e.g., "blur", "esc", "submit", "select", "nomatches").
### `awesomplete-highlight`
**Description**: The highlighted item has changed.
**Can be cancelled**: No.
**Callback arguments**: An object with a `text` property containing the highlighted suggestion.
```
--------------------------------
### Enable Multiple Values Support in Awesomplete
Source: https://context7.com/leaverou/awesomplete/llms.txt
Configures the autocomplete to handle comma-separated inputs by filtering and replacing text based on the segment after the last comma.
```javascript
// Multiple comma-separated tags
new Awesomplete(input, {
list: ["CSS", "JavaScript", "HTML", "SVG", "ARIA", "MathML"],
minChars: 1,
// Filter based on text after last comma
filter: function(text, input) {
return Awesomplete.FILTER_CONTAINS(text, input.match(/[^,]*$/)[0]);
},
// Highlight based on text after last comma
item: function(text, input) {
return Awesomplete.ITEM(text, input.match(/[^,]*$/)[0]);
},
// Append selection with comma separator
replace: function(text) {
var before = this.input.value.match(/^.+,\s*|/)[0];
this.input.value = before + text + ", ";
}
});
// User can enter: "CSS, JavaScript, HTML"
```
--------------------------------
### Customizing Input Value with Label
Source: https://github.com/leaverou/awesomplete/blob/gh-pages/index.html
Customize the behavior of Awesomplete to insert the suggestion's label into the input field instead of its value. This requires overriding the default 'replace' function.
```javascript
new Awesomplete(input, {
list: [
{ label: "Belarus", value: "BY" },
{ label: "China", value: "CN" },
{ label: "United States", value: "US" }
],
// insert label instead of value into the input.
replace: function(suggestion) {
this.input.value = suggestion.label;
}
});
```
--------------------------------
### Implement Multiple Value Selection
Source: https://github.com/leaverou/awesomplete/blob/gh-pages/index.html
Enables comma-separated tag selection by overriding filter, item, and replace methods.
```html
```
```javascript
new Awesomplete('input[data-multiple]', {
filter: function(text, input) {
return Awesomplete.FILTER_CONTAINS(text, input.match(/[^,]*$/)[0]);
},
item: function(text, input) {
return Awesomplete.ITEM(text, input.match(/[^,]*$/)[0]);
},
replace: function(text) {
var before = this.input.value.match(/^.+,\s*|/)[0];
this.input.value = before + text + ", ";
}
});
```
--------------------------------
### Define Label and Value Pairs
Source: https://context7.com/leaverou/awesomplete/llms.txt
Use objects or arrays to separate display labels from inserted values, and optionally override the insertion behavior with a custom replace function.
```javascript
// Object format with label and value
new Awesomplete(input, {
list: [
{ label: "Belarus", value: "BY" },
{ label: "China", value: "CN" },
{ label: "United States", value: "US" },
{ label: "United Kingdom", value: "GB" }
]
});
// User sees "United States" but input receives "US"
// Array format: [label, value]
new Awesomplete(input, {
list: [
["Belarus", "BY"],
["China", "CN"],
["United States", "US"]
]
});
// Insert label instead of value using custom replace function
new Awesomplete(input, {
list: [
{ label: "Belarus", value: "BY" },
{ label: "China", value: "CN" },
{ label: "United States", value: "US" }
],
replace: function(suggestion) {
this.input.value = suggestion.label; // Insert label instead of value
}
});
```
--------------------------------
### Control Awesomplete Behavior
Source: https://github.com/leaverou/awesomplete/blob/gh-pages/index.html
This JavaScript code snippet controls the behavior of the Awesomplete autocomplete component based on the number of child nodes in its list and its current state (hidden or open).
```javascript
if (comboplete.ul.childNodes.length === 0) {
comboplete.minChars = 0;
comboplete.evaluate();
}
else if (comboplete.ul.hasAttribute('hidden')) {
comboplete.open();
}
else {
comboplete.close();
}
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.