Floating Autocomplete Box For Textarea – floatype.js

Category: Form , Javascript , Recommended | November 29, 2023
Author:knadh
Views Total:123 views
Official Page:Go to website
Last Update:November 29, 2023
License:MIT

Preview:

Floating Autocomplete Box For Textarea – floatype.js

Description:

floatype.js is a lightweight and fast JavaScript library that adds autocomplete/autosuggestion functionality to textareas.

As soon as you start typing characters into a textarea, the library automatically displays a floating dropdown box next to the cursor with preset suggestions to choose from.

See Also:

How to use it:

1. Install and import the floatype.js library.

# NPM
$ npm i @knadh/floatype
// ES module
import { floatype } from @knadh/floatype;
// Browser
<script type="module">
  import { floatype } from './floatype.js';
</script>

2. Define an array of suggestions as follows:

const myData = ["CSS", "Script", "Com"];

3. Initialize the floatype.js on your textarea element and enable the autocomplete functionality using the onQuery.

floatype(document.querySelector("textarea"), {
  onQuery: async (val) => {
  // This callback returns an array of search results.
  // Typically, this will be a server side fetch() request.
  // Example:
  //    const resp = await fetch(`/search?q=${query}`);
  //    const res = await response.json();
  //    return res;
  const q = val.trim().toLowerCase();
  return myData.filter(s => s.startsWith(q)).slice(0, 10);
  }
});

4. Apply your own CSS styles to the autocomplete list.

.floatype {
  /* styles here */
}
.floatype-item {
  /* styles here */
}
.floatype-item:hover {
  /* styles here */
}
.floatype-sel {
  /* styles here */
}

You Might Be Interested In:


Leave a Reply