.on(events [, selector] [, data], handler) attaches event handlers to the selected elements (since 1.7). Omit selector for a direct bind; pass a selector for delegated events on current and future descendants.
Syntax
Start with these common calls. Keep them short and readable.
jQuery
// Direct
$("p").on("click", function () {
alert($(this).text());
});
// Delegated (dynamic children OK)
$("body").on("click", "p", function () {
$(this).after("
Another paragraph!
");
});
// Remove with .off()
$("body").off("click", "p");
Call
What it does
events
Event name(s) / namespaces, or a map of event → handler
selector
Filter descendants (delegation). Omit for direct binds
data
Available as event.data in the handler
handler
Function to run, or false (*not needed with an events map)
Load jQuery before your script (CDN or local file), then wrap DOM work in $(function () { ... }) when needed.
Parameters
Parameter
Description
Step 1
Select the element that will own the listener (button, list, form, or document).
Step 2
Call .on(events, handler) for a direct bind.
Step 3
Or call .on(events, selector, handler) to handle matching descendants.
Return Value
Return Value
Description
jQuery object
Most setters and traversing helpers return the jQuery collection so you can chain more methods.
Value / undefined
Getters usually return a value from the first matched element, or undefined when nothing applies.
jQuery Examples
Example 1 — Direct Click
Bind a click handler straight to matching paragraphs.
jQuery
$("p").on("click", function () {
$("#out").text($(this).text());
});
.on() attaches event handlers to the selected elements. Since jQuery 1.7 it is the unified binding API for direct handlers, delegated handlers, namespaces, event data, and multiple events — replacing .bind(), .delegate(), and .live().
Direct: $("button").on("click", fn) runs for that button. Delegated: $("#list").on("click", "li", fn) listens on #list and runs for matching li descendants — including ones added later.
Use .off() with matching filters: event type, namespace, selector, and/or handler function. Example: $("#list").off("click", "li", fn).
Append a suffix like click.myPlugin. You can then .off(".myPlugin") or .trigger("click.myPlugin") without affecting other click handlers. Namespaces are not hierarchical — one matching name is enough.
Yes. .on("click", { foo: "bar" }, handler) puts that object on event.data. If data is a string and you also need a selector, pass the selector explicitly (or null) so the string is not treated as a selector.
Yes. .on("myCustomEvent", fn) listens for events you fire with .trigger("myCustomEvent") or .trigger("myCustomEvent", [extraArgs]).