jQuery on() Method

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

ValueTypeExplanation
eventsRequiredOne or more space-separated event types and optional namespaces
selectorOptionalA selector string to filter the descendants of the selected elements that trigger the event.
dataOptionalData to be passed to the handler in event.data when an event is triggered.
handlerRequiredA function to execute when the event is triggered.

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>

Reminder

Hi Developers, we almost covered 99.5% of jQuery Tutorials with examples for quick and easy learning.

We are working to cover every Single Concept in jQuery.

Please do google search for:

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author