jQuery on() – Click event not working for dynamically added element

My colleague got stuck into a problem where he was using jQuery on() method to attach the click event handlers but click event was not working for dynamically added elements. Although he knew that .bind() method doesn't work for dynamically added element but he was quite sure about .live() and .on(). Since .live() method is already deprecated, so .on() method was the only left choice.

But for him even the .on() was working for one of his scenario. First let's see the scenario. There is a HTML table with set of rows and every row with class "trDummy" being added dynamically.

<table class="tbMain">
  <tr class="trDummy">
     <td>Some Data</td>
     <td><a href="#" class="toggle">Close</a></td>
  </tr>
</table>

And there was a close event attach to "tr" using .on() which does blah blah..

$(document).ready(function () {
  $('.trDummy').on('click', '.close', function () {
     //Do something...
  });
});

The close event was working fine for already added "tr" but it was not working for dynamically added "tr" rows. Is there anything wrong?
YES, there is. Official jQuery document about jQuery on() says,

" Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on()."

So click event works only for element present on the page. If it is added dynamically, it's not going to work. So, the solution is to delegate the events to that wrapper, instead of binding handlers directly on the dynamic elements. So always use static elements in which you add the dynamic control while using .on().

$(document).ready(function () {
  $('.tbMain').on('click', '.close', function () {
     //Do something...
  });
});

Related Post:

Feel free to contact me for any help related to jQuery, I will gladly help you.



Responsive Menu
Add more content here...