@muvon/delegate
v0.1.0
Published
DOM event delegation library
Downloads
21
Readme
delegate
A lightweight, dependency-free DOM event delegation library.
Installation
Install the library using npm:
npm install @muvon/delegate
Usage
Here's a simple example of how to use the @muvon/delegate library:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>@muvon/delegate Example</title>
</head>
<body>
<button class="js-button">Click me</button>
<script type="module">
import delegate from '@muvon/delegate';
const d = delegate(document.body);
d.on('click', '.js-button', (event, element) => {
console.log('Button clicked!', element);
});
</script>
</body>
</html>
API
delegate(node)
Creates a new Delegate instance for the specified DOM node.
node
: The DOM node to attach the delegate to (e.g.,document.body
).
Returns a Delegate
instance.
Delegate Methods
on(event, selector, callback, useCapture)
Binds a new event listener to elements matching the selector.
event
: The JavaScript event to listen for (e.g., 'click', 'keyup').selector
: A valid CSS selector string.callback
: The function to call when the event occurs. Receivesevent
andelement
as arguments.useCapture
: (Optional) Whether to use event capturing. Default isfalse
.
Return false
from the callback to prevent default behavior and stop propagation.
off(event, selector)
Removes event listeners matching the specified event and selector.
event
: The JavaScript event to remove.selector
: The CSS selector string to match.
Features
- Lightweight and dependency-free
- Supports event delegation for dynamically added elements
- Works with both bubbling and capturing phases
- Easy to use API
Browser Support
This library supports all modern browsers and IE11+.
License
MIT License
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.