Reputation: 137
What's the best way of updating my Javascript event listeners after I load new content onto the page? I realized my click listener wasn't working if I added it before I loaded data into my feed. To fix this problem I put it in the .done callback of my ajax call.
$(".likebutton").click(function(){
//function
});
If I load more data into the same feed the click listener gets added again to all the instances of .likebutton that were there before. This means sometimes my function gets called 2 or even 3 times depending on how many times I've loaded new data.
I know I can remove a listener on all objects and then add a new one each time, but I'm not sure if that's the best practice.
Suggestions?
Upvotes: 0
Views: 263
Reputation: 6787
Supposing that you always load the new content inside a specific element, like a div with id content
, you could use the on
method to delegate the click event to this element.
$('#content').on('click', '.likebutton', function() {
// your code
});
Example: http://jsfiddle.net/nxpgp/ (note that every new .likebutton
will respond to the click event)
Upvotes: 7