search
HomeWeb Front-endJS TutorialBuilding a JavaScript Autocomplete Widget with Awesomplete

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>

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.

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>
<🎜>

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" />

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"];

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"];

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'];

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"];

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>

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>
<🎜>

Then, attach a keyup event listener:

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

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"];

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"];

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
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
Replace String Characters in JavaScriptReplace String Characters in JavaScriptMar 11, 2025 am 12:07 AM

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

Build Your Own AJAX Web ApplicationsBuild Your Own AJAX Web ApplicationsMar 09, 2025 am 12:11 AM

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

10 jQuery Fun and Games Plugins10 jQuery Fun and Games PluginsMar 08, 2025 am 12:42 AM

10 fun jQuery game plugins to make your website more attractive and enhance user stickiness! While Flash is still the best software for developing casual web games, jQuery can also create surprising effects, and while not comparable to pure action Flash games, in some cases you can also have unexpected fun in your browser. jQuery tic toe game The "Hello world" of game programming now has a jQuery version. Source code jQuery Crazy Word Composition Game This is a fill-in-the-blank game, and it can produce some weird results due to not knowing the context of the word. Source code jQuery mine sweeping game

How do I create and publish my own JavaScript libraries?How do I create and publish my own JavaScript libraries?Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

jQuery Parallax Tutorial - Animated Header BackgroundjQuery Parallax Tutorial - Animated Header BackgroundMar 08, 2025 am 12:39 AM

This tutorial demonstrates how to create a captivating parallax background effect using jQuery. We'll build a header banner with layered images that create a stunning visual depth. The updated plugin works with jQuery 1.6.4 and later. Download the

How do I optimize JavaScript code for performance in the browser?How do I optimize JavaScript code for performance in the browser?Mar 18, 2025 pm 03:14 PM

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

Getting Started With Matter.js: IntroductionGetting Started With Matter.js: IntroductionMar 08, 2025 am 12:53 AM

Matter.js is a 2D rigid body physics engine written in JavaScript. This library can help you easily simulate 2D physics in your browser. It provides many features, such as the ability to create rigid bodies and assign physical properties such as mass, area, or density. You can also simulate different types of collisions and forces, such as gravity friction. Matter.js supports all mainstream browsers. Additionally, it is suitable for mobile devices as it detects touches and is responsive. All of these features make it worth your time to learn how to use the engine, as this makes it easy to create a physics-based 2D game or simulation. In this tutorial, I will cover the basics of this library, including its installation and usage, and provide a

Auto Refresh Div Content Using jQuery and AJAXAuto Refresh Div Content Using jQuery and AJAXMar 08, 2025 am 12:58 AM

This article demonstrates how to automatically refresh a div's content every 5 seconds using jQuery and AJAX. The example fetches and displays the latest blog posts from an RSS feed, along with the last refresh timestamp. A loading image is optiona

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft