1

I'm using infinite-scroll, a plugin that replaces the standard pagination by fetching new pages through ajax.

The problem with this is that jquery functions don't register the new posts, causing functions like these:

jQuery(document).ready(function($) {
        $('.vote-a, .vote-b').click(function() {
            //do stuff
        });

        $('.vote-b').click(function() {
                    //do other stuff
        }); 
}); 

to stop running. To solve this, the plugin provides callback, and let's you include codes that you'd like to be called whenever a new page is loaded.

What I did was simply putting the code above there. It worked but I ended up with several instances of the same code.

So the question is how do I solve this? One way I can think of is destroying/removing the old instance with each callback.

Or somehow reinitiliaze/restart/invoke the function.

Ming
  • 744
  • 4
  • 13
  • 26
  • possible duplicate of [In jQuery, how to attach events to dynamic html elements?](http://stackoverflow.com/questions/1359018/in-jquery-how-to-attach-events-to-dynamic-html-elements) – epascarello Apr 01 '14 at 15:52

1 Answers1

1

You can register the click events at a root level instead of by finding the individual elements and assigning a click event to them.

https://api.jquery.com/on/ and the older method https://api.jquery.com/live/

jQuery(document).ready(function($) {
        $(document).on('click', '.vote-a, .vote-b', function() {
            //do stuff
        });

        $(document).on('click', '.vote-b', function() {
                    //do other stuff
        }); 
});
Will Shaver
  • 12,471
  • 5
  • 49
  • 64