Question

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.

Was it helpful?

Solution

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
        }); 
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top