jQuery on()Method
Examples
Add a click event handler to the <p> element:
Try it Yourself »
Definition and Usage
The on() method adds one or more event handlers to the selected elements and their 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 many conveniences to the API, and we recommend using it, as it simplifies the jQuery codebase.
Note:Event handlers added using the on() method work for both current and future elements (such as new elements created by script).
Tip:To remove event handlers, use theoff()method.
Tip:To add an event that runs only once and then remove it, use theone()method.
Syntax
| Parameter | Description |
|---|---|
| event | Required. Specifies one or more events or namespaces to attach to the selected elements. Multiple event values are separated by spaces, or it can be an array. Must be a valid event. |
| childSelector | Optional. Specifies that the event handler can only be added to the specified child elements (and not the selector itself, such as the deprecated delegate() method). |
| data | Optional. Specifies additional data to pass to the function. |
| function | Optional. Specifies the function to run when the event occurs. |
More Examples
Replace bind() with on()
How to use on() to achieve the same effect as bind().
Replace delegate() with on()
How to use on() to achieve the same effect as delegate().
Replace live() with on()
How to use on() to achieve the same effect as live().
Adding multiple event handlers
How to add multiple event handlers to an element.
Adding multiple event handlers using the map parameter
How to add multiple event handlers to selected elements using the map parameter.
Adding custom events to elements
How to add custom namespaced events to elements.
Passing data to the function
How to pass data to a function.
Adding event handlers to future elements
Demonstrates that the on() method also works for elements that have not yet been created.
Removing event handlers
How to use the off() method to remove event handlers.
Other extensions
jQuery Event Methods