Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
178
rated 0 times [  184] [ 6]  / answers: 1 / hits: 17603  / 11 Years ago, mon, june 24, 2013, 12:00:00

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?


More From » jquery

 Answers
11

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


[#77447] Saturday, June 22, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jeanettee

Total Points: 209
Total Questions: 97
Total Answers: 98

Location: Papua New Guinea
Member since Thu, Jul 9, 2020
4 Years ago
;