How to Add Click Event for Dynamic Button Element in Jquery

4
Our Reader Score
[Total: 2 Average: 3]
  jQuery Dynamic Click Event:  Bind click event on dynamically added element HTML tags. Here this article explains how to add click event for dynamic added element. In jQuery for click event we can simply use .click() method which works fine, but when you add dynamic HTML and try to achieve click event for it, then there you face problem .i.e .click() is not working. Yeah you are right .click() is not working because it’s not loaded on dom , so now what we are going to do is we use  .on() method which is added in jQuery v 1.7. The .on() method attaches event handlers to the currently selected set of elements in the jQuery object.

Prototype : .on( events [, selector ] [, data ], handler )

Description: Attach an event handler function for one or more events to the selected elements.


Example 1: Click event for dynamically added li tags

HTML Markup:  Here we having UL list tag and then dynamically LI tag gets added. So now how to achieve click event on this dynamically added element in jQuery.

Here myUL– is the id which is already there on dom when the page loads. Jquery: Now by using .on() will able to bind the click event on dynamically added HTML tag .i.e click event for dynamic li tags.

 


Example 2: jQuery click event for dynamically added row and divs .i.e tr 

HTML Markup:  Here we have HTML table, and dynamically tr table rows get added, so now we want to bind click event for dynamic tr table rows using jQuery .on() method

Jquery : Here myTable is my table id, and on each dynamically added tr we can bind click event as shown in below code.

Here myDiv – is parent Div id,  .itemName- each span which have itemName call will alert its data Try It Yourself ⇒


 For older jQuery library  – 1.7

We can use .live() (method is deprecated in 1.7 and removed in 1.9)

Prototype : .live(events, handler )

Description: Attach an event handler for all elements which match the current selector, now and in the future.

 Note:  Use of the .live() method is no longer recommended since later versions of jQuery offer better methods that do not have its drawbacks.

Hope you enjoyed this tutorial. If you have any recommendations, please let us know what you think in the comment section below! See you again next time! 


Get your Printable Copy

4 COMMENTS

  1. great tutorial, i still have trouble getting click from dynamicaly loaded blog posts! eg “like” or “comment” how would i do that? am trying to build a blog site , al ajax (Jquery) load from DB are fine but to coment or like post
    Please help

    • Hi martin,
      Thanks you for the reading, well you can use below code to achieve jquery click event for all dynamically added element.
      $("body").on('click','yourDynamicSelector',function(){
      // code logic
      });

LEAVE A REPLY