skip to Main Content

I’m affronted to another jQuery problem. Well I’m beginning by my code to understand my issue here:

<script type="text/javascript">
jQuery(document).ready(function() {

  var current = <?php echo ($_GET['page']!='') ? $_GET['page'] : 1; ?>;
  var idp;

  $(window).scroll(function(e){
    if($(window).scrollTop() + $(window).height() >= $(document).height()) {
      current=current+1;
      if(current<=1)
      {
        idp = '';
      }
      else
      {
        idp = '?page='+current;
      }
      loadMoreContent(idp);

      history.pushState("state", "title: "+current, "index.php"+idp);
            e.preventDefault();
    }
    if($(window).scrollTop() == 0) {
      current=((current-1)<=0) ? 1 :  current-1;
      if(current<=1)
      {
        idp = '';
      }
      else
      {
        idp = '?page='+current;
      }

      loadMoreContent(idp);

      history.pushState("state", "title: "+current, "index.php"+idp);
            e.preventDefault();

    }
  });

  window.onpopstate = function(event) {
      if(current<=1)
      {
        idp = '';
      }
      else
      {
        idp = '?page='+current;
      }
        loadMoreContent(idp);
        history.pushState("state", "title: "+current, "index.php"+idp);
      };

  function loadMoreContent(position) {
      $('#loader').fadeIn('slow', function() {
        $.get("index.php"+position+" #annonceis", function(data){
          var dato = $(data).find("#annonceis");
          $("#annonceis").html(dato);
          $('#loader').fadeOut('slow', function() {
            $(window).scrollTop(60);
          });
        });
      });
  }
});
</script>

My problem is based on infinite scroll but instead of “append” I used html() function to replace content in a div called annonceis.

The idea is that when I’m scrolling to bottom of the page I get content of new page called index.php?page=1 2 3. And replace old content in de div annonceis with the new content that I get with jQuery, but when I scroll to the bottom I Get content of next next page ex when the current page is index.php?page=2 normally when I scroll to bottom I must get content of index.php?page=3 but here I get content of index.php?page=3 and instantly index.php?page=4 so the page display index.php?page=4.

The main idea is scrolling to bottom and get the content of the next page instead of pagination, but it must take care about history.pushState for SEO purpose and Google suggestions see http://scrollsample.appspot.com/items and that https://googlewebmastercentral.blogspot.com/2014/02/infinite-scroll-search-friendly.html.

Thank you very much in advance.

2

