How to make infinite scroll reset with new ajax content

Pollux Khafra picture Pollux Khafra · Jun 27, 2012 · Viewed 8.8k times · Source

On my homepage I have a loop of posts that uses infinite scroll. A user can replace that loop with other loops using ajax like ajax search and so on. My issue is the infinite scroll only works the first time it's used so if it's triggered for the main loop then it won't work again when a new loop replaces the main. Each time a new loop replaces the old the following function is reloaded. So how do I make infinite scroll reset and work every time a new loop is called?

var href = 'first';
$(document).ready(function() {
    $('#boxes').infinitescroll({
        navSelector: '.infinitescroll',
        nextSelector: '.infinitescroll a',
        itemSelector: '#boxes .box',
        loadingImg: '<?php echo get_bloginfo('stylesheet_directory') ?>/images/loading.gif',
        loadingText: 'Loading...',
        donetext: 'No more pages to load.',
        debug: false
    }, function(arrayOfNewElems) {
        $('#boxes').masonry('appended', $(arrayOfNewElems));
        if(href != $('.infinitescroll a').attr('href')) {
            href = $('.infinitescroll a').attr('href');
        }
    });
});

I'm using the latest version 2.0b2.120519 of the Pual Irish infinite scroll plugin on a wordpress site.

Answer

Ohgodwhy picture Ohgodwhy · Jun 30, 2012

I'm not 100% sure which version of that plugin you're using, but I checked into the latest distribution and you need to perform two methods to make this work.

First, in your ajax function, you need to destroy the session on success.

$.ajax({
  url: 'path/to/something.ext',
  success: function(data){
    //call the method to destroy the current infinitescroll session.
    $('#boxes').infinitescroll('destroy');

    //insert the new data into the container from the_loop() call
    $('#boxes').html(data);

    //reinstantiate the container
    $('#boxes').infinitescroll({                      
      state: {                                              
        isDestroyed: false,
        isDone: false                           
      }
    });

    //call the methods you need on the container again.
    $('#boxes').infinitescroll({
      navSelector: '.infinitescroll',
      nextSelector: '.infinitescroll a',
      itemSelector: '#boxes .box',
      loadingImg: '<?php echo get_bloginfo('stylesheet_directory') ?>/images/loading.gif',
      loadingText: 'Loading...',
      donetext: 'No more pages to load.',
      debug: false
    }, function(arrayOfNewElems) {
      $('#boxes').masonry('appended', $(arrayOfNewElems));
      if(href != $('.infinitescroll a').attr('href')) {
        href = $('.infinitescroll a').attr('href');
      }
    });
  }
});

You could also make it a function, bind to it, and unbind/rebind instead of repeating alot of code, but the code I've outlined should be a copy+ paste solution.