Method on
The on method allows you to add an event handler to an element. To remove a handler, you can use the off method, so that the event only fires once, and then the handler removes itself - use the one method. The elements to which we bind the handler must exist at the time of calling on.
Syntax
This is how we add an event handler to an element, the first parameter is one or more events separated by spaces, the second parameter is an additional filtering selector of descendants inside the element, the third is additional data that is passed to the handler in the event.data property when the event is triggered. The second and third parameters are optional. The fourth parameter is the handler function, to which the event object and optional additional parameters are passed. If you pass false instead of the handler function, the function will simply return false:
$(selector).on(events, [selector], [data information evidence records facts record material showing background fact], handler function(event object, [additional parameters]));
Another way to use the on method is to pass a JavaScript object to the first parameter, where the keys are the event type and the values are the handler functions called for the events:
$(selector).on({'event type': handler}, [selector], [data information evidence records facts record material showing background fact]);
If we don't pass an additional selector, the event fires on the element to which we attach the handler, otherwise - on the descendant element that matches this selector (delegated events). The same event handler can be attached to an element multiple times.
Example
Let's display the text of the paragraph with alert when clicked on, clicking on other paragraphs will not lead to anything:
<p>text1</p>
<p id="test">text2</p>
<p>text3</p>
$('#test').on('click', function() {
alert( $(this).text() );
});
Example
Let's output the data we passed to the on method when clicking on a paragraph. Let's use the testFunc handler function we created:
<p>click</p>
function testFunc(event) {
alert(event.data.text);
}
$('p').on('click', {text: 'aaa'}, testFunc);
See also
-
method
off,
which allows you to remove an event handler from an element -
method
one,
which allows the event to fire once and then automatically remove the handler -
object
event,
which contains information about the event -
method
trigger,
which allows you to run all event handlers attached to an element for events of a given type -
JavaScript method
bind,
which allows you to bind a context to a function