Bouncer.js
A lightweight utility for debouncing input events using HTML data attributes, with no additional JavaScript required for each implementation.
Features
- 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
Installation
Direct Download
Download bouncer.js from the src directory and include it in your project.
Usage
Basic Setup
- Include the script in your HTML:
- Initialize Bouncer:
- Add data attributes to your inputs:
type="text"
data-bouncer-delay="500"
data-bouncer-callback="myCallbackFunction"
>
- Define your callback function:
console.log('Input value:', element.value);
// Do something with the input value
}
Custom Prefix
If you need to avoid conflicts with other libraries or your own data attributes, you can customize the prefix:
Then use your custom prefix in the data attributes:
type="text"
data-custom-delay="500"
data-custom-callback="myCallbackFunction"
>
Custom Default Delay
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:
API
Constructor Options
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 |
Data Attributes
| 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" |
Callback Function
The callback function receives two parameters:
element: The HTML element that triggered the eventevent: The original event object
Example:
console.log('Input value:', element.value);
// Do something with the input value
}
Examples
See the index.html file for complete examples of how to use Bouncer.js.
Browser Support
Bouncer.js works in all modern browsers that support ES6 features.
License
MIT