国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

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>

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進(jìn)行排序
}

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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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)

Which Comment Symbols to Use in JavaScript: A Clear Explanation Which Comment Symbols to Use in JavaScript: A Clear Explanation Jun 12, 2025 am 10:27 AM

In JavaScript, choosing a single-line comment (//) or a multi-line comment (//) depends on the purpose and project requirements of the comment: 1. Use single-line comments for quick and inline interpretation; 2. Use multi-line comments for detailed documentation; 3. Maintain the consistency of the comment style; 4. Avoid over-annotation; 5. Ensure that the comments are updated synchronously with the code. Choosing the right annotation style can help improve the readability and maintainability of your code.

Java vs. JavaScript: Clearing Up the Confusion Java vs. JavaScript: Clearing Up the Confusion Jun 20, 2025 am 12:27 AM

Java and JavaScript are different programming languages, each suitable for different application scenarios. Java is used for large enterprise and mobile application development, while JavaScript is mainly used for web page development.

Javascript Comments: short explanation Javascript Comments: short explanation Jun 19, 2025 am 12:40 AM

JavaScriptcommentsareessentialformaintaining,reading,andguidingcodeexecution.1)Single-linecommentsareusedforquickexplanations.2)Multi-linecommentsexplaincomplexlogicorprovidedetaileddocumentation.3)Inlinecommentsclarifyspecificpartsofcode.Bestpractic

Mastering JavaScript Comments: A Comprehensive Guide Mastering JavaScript Comments: A Comprehensive Guide Jun 14, 2025 am 12:11 AM

CommentsarecrucialinJavaScriptformaintainingclarityandfosteringcollaboration.1)Theyhelpindebugging,onboarding,andunderstandingcodeevolution.2)Usesingle-linecommentsforquickexplanationsandmulti-linecommentsfordetaileddescriptions.3)Bestpracticesinclud

JavaScript Data Types: A Deep Dive JavaScript Data Types: A Deep Dive Jun 13, 2025 am 12:10 AM

JavaScripthasseveralprimitivedatatypes:Number,String,Boolean,Undefined,Null,Symbol,andBigInt,andnon-primitivetypeslikeObjectandArray.Understandingtheseiscrucialforwritingefficient,bug-freecode:1)Numberusesa64-bitformat,leadingtofloating-pointissuesli

JavaScript vs. Java: A Comprehensive Comparison for Developers JavaScript vs. Java: A Comprehensive Comparison for Developers Jun 20, 2025 am 12:21 AM

JavaScriptispreferredforwebdevelopment,whileJavaisbetterforlarge-scalebackendsystemsandAndroidapps.1)JavaScriptexcelsincreatinginteractivewebexperienceswithitsdynamicnatureandDOMmanipulation.2)Javaoffersstrongtypingandobject-orientedfeatures,idealfor

How to work with dates and times in js? How to work with dates and times in js? Jul 01, 2025 am 01:27 AM

The following points should be noted when processing dates and time in JavaScript: 1. There are many ways to create Date objects. It is recommended to use ISO format strings to ensure compatibility; 2. Get and set time information can be obtained and set methods, and note that the month starts from 0; 3. Manually formatting dates requires strings, and third-party libraries can also be used; 4. It is recommended to use libraries that support time zones, such as Luxon. Mastering these key points can effectively avoid common mistakes.

JavaScript: Exploring Data Types for Efficient Coding JavaScript: Exploring Data Types for Efficient Coding Jun 20, 2025 am 12:46 AM

JavaScripthassevenfundamentaldatatypes:number,string,boolean,undefined,null,object,andsymbol.1)Numbersuseadouble-precisionformat,usefulforwidevaluerangesbutbecautiouswithfloating-pointarithmetic.2)Stringsareimmutable,useefficientconcatenationmethodsf

See all articles