jQuery on: Main Tips
- The jQuery
.on()
method adds event listeners to the selected element. - The .off() function removes the event listeners added by
on()
. - For instance, the
.on()
method with thechange
as the event parameter works similarly to change().
Usage and Syntax
The .on()
jQuery method is used to add event handlers:
Example
$("div").on("click", function() {
$(this).css("background-color", "red");
});
This is the syntax you need to use:
$("selector").on(event,selector,data,handler);
jQuery .on()
method takes four arguments:
event
- an event type to specify what handlers should be added. Accepts multiple values separated by commas.selector
- a selector to filter which descendants can trigger the jQuery event handler.data
- additional data that gets passed to the handler via the event.data when the event triggers.handler
- the handler function that is executed when the jQueryon
event is triggered.
Note: if the selector is undefined or null in the jQuery on method, the handler applies to all of the children of the selected elements.