When we want to bind any event to an element, normally we could directly bind to any event of each element using the on() method.
Example 1: This example using jQuery on() method to add paragraph element dynamically.
This works really well, but when we add a new list item and click it, nothing happens. This is because of the event handler attached before which is executed when the document is loaded. At that time only the first list item existed and not the new ones. Hence the .on() method was applied only for the first list item and not the rest.
Example 2: The following example is implemented using on() method.
Example 3: The following example is implemented using delegate() function. To bind the event handler to dynamically created elements, we will be using Event Delegation. On clicking the new list items, the same action is performed.
Event delegation is the process that allows us to attach a single event listener, to the parent element and it will fire for all the children elements that exist now or will be added in the future. Both on() and delegate() functions allow us to do event delegation.
- jQuery Mouse Events
- How to Dynamically Add/Remove Table Rows using jQuery ?
- Create a Form Dynamically using Dform and jQuery
- How to dynamically set the height and width of a div element using jQuery ?
- How to disable mouseout events triggered by child elements?
- Where is an object stored if it is created inside a block in C++?
- Why does SASS cache folder is created ?
- What is the difference between created and mounted event in VueJS?
- How to put the text inside of a created icon?
- How I Handle GATE CS Preparation with College Studies
- Perl | Warnings and how to handle them
- How to handle the warning of file_get_contents() function in PHP ?
- How to handle badwords in Node.js ?
- How to handle the modal closing event in Twitter Bootstrap?
- How to handle errors in node.js ?
- Merge Conflicts and How to handle them
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.