Ajax pagination works only first and third time

I’m using ajax-based pagination, heres the markup

<div id="portfolio-thumbs">
        <ul id="portfolio-destaque">
     HERE GOES MY LOOP AND CONTENT , some LI's with thumbs and stuff   
                        </ul></div>
                <div id="pagi-container">
                    <div id="paginar">
        <?php posts_nav_link(); ?>  
            </div>
</div>

then, i use this jquery so it loads content inside #portfolio-thumbs and pagination links inside #pagi-container:

Read More
  $('#paginar > a').on('click',  function(e){
        e.preventDefault();
        var link = jQuery(this).attr('href');
        jQuery('#portfolio-thumbs').html('Loading...');
        jQuery('#portfolio-thumbs').load(link+' #portfolio-destaque');
        jQuery('#pagi-container').load(link+' #paginar');

    });

Well, when i click > Next Page for the first time:

  • it loads page/2 ok, inside #portfolio-thumbs goes the looped posts and the markup stays the same
  • except for the < previous page link that is added inside #pagi-container
  • If I click again, the jquery/ajax does not work, and loads full page/3, reloading browser’s window.. If, in page/3 I click <previous page or > next-page ajax works ok again…. Any ideas what i’m doing wrong?

    Related posts

    Leave a Reply

    1 comment

    1. @kennypu in stackoverflow saved my life with this:

      t’s because you’re changing the contents of #paginar, so what happens is the event on the links are getting cleared. depending on your jquery version, you can either use .live() or add the even to the #pagi-container instead:

      $('#pagi-container').on('click','#paginar > a',function() {... }
      

      my finished code is like this:

        $('#pagi-container').on('click','#paginar > a',function(e) {
              e.preventDefault();
              var link = jQuery(this).attr('href');
              $('#portfolio-thumbs').html('Aguarde, por favor...');
              $('#portfolio-thumbs').load(link+' #portfolio-destaque');
              $('#pagi-container').load(link+' #paginar');
      
          });
      

      thanks kennypu!