delegate

Lightweight event delegation.

Install

You can get it on npm.

  1. npm install delegate --save

If you’re not into package management, just download a ZIP file.

Setup

Node (Browserify)
  1. var delegate = require('delegate');
Browser (Standalone)
  1. <script src="dist/delegate.js"></script>

Usage

Add event delegation

With the default base (document)

  1. delegate('.btn', 'click', function(e) {
  2. console.log(e.delegateTarget);
  3. }, false);

With an element as base

  1. delegate(document.body, '.btn', 'click', function(e) {
  2. console.log(e.delegateTarget);
  3. }, false);

With a selector (of existing elements) as base

  1. delegate('.container', '.btn', 'click', function(e) {
  2. console.log(e.delegateTarget);
  3. }, false);

With an array/array-like of elements as base

  1. delegate(document.querySelectorAll('.container'), '.btn', 'click', function(e) {
  2. console.log(e.delegateTarget);
  3. }, false);

Remove event delegation

With a single base element (default or specified)

  1. var delegation = delegate(document.body, '.btn', 'click', function(e) {
  2. console.log(e.delegateTarget);
  3. }, false);
  4. delegation.destroy();

With multiple elements (via selector or array)

Note: selectors are always treated as multiple elements, even if one or none are matched. delegate() will return an array.

  1. var delegations = delegate('.container', '.btn', 'click', function(e) {
  2. console.log(e.delegateTarget);
  3. }, false);
  4. delegations.forEach(function (delegation) {
  5. delegation.destroy();
  6. });

Browser Support

Chrome logo Edge logo Firefox logo Internet Explorer logo Opera logo Safari logo
Latest ✔ Latest ✔ Latest ✔ 9+ ✔ Latest ✔ Latest ✔

License

MIT License © Zeno Rocha