Home >Web Front-end >JS Tutorial >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
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 pageTo 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>
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>
Basic Functions
There are many ways to use this multi-function library. Let's start with a basic use case.
The options in the above datalist element can be moved to the data-list attribute of the input element itself.
<code class="language-html"><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> <option value="Two"> </option> <option value="Three"> </option></datalist> </code>
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.
<code class="language-html"><input class="awesomplete" data-minchars="1" data-maxitems="5" data-list="China, India, Japan, Russia, UK, USA"></code>
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?
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:
<code class="language-javascript">var input = document.getElementById("countries"); var awesomplete = new Awesomplete(input, { minChars: 1, maxItems: 5, autoFirst: true }); awesomplete.list = ["China", "India", "Japan", "Russia", "UK", "USA"];</code>
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:
<code class="language-javascript">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"];</code>
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:
<code class="language-javascript">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'];</code>
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:
<code class="language-javascript">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"];</code>
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>
Awesomplete provides various methods on the Awesomplete object that allow you to customize its behavior:
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.
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):
<code class="language-html"><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> <option value="Two"> </option> <option value="Three"> </option></datalist> </code>
Then, attach a keyup event listener:
<code class="language-html"><input class="awesomplete" data-minchars="1" data-maxitems="5" data-list="China, India, Japan, Russia, UK, USA"></code>
When the user presses the key, we need to get the value of the input element and make a request:
<code class="language-javascript">var input = document.getElementById("countries"); var awesomplete = new Awesomplete(input, { minChars: 1, maxItems: 5, autoFirst: true }); awesomplete.list = ["China", "India", "Japan", "Russia", "UK", "USA"];</code>
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:
<code class="language-javascript">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"];</code>
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
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.
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.
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.
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.
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.
Yes, you can use Awesomplete with multiple input fields. You just need to create a new Awesomplete instance for each input field.
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.
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.
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.
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!