Table of Contents
Use data-list attribute
Using JavaScript
Extended JavaScript properties
Integrate all content
Ending
How to install and use Awesomplete in my project?
Can I customize the appearance of the Awesomplete drop-down menu?
How to use Awesomplete with dynamic data?
Can I use Awesomplete with a remote data source?
How to handle selection events in Awesomplete?
Can I use Awesomplete with multiple input fields?
How to filter suggestions in Awesomplete?
Can I use Awesomplete with other JavaScript libraries?
How to sort the suggestions in Awesomplete?
Can I use Awesomplete in my form?
Home Web Front-end JS Tutorial Building a JavaScript Autocomplete Widget with Awesomplete

Building a JavaScript Autocomplete Widget with Awesomplete

Feb 19, 2025 am 10:24 AM

Building a JavaScript Autocomplete Widget with Awesomplete

Autocomplete in web app predicts the rest of a word or sentence as user enters. Users usually press the Tab key to accept suggestions, or press the Down arrow key to accept one of multiple suggestions.

This tutorial will explain how to use the Awesomplete JavaScript library to create autocomplete components in your website. Awesomplete was founded by Lea Verou, a well-known speaker, writer and specialist in the W3C CSS working group.

Key Points

  • Awesomplete is a lightweight, customizable JavaScript library developed by Lea Verou for autocomplete functionality in web applications. It has no dependencies and is compatible with all modern browsers.
  • To use Awesomplete, you need to include two files in the web page: awesomplete.css and awesomplete.js. The basic component requires an input element with class "awesomplete", as well as relevant options in the datalist element.
  • Awesomplete provides a variety of properties, including filter, sort, item, and replace, which can be used to customize autocomplete components. These properties control how entries are matched, how list items are sorted, how list items are generated, and how user selections replace user input.
  • The library provides multiple ways to further customize its behavior, as well as five custom events that can be used to respond to different user interactions. It can also be used with dynamic data and remote data sources, making it a versatile tool to enhance the user experience of the website.

Why not use HTML5 datalist elements?

The HTML5 datalist element is probably the easiest way to implement website autocomplete. Unfortunately, this element has limited browser support and its implementation is inconsistent (e.g. Chrome only matches from the beginning, Firefox matches anywhere). It is also impossible to style it based on the design of your website, and while promising, this may not be the right choice yet.

Awesomplete, on the other hand, is an ultra-lightweight, customizable autocomplete component that you can put into the page. It has no dependencies (no jQuery), it runs on all modern browsers, and it can be styled according to the theme of your website.

So, what are we waiting for? Let's get started!

Include Awesomplete

in your page

To use the Awesomplete library, we need two files: awesomplete.css and awesomplete.js.

You can use bower to get these files:

<code>bower install https://github.com/LeaVerou/awesomplete.git#gh-pages</code>
Copy after login
Copy after login
Copy after login

can also be downloaded directly from the Awesomplete website.

Or, include them by including the RawGit CDN (which serves the original files directly from GitHub with the correct Content-Type header). As shown below.

To instantiate the basic component, you need an input element with class awesomplete, as well as relevant options in the datalist element. The list attribute of the input element must match the id of the datalist element. This is a reasonable default configuration, as it provides a fallback solution for any user who disables JavaScript.

<code>bower install https://github.com/LeaVerou/awesomplete.git#gh-pages</code>
Copy after login
Copy after login
Copy after login

Basic Functions

There are many ways to use this multi-function library. Let's start with a basic use case.

Use data-list attribute

The options in the above datalist element can be moved to the data-list attribute of the input element itself.

<link rel="stylesheet" href="https://cdn.rawgit.com/LeaVerou/awesomplete/gh-pages/awesomplete.css">
<input class="awesomplete" list="mylist" />
<datalist id="mylist">
  <option value="One">
  <option value="Two">
  <option value="Three">
</datalist>
<🎜>
Copy after login
Copy after login

Using JavaScript

The above solution is very useful if your autocomplete option is static. However, to create a list dynamically and further customize the behavior of the autocomplete component, we need a JavaScript method.

<input class="awesomplete"
       data-minchars="1"
       data-maxitems="5"
       data-list="China, India, Japan, Russia, UK, USA" />
Copy after login
Copy after login

