Advertisement
5ally

myloadmore.js

Mar 23rd, 2019
359
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /** Notes by Sally:
  2.  * 1) This file uses tab for indentation and not spaces.
  3.  * 2) I set the bottomOffset to a dynamic value.
  4.  * 3) I added the max_page check.
  5.  */
  6. // REPLACE THE "article" with "div" or the proper tag, if it's not "article".
  7. jQuery(function($){
  8.     var canBeLoaded = true, // this param allows to initiate the AJAX call only if necessary
  9.         // the distance (in px) from the page bottom when you want to load more posts,
  10.         bottomOffset = ( $( '#main > article.post:last' ).offset() || {} ).top;
  11.  
  12.     $(window).scroll(function(){
  13.         if ( misha_loadmore_params.current_page >= misha_loadmore_params.max_page ) {
  14. //          console.log( 'max_page reached; AJAX canceled' );
  15.             return; // we've already reached the last page, so let's do no more AJAX.
  16.         }
  17.         var data = {
  18.             'action': 'loadmore',
  19.             'query': misha_loadmore_params.posts,
  20.             'page' : misha_loadmore_params.current_page
  21.         };
  22.         if( $(document).scrollTop() > ( $(document).height() - bottomOffset ) && canBeLoaded == true ){
  23.             $.ajax({
  24.                 url : misha_loadmore_params.ajaxurl,
  25.                 data: data,
  26.                 type: 'POST',
  27.                 beforeSend: function( xhr ){
  28.                     // you can also add your own preloader here
  29.                     // you see, the AJAX call is in process, we shouldn't run it again until complete
  30.                     canBeLoaded = false;
  31.                 },
  32.                 success:function(data){
  33.                     if( data ) {
  34.                         $('#main').find('article:last-of-type').after( data ); // where to insert posts
  35.                         canBeLoaded = true; // the ajax is completed, now we can run it again
  36.                         misha_loadmore_params.current_page++;
  37.  
  38.                         bottomOffset = ( $( '#main > article.post:last' ).offset() || {} ).top
  39.                     }
  40.                 }
  41.             });
  42.         }
  43.     });
  44. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement