Stopping a scroll function from triggering multiple times?

后端 未结 2 475
悲哀的现实
悲哀的现实 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:18

    Try defining handler as named function , using .off() to detach scroll event before $.ajax() call , reattach scroll event after $.ajax() completes

    function scroller() {
           if($(window).scrollTop() + $(window).height() > $(document).height() - 200) {
                $(this).off("scroll.ajax");
                $('div#loadMoreArticles').show( function(){         
                     $.ajax({
                          url: "loadMoreArticles.php?lastArticle="+ $(".postedArticle:last").attr('id') ,
                          success: function(html) {
                               if(html){       
                                    $("#postedArticle").append(html);
                                    $('div#loadMoreArticles').hide();       
                               } else { 
                                    $('div#loadMoreArticles').replaceWith("

    There are no more articles.

    "); }; // setTimeout(function() { $(window).on("scroll.ajax", scroller) // }, 500) } }); }); } } $(window).on("scroll.ajax", scroller);

提交回复
热议问题