简体   繁体   中英

How do you make an Ajax call when a user scrolls down to the bottom of the screen

I would like to make an Ajax call when a user scrolls down to the bottom of the screen. For some reason my code isn't working. I think it could be a syntax error but I checked my console and I don't see an error. Any suggestions, improvements or examples are welcomed.

<div id="content">
<?php include('post-1.php'); ?>
</div>

<div id="loading-image" style="display: none;"></div>
<div id="part2"></div>
<script>
window.onscroll = function(ev) {
  if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {

  $('#loading-image').show();
  $.ajax({
        url: "<?php echo get_stylesheet_directory_uri();?>/post-2.php",
        cache: false,
        success: function(html){
          $("#part2").html(result);
        },
        complete: function(){
          $('#loading-image').hide();
        }
  });


}
};
</script>

You can use this.Works here

function CallAjax(){
      $.ajax({
        url: "<?php echo get_stylesheet_directory_uri();?>/post-2.php",
        cache: false,
        success: function(html){
          $("#part2").html(result);
        },
        complete: function(){
          $('#loading-image').hide();
        }
      });    
}

$(window).scroll(function() {
       var divTop = $('#yourDivId').offset().top,
           divHeight = $('#yourDivId').outerHeight(),
           wHeight = $(window).height(),
           windowScrTp = $(this).scrollTop();
       if (windowScrTp > (divTop+divHeight-wHeight)){
            console.log('reached');
            // add your ajax method here;
            CallAjax();
       }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM