jQuery on() Method

Last Updated:

jQuery on() Method

The jQuery on() method attaches an event handler function for one or more events to the selected elements.

Note: This method is very useful for dynamically generated elements.

Example

HTML Editor
<!DOCTYPE html> <html lang="en-US"> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <h1>jQuery on() Method</h1> <button>Click Me</button> <script> $(document).ready(function(){ $("button").on("click",function(){ alert("You clicked the button"); }); }); </script> </body> </html>

Syntax

$(selector).on(events, selector, data, handler);

Parameter Values

Value Type Explanation
events Required One or more space-separated event types and optional namespaces
selector Optional A selector string to filter the descendants of the selected elements that trigger the event.
data Optional Data to be passed to the handler in event.data when an event is triggered.
handler Required A function to execute when the event is triggered.

Browser Support

Devicedesktopmobile
Browsergoogle chromesafarifirefoxinternet Exploreredgeoperagoogle chromesafarifirefoxedgeoperaandroid webviewsamsung internet
on()YesYesYesYesYesYesYesYesYesYesYesYesYes

Deep Understanding

In the following example, we will using both click() method and on() method for dynamically generated elements.

Note: click event will not trigger for dynamically generated elements.

Example

HTML Editor
<!DOCTYPE html> <html lang="en-US"> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <h1>jQuery on() Method</h1> <button>Generate Paragraph</button> <script> $(document).ready(function(){ $(document).on("click", "p", function(){ alert("on() is triggered"); }); $("p").click(function(){ alert("click() is triggered"); }); $("button").click(function(){ $("body").append("<p>Click on this paragraph.</p>"); }); }); </script> </body> </html>

Share this Page

Meet the Author