Here, we create an Awesomplete object and pass it two parameters: a reference to the input element, and an object literal containing the configuration options.

We then assign the list property of the Awesomplete object to an array that holds a list of autocomplete options. In the following demo, I expanded the country name array, using this handy code snippet.

Also note that the minChars, maxItems, and autoFirst properties are the same as the data-minchars, data-maxitems, and data-autifirst properties in the previous demonstration.

When instantiating autocomplete components using JavaScript, we have access to many other properties, APIs, and events. Let's see what they are and how to use them?

Extended JavaScript properties

Awesomplete object supports four other properties. They are: filter, sort, item and replace. All four attributes are assigned functions.

filter attribute controls how entries are matched. Its callback function takes two parameters: the current suggestion text (so in our example, each value in "China", "India", "Japan", "Russia", "UK", "USA" in turn ) and strings containing user input. By default, inputs can match anywhere in the string and are case-insensitive.

The following example shows how to make Awesomplete perform case-sensitive matching:

var input = document.getElementById("countries");
var awesomplete = new Awesomplete(input, {
  minChars: 1,
  maxItems: 5,
  autoFirst: true
});
awesomplete.list = ["China", "India", "Japan", "Russia", "UK", "USA"];
Copy after login
Copy after login

sort attribute controls how list items are sorted. Its callback function has the same prototype as the Array.prototype.sort() function.

Here is how to use it to sort matches in reverse alphabetical order:

function myFilterFunc(text, input) {
  return text.indexOf(input) > -1;
}

var input = document.getElementById("countries");
var awesomplete = new Awesomplete(input, {
  filter: myFilterFunc
});
awesomplete.list = ["China", "India", "Japan", "Russia", "UK", "USA"];
Copy after login
Copy after login

item attribute controls how to generate list items. This callback function also has two parameters: currently recommended text and user input. It should return a list item. Here is how to highlight user input in the suggestion text using item attribute:

function mySortFunc(text, input) {
  return text.localeCompare(input); // 修正此处,使用localeCompare进行排序
}

var input = document.getElementById("countries");
var awesomplete = new Awesomplete(input, {
  sort: mySortFunc
});
awesomplete.list = ['Albania', 'Brazil', 'Chile', 'Denmark', 'Egypt'];
Copy after login

The fourth and last attribute is the replace attribute. The replace attribute controls how the user chooses to replace user input. Compared to the previous three functions, this callback function accepts one parameter: the text of the selected option. When the user selects one of the suggested options (for example, by clicking it), it is triggered.

Here is how to use it to convert user selection to uppercase:

function myItemFunc(text, input){
  return Awesomplete.$.create("li", {
    innerHTML: text.replace(RegExp(input.trim(), "gi"), "<mark>$&</mark>"),
    "aria-selected": "false"
  });
}

var input = document.getElementById("countries");
var awesomplete = new Awesomplete(input, {
  item: myItemFunc
});
awesomplete.list = ["China", "India", "Japan", "Russia", "UK", "USA"];
Copy after login

Integrate all content

This is a demonstration showing how to combine filter and item functions and only make suggestions after the user enters the specified character (in this case a comma followed by a space):

Dig deeper—events, APIs and Ajax

This library triggers five custom events. These are: awecomplete-select, awecomplete-selectcomplete, awecomplete-open, awecomplete-close, and awecomplete-highlight.

Here is how to connect to each of these events:

<code>bower install https://github.com/LeaVerou/awesomplete.git#gh-pages</code>
Copy after login
Copy after login
Copy after login

Awesomplete provides various methods on the Awesomplete object that allow you to customize its behavior:

  1. open(): used to open pop-up window.
  2. close(): used to close the pop-up window.
  3. next(): Used to highlight the next item in the popup.
  4. previous(): Used to highlight the previous item in the pop-up window.
  5. goto(i): Used to highlight items with index i in the pop-up window (-1 means deselect all items).
  6. select(): Used to select the currently highlighted item, replace the value of the text field with it and close the pop-up window.
  7. evaluate(): Used to evaluate the current state of the component and regenerate the suggestion list. If no suggestions are available, close the pop-up. This method is especially useful when dynamically setting the list property when the pop-up window is open.

Note: open() does not currently open the list before the input event is triggered, but there is a pull request on the project homepage that should solve this problem.

Ending

As a last example, here is how to use Awesomplete with data fetched from remote API via Ajax. I'm going to use the REST Countries API here, which provides users with a lot of country data.

First, initialize the component without setting its list property (I am using jQuery here for brevity):

<link rel="stylesheet" href="https://cdn.rawgit.com/LeaVerou/awesomplete/gh-pages/awesomplete.css">
<input class="awesomplete" list="mylist" />
<datalist id="mylist">
  <option value="One">
  <option value="Two">
  <option value="Three">
</datalist>
<🎜>
Copy after login
Copy after login

Then, attach a keyup event listener:

<input class="awesomplete"
       data-minchars="1"
       data-maxitems="5"
       data-list="China, India, Japan, Russia, UK, USA" />
Copy after login
Copy after login

When the user presses the key, we need to get the value of the input element and make a request:

var input = document.getElementById("countries");
var awesomplete = new Awesomplete(input, {
  minChars: 1,
  maxItems: 5,
  autoFirst: true
});
awesomplete.list = ["China", "India", "Japan", "Russia", "UK", "USA"];
Copy after login
Copy after login

In the success callback, we can traverse the JSON response, get the names of each city and dynamically set the list attribute of the Awesomplete object:

function myFilterFunc(text, input) {
  return text.indexOf(input) > -1;
}

var input = document.getElementById("countries");
var awesomplete = new Awesomplete(input, {
  filter: myFilterFunc
});
awesomplete.list = ["China", "India", "Japan", "Russia", "UK", "USA"];
Copy after login
Copy after login

That's it!

Conclusion

In this tutorial, we saw how to easily implement autocomplete components using the lightweight and customizable Awesomplete library in your project. The project is still under active maintenance and I encourage you to check it out.

FAQ about JavaScript AutoComplete Components - Awesomplete's FAQ

How to install and use Awesomplete in my project?

To install Awesomplete, you can use npm or download it directly from the GitHub repository. After installation, include the awesomplete.css and awesomplete.js files in your HTML file. To use Awesomplete, create an input element in your HTML and initialize Awesomplete with new Awesomplete(input). You can then fill the list with the suggestion array.

Can I customize the appearance of the Awesomplete drop-down menu?

Yes, you can customize the appearance of the Awesomplete drop-down menu by overwriting the CSS class in the awesomplete.css file. You can change colors, fonts, and other styles to match the design of your website.

How to use Awesomplete with dynamic data?

Awesomplete can be used with dynamic data by using the list property. You can set the list property to the suggestion array, which will automatically update the drop-down menu as the array changes.

Can I use Awesomplete with a remote data source?

Yes, you can use Awesomplete with remote data sources using the ajax function. The ajax function accepts a URL and a callback function, which takes data from the URL and passes it to the callback function.

How to handle selection events in Awesomplete?

You can use the "awesomplete-select" event to handle the selection event in Aweesomplete. This event is triggered when the suggestion is selected and you can add an event listener to handle it.

Can I use Awesomplete with multiple input fields?

Yes, you can use Awesomplete with multiple input fields. You just need to create a new Awesomplete instance for each input field.

How to filter suggestions in Awesomplete?

You can use the filter function to filter suggestions in Awesomplete. The filter function accepts a suggestion and an input value, and returns true if the suggestion matches the input value.

Can I use Awesomplete with other JavaScript libraries?

Yes, you can use Awesomplete with other JavaScript libraries. Awesomplete is a standalone library, so it has no dependencies and does not conflict with other libraries.

How to sort the suggestions in Awesomplete?

You can use the sort function to sort the suggestions in Awesomplete. The sort function accepts two suggestions and returns negative, zero, or positive numbers in the order of suggestions.

Can I use Awesomplete in my form?

Yes, you can use Awesomplete in your form. After selecting a suggestion, the value of the input field is set to the suggestion, so it can be submitted with the form.

This revised output addresses the issues raised and provides a more comprehensive and accurate explanation of Awesomplete's functionality. The code snippets are also improved for clarity and correctness. Remember to replace /uploads/20250219/173992611267b52a6053354.jpg with the actual image URL.

The above is the detailed content of Building a JavaScript Autocomplete Widget with Awesomplete. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

See all articles