0

I am using bootstrap

Following is my code to dynamically fetch feeds and then add them on the page by appending inside the division whose id is 'feeds':

$.ajax({
    url: 'http://api.feedzilla.com/v1/categories/'+newsId+'/articles.json',
    type: 'GET',
    dataType: 'json',

    // to execute when successfully got json response
    success: function(response){
        $.each(response.articles, function(){
            var feed=   "<div class='media well'>"+
                            "<div class='media-body'>"+
                                "<h4 class='media-heading'>"+this.title+"</h4>"+
                                "<h6>"+this.publish_date+"</h6>"+
                                "<p>"+this.summary+"</p>"+
                                "<a href='"+this.url+"' target='_blank'>Continue Reading</a>"+
                            "</div><br><br>"+
                            "<button class='showinfo btn pull-right' id='info'>Show Info</button>"+
                        "</div>";

            $('#feeds').append(feed);
        });
    },

    // to execute when error
    error: function(jqXHR, textStatus, errorThrown){
        alert("Server error!");
    },

    // execute at last whether success or error
    complete: function(){

    }
});

As you can see I am adding a class 'showinfo' as well as id 'info' to dynamically added buttons.

Now following is my event handler:

    // SHOW INFO BUTTON CLICK HANDLER
    $('.showinfo').click(function(){
      alert('triggered');
    });

But it does not work :(!! neither with id: $('#info').click()!! If I don't add the button dynamically, it works perfect. Why this is so?

kunal18
  • 1,935
  • 5
  • 33
  • 58

3 Answers3

19

Use on():

$('#feeds').on('click', '.showinfo', function() {
    alert('triggered');
});

The above binds any click event on any element matching .showinfo inside #feeds to the specified callback function.

Also, note that the elements that should match (.showinfo in this case) need not exist at the time of binding (hence it applies to dynamically added elements as well).

techfoobar
  • 65,616
  • 14
  • 114
  • 135
4

You have to do event delegation for dynamically added elements.

  // SHOW INFO BUTTON CLICK HANDLER
    $('#feeds').on("click",'.showinfo' ,function(){
      alert('triggered');
    });

And why on() works ??

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().

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
2

.click works for existing objects. If your controls are going to be added dynamically, then use .on(or live - but i's deprecated). It attaches the events for the objects which are added dynamically.

$('.showinfo').on('click', function(){
  alert('triggered');
});
Paritosh
  • 11,144
  • 5
  • 56
  • 74