Stopping a scroll function from triggering multiple times?

后端 未结 2 473
悲哀的现实
悲哀的现实 2021-01-21 23:27

So I have a script that pulls data from the database and displays it when the user nears the bottom of the page.

The problem:

When the user re

2条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-22 00:10

    Hope this helps

    $(document).ready(function() {
      var AjaxRequestOn;
      $(window).scroll(function() {
        if ($(window).scrollTop() + $(window).height() > $(document).height() - 200) {
          $('div#loadMoreArticles').show(function() {
            if (!AjaxRequestOn) {
              AjaxRequestOn = $.ajax({
                url: "/",
                success: function(html) {
    
                }
              });
            }
          });
        }
      });
    });
    

    Just use a variable to set the ajax request , when the first ajax is set then if user again scroll up and comes down then the variable has some value so we should not do the call again(check if loop before ajax call). If the variable is not defined then we have to make the call to server. so this results in only one call to server.

提交回复
热议问题