Example
Attach a click event to the <p> element:
$("p").on("click", function(){
alert("The
paragraph was
clicked.");
});
Try it Yourself »
Definition and Usage
The on() method attaches one or more event handlers for the selected elements and child elements.
As of jQuery version 1.7, the on() method is the new replacement for the bind(), live() and delegate() methods. This method brings a lot of consistency to the API, and we recommend that you use this method, as it simplifies the jQuery code base.
Note: Event handlers attached using the on() method will work for both current and FUTURE elements (like a new element created by a script).
Tip: To remove event handlers, use the off() method.
Tip: To attach an event that only runs once and then removes itself, use the one() method.
Syntax
$(selector).on(event,childSelector,data,function,map)
Parameter | Description |
---|---|
event | Required. Specifies one or more event(s) or namespaces to attach to the
selected elements. Multiple event values are separated by space. Must be a valid event |
childSelector | Optional. Specifies that the event handler should only be attached to the specified child elements (and not the selector itself, like the deprecated delegate() method). |
data | Optional. Specifies additional data to pass along to the function |
function | Required. Specifies the function to run when the event occurs |
map | Specifies an event map ({event:function, event:function, ...}) containing one or more event to attach to the selected elements, and functions to run when the events occur |
Try it Yourself - Examples
Changing from bind() to on()
How to use on() to achieve the same effect as bind().
Changing from delegate() to on()
How to use on() to achieve the same effect as delegate().
Changing from live() to on()
How to use on() to achieve the same effect as live().
Attach multiple events
How to attach multiple events to an element.
Attach multiple event handlers using
the map parameter
How to attach multiple event handlers to the selected elements using the map
parameter.
Attach a custom event on an element
How to attach a customized namespace event on an element.
Pass along data to the function
How to pass along data to the function.
Add event
handlers for future elements
Show that the on() method also works for elements not yet created.
Remove an event handler
How to remove an event handler using the off() method.