Namespace: Events:on

Events:on

Source:

Methods

on(targets, events, handler, optionsopt, onceopt, nullable) → {function}

Registers (an) event listener(s) to (a) valid EventTarget(s) (most likely (a) DOM-element(s)).

This method is inspired by jQuery and cash, though not identical. You may define one or more targets as well as one or more events to register a handler to, by either providing single arguments or arrays. You may also, additionally, namespace events, like in jQuery/cash, by adding it after the event name, separated by a dot ('click.namespace').

This method returns a remover function, which removes all event registrations done by this method call. So, in essence, calling that function, removes exactly, what was added, in a single call.

Parameters:
Name Type Attributes Default Description
targets EventTarget | Array.<EventTarget>

the target(s) to register event handlers on

events String | Array.<String>

the event name(s) to listen to, can be either a single name or a list of names, each name may also have a namespace, separated by a dot, to target all events/namespaces, you may use ""/".*"

handler function

the callback to execute if the event(s) defined in events are being received on target

options Object | Boolean <optional>
null

event listener options according to "addEventListener"-syntax, will be ignored, if browser does not support this, if boolean, will be used as "useCapture", the same will happen if options are not supported, but you defined "{capture : true}", "{once : true}" will not be applied directly to the listener, but will, instead, set the "once"-parameter to true (otherwise delegated listeners would self-destroy immediately on any check)

once Boolean <optional>
<nullable>
false

defines if the handler should only execute once, after which it self-destroys automatically, this will automatically be enabled, if you set options.once to true

Source:
See:
Throws:
  • error in case no targets are defined

  • error in case no events are defined

  • error in case handler is not a function

  • error in case targets are not all usable event targets

  • error in case delegations are missing viable ancestor targets

Returns:
remover function, which removes all handlers again, added by the current execution
Type
function
Example
on(linkElement, 'click', e => {	e.stopPropagation(); });
on(someElementWithCustomEvents, 'crash.test', () => { alert('crashed!'); });
on([ancestorElement, 'a'], 'click', e => { e.target.classList.add('clicked'); });
on(buttonElement, 'click', () => { console.log('click twice, but I'll just print once); }, {passive : true, once : true});
on([ancestorElement, '.btn[data-foobar="test"]'], 'click', () => { console.log('I'll just fire once); }, null, true);
on(document.body, 'click', e => { console.log(`oh, a bubbled event, let's see what has been clicked: "${e.target}"`); });
on([foo, foo, 'button', bar], ['mousedown', 'touchstart'], e => { e.target.classList.add('interaction-start'); });