- name – the name of the event to attach to (required). \\ Examples: ''%%'click'%%'', ''%%'hover'%%'', etc.
- callback – the [[mdn>Web/JavaScript/Reference/Global_Objects/Function|function]] to call when the event occurs (required).
Returns:
The [[mdn>Web/API/HTMLElement|HTMLElement]] it was called on, thus allowing for command chaining.
Notes
* This is just a simple wrapper for the JavaScript ''[[mdn>Web/API/EventTarget/addEventListener|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 [[toolbox:event:off:index|.off]] method), then you need to store a reference to this function.
* The shortcut methods available for specific event types (e.g. [[toolbox:event:onclick:index|.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 [[toolbox:event:off:index|.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 =====
* [[toolbox:event:off:index|.off]]
* [[toolbox:event:once:index|.once]]
===== More information =====
* [[mdn>Web/JavaScript/Reference/Global_Objects/Function|Function]] on MDN.
* [[mdn>Web/API/EventTarget/addEventListener|EventTarget: addEventListener() method]] on MDN.