document-event v2.0.0
document-event
A simple document/element event delegator with basic touch support. A wrapper around addEventListener.
This library also experimentally handles basic touch events for tapping and swiping. See examples.
Installation
With NPM
npm install document-event --save
Standalone
See dist/ for full and minified versions.
Usage
onEvent(...event, ...scope, callback[, opts])
event, can be one or an array of events to listen forscope, can be one or an array of selectors to listen for which can be scopedcallback, the function to fire on successopts, optional, native options to pass toaddEventListener, and used for touch events
Callback will have access to:
this, the target element matchinge, the event for the listenerevent, the event that triggeredselector, the selector useddetails, any details helpful (currently used for touch events only)
Examples
Simple; one event, one selector, which is attached to an element:
onEvent('click', 'main a', (e) => {
e.preventDefault();
console.log('Clicked!');
});Simple; one event, one selector, which is attached to document so it works for "live" elements:
onEvent('click', [[document, 'main a']], (e) => {
e.preventDefault();
console.log('Clicked live!');
});Complex; multiple events, multiple selectors:
onEvent(['focus', 'keyup'], ['form input', [document, '#search']], function(e, event, selector) {
console.log(`${event} happened for ${selector}`);
}, { capture: true }); // Makes focus bubbleIn the above example, an event listener will be created to watch focus on form input and document.#search. Also, an event listener will be created to watch keyup on form input and document.#search.
Touch events:
tap and swipe supported.
onEvent('tap', 'body', (e, event) => {
console.log(`${event} happened!`);
});
onEvent('tap', 'body', (e, event) => {
console.log(`${event} happened!`);
}, { delay: 500 }); // Wait 500ms to check for a tap instead of default 300
onEvent('swipe', [[document, '#cool-div']], (e, event, selector, details) => {
console.log(`We ${event}ed to the ${details.direction}`);
});TODO
- Add tests
License
This project is released under the "MIT" license. See LICENSE file for more details.