2.0.0 • Published 7 years ago

document-event v2.0.0

Weekly downloads
2
License
MIT
Repository
github
Last release
7 years ago

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])

  1. event, can be one or an array of events to listen for
  2. scope, can be one or an array of selectors to listen for which can be scoped
  3. callback, the function to fire on success
  4. opts, optional, native options to pass to addEventListener, and used for touch events

Callback will have access to:

  1. this, the target element matching
  2. e, the event for the listener
  3. event, the event that triggered
  4. selector, the selector used
  5. details, 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 bubble

In 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.

2.0.0

7 years ago

1.0.2

7 years ago

1.0.1

7 years ago

1.0.0

7 years ago