A lightweight utility for debouncing input events using HTML data attributes, with no additional JavaScript required for each implementation.
- Debounce input events with simple HTML data attributes
- Configurable delay times
- Custom callback functions
- Customizable attribute prefix to avoid conflicts
- No dependencies
- Works in both browser and Node.js environments
Download bouncer.js from the src directory and include it in your project.
- Include the script in your HTML:
<script src="path/to/bouncer.js"></script>- Initialize Bouncer:
const bouncer = new Bouncer();- Add data attributes to your inputs:
<input
type="text"
data-bouncer-delay="500"
data-bouncer-callback="myCallbackFunction"
>- Define your callback function:
function myCallbackFunction(element, event) {
console.log('Input value:', element.value);
// Do something with the input value
}If you need to avoid conflicts with other libraries or your own data attributes, you can customize the prefix:
const Bouncer = new Bouncer({ prefix: 'custom' });Then use your custom prefix in the data attributes:
<input
type="text"
data-custom-delay="500"
data-custom-callback="myCallbackFunction"
>If you only ever use the same delay, you can omit the data-bouncer-delay attribute and Bouncer will default to 1000ms.
Alternatively, if you want to change the default delay, you can pass in the option like so:
const Bouncer = new Bouncer({ delay: 750 });The Bouncer constructor accepts an options object with the following properties:
| Option | Type | Default | Description |
|---|---|---|---|
| prefix | string | 'bouncer' | Prefix for data attributes |
| delay | int | 1000 | Default delay if none is defined |
| Attribute | Description | Example |
|---|---|---|
| data-[prefix]-delay | (optional) The debounce delay in milliseconds | data-bouncer-delay="500" |
| data-[prefix]-callback | The name of the callback function | data-bouncer-callback="handleInput" |
The callback function receives two parameters:
element: The HTML element that triggered the eventevent: The original event object
Example:
function handleInput(element, event) {
console.log('Input value:', element.value);
// Do something with the input value
}See the index.html file for complete examples of how to use Bouncer.js.
Bouncer.js works in all modern browsers that support ES6 features.
MIT