Table of Contents

<HTMLElement>.on()

Attaches a callback function for a named event to any HTMLElement.

Usage:
HTMLElement = Element.on(name, callback)
Member of:
HTMLElement
Parameters:
  1. name – the name of the event to attach to (required).
    Examples: 'click', 'hover', etc.
  2. callback – the function to call when the event occurs (required).
Returns:
The HTMLElement it was called on, thus allowing for command chaining.
Notes
  • This is just a simple wrapper for the JavaScript addEventListener method, which also allows to use more specific options.
  • You can simply use anonymous or arrow functions as callbacks (and in many cases this is even preferred), but if you also want to be able to detach the callback function later (using the .off method), then you need to store a reference to this function.
  • The shortcut methods available for specific event types (e.g. .onClick for 'click' events) are independent of this method, and do not require it to be present in the library.

Examples

let foo document.getElementById('foo');
foo.on('click', function(e) {
  console.log(e);
});

Using arrow functions can makes this even more lightweight:

let foo document.getElementById('foo');
foo.on('click', e => {
  console.log(e);
});

If you need to be able to unregister the event handler using the .off method, you need to keep a reference to the callback function, as in the following example:

let callback = function(e) {
  console.log(e);
}
let foo document.getElementById('foo');
foo.on('click', callback);

See also

More information