Answers


  1. Chosen as BEST ANSWER

    Hey Bro @LionelRitchietheManatee Finnaly I have resolved the problem this is the code that I used.

    <script type="text/javascript">
    jQuery(document).ready(function() {
      
      var current = <?php echo ($_GET['page']!='') ? $_GET['page'] : 1; ?>;
      var idp;
      var loaded = true;
    
      $(window).scroll(function(e){
        if(($(window).scrollTop() + $(window).height() == $(document).height())&&(loaded)) {
          loaded = !loaded;
          current=current+1;
          if(current<=1)
          {
            idp = '';
          }
          else
          {
            idp = '?page='+current;
          }
          loadMoreContent(idp);
    
          history.pushState("state", "title: "+current, "index.php"+idp);
                e.preventDefault();
        }
        if($(window).scrollTop() == 0) {
          loaded = !loaded;
          current=((current-1)<=0) ? 1 :  current-1;
          if(current<=1)
          {
            idp = '';
          }
          else
          {
            idp = '?page='+current;
          }
          
          loadMoreContent(idp);
    
          history.pushState("state", "title: "+current, "index.php"+idp);
                e.preventDefault();
    
        }
      });
    
      
    
      window.onpopstate = function(event) {
          if(current<=1)
          {
            idp = '';
          }
          else
          {
            idp = '?page='+current;
          }
            loadMoreContent(idp);
            history.pushState("state", "title: "+current, "index.php"+idp);
          };
    
      function loadMoreContent(position) {
          $('#loader').fadeIn('slow', function() {
            $.get("index.php"+position+" #annonceis", function(data){ 
              var dato = $(data).find("#annonceis");
              $("#annonceis").html(dato);
              $('#loader').fadeOut('slow', function() {
                loaded = !loaded;
                $(window).scrollTop(60);
              }); 
            });
          });
      }
    });
    </script>

    I had added a new var called "loaded" with initial value as TRUE, and it will be updated to FALSE state when content is loaded, and to the TRUE state when we begin scrolling.

    I'ts very primitive as solution not very clean work as you did but it solved my problem.

    Thank you anyway for your help, you are the BOSS.


  2. So, what you’re after really is pagination combined with infinite scroll. What the provided example is doing is using .pushState() to track the users scroll using page Waypoints. Notice, once page X reaches the center point in the page, the .pushState() is triggered.

    Secondly, if you look at the example’s source code for any of the pages, you’ll see it will only render the selected page, then using listeners on the .scroll it will append or prepend content as needed.

    So, at it’s core, this is really just simple pagination. The infinite scroll feel is simply added on top for user experience. Basic overview to do this would look something like this:

    Model or Controller

    Your PHP file or whatnot, that runs the actual queries – class based for ease of use. The class will contain one function to grab a set of posts based on a request page. JavaScript will handle everything else.

    <?php
    
    Class InfiniteScroller {
    
        // Set some Public Vars
        public $posts_per_page = 5;
        public $page;
    
        /**
        * __construct function to grap our AJAX _POST data
        */
        public function __construct() {
    
            $this->page = ( isset($_POST['page']) ? $_POST['page'] : 1 );
    
        }
    
    
        /**
        * Call this function with your AJAX, providing what page you want
        */
        public function getPosts() {
    
            // Calculate our offset
            $offset = ($this->posts_per_page * $this->page) - $this->posts_per_page;
    
            // Set up our Database call
            $SQL = "SELECT * FROM my_post_table ORDER BY post_date ASC LIMIT " . $offset . ", " . $this->posts_per_page;
    
            // Run Your query, format and return data
            // echo $my_formatted_query_return;
    
        }
    
    }
    
    ?>
    

    AJAX Call

    The next thing you’ll want to take care of is your frontend and JavaScript, so your AJAX call can sit in a function that simply calls the above method and takes a page parameter.

    <script type="text/javascript">
    
    function getPageResults( page = 1, arrange = 'next' ) {
        $.ajax({
            url: url;
            type: "POST",
            data: "?page=" + page,
            success: function(html) {
                /* print your info */
                if( arrange == 'prev' ) {
                    $( '#myResults' ).prepend(html);
                else if( arrange == 'next' ) {
                    $( '#myResults' ).append(html);
                }
            },
            error: function(e) {
                /* handle your error */
            }
    
        });
    }
    
    </script>
    

    The HTML View

    Your HTML would be fairly basic, just a place to hold your displayed results and some creative triggers.

    <html>
    <head>
    </head>
    <body>
    
        <div class="loadPrev"></div>
    
        <div id="myResults">
            <!-- Your Results will show up here -->
        </div>
    
        <div class="loadNext"></div>
    
    </body>
    </html>
    

    Loading the Page You Want

    In basic summation, the last piece of your puzzle is loading the page requested based on the querystring in the URL. If no querystring is present, you want page 1. Otherwise, load the requested page.

    <script type="text/javascript">
    
    $( document ).ready(function() {
    
        var page = <?php echo ( isset($_GET['page'] ? $_GET['page'] : 1) ?>;
        getPageResults( page, 'next' );
    
    });
    
    </script>
    

    After that you can set up some creative listeners for your previous and next triggers and call the getPageResults() with the needed page, and the next or prev attribute as needed.

    This can really be done in a much more elegant sense – look at the JS from the example you provided: http://scrollsample.appspot.com/static/main.js

    Cleaning it up

    Once you have the basic architecture in place, then you can start altering the .pushState() as well as changing out the canonical, next, and prev <link rel> header items. Additionally at this point you can start to generate the next / prev links you need, etc. It should all fall into place once you have that basic foundation laid.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search