I am using the infinite scroll plugin http://www.infinite-scroll.com/infinite-scroll-jquery-plugin/ to load page content.
I have a jQuery event listener such as:
$('.like-action').on('click',
function(event){
likeComment($(this));
event.preventDefault();
});
That get's loaded on $(document).ready
. However, when new content is loaded with the infinitescroll
the event listeners are not applied/available to the new content. So, I created a function that is called on the callback of the infinitescroll
(when all content has loaded).The function:
function afterUpdate(){
$('.like-action').on('click',function(event){
likeComment($(this));
event.preventDefault();
});}
What ends up happening however, is for the old content (that is already loaded) when a link is clicked that has the .like-action class
, the likeComment
function is called however many times new content has been loaded + the original $(document).ready
.
Ex: content is loaded on page load. link executes likeComment
1 on click. After scrolling down and having new content loaded (and callback) if you click the same link as before, likeComment
is executed twice. etc,etc.
What am I doing wrong here?
Is my event listener written incorrectly?
Is there a way to write a listener that automatically works for all elements in the DOM
even if they were not there on page load?
Or, is there a way to only register the .on on elements that were just loaded by infinite scroll (so there isn't a duplication)?