Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid multiple JavaScript function calls in Infinite Scrolling

I'm using this JavaScript functions to create a JSP page with Infinite Scroll feature.

<script language="javascript" type="text/javascript">

var count = 0;

window.onload = loadSubPage;

$(window).scroll(function(){
    if  ($(window).scrollTop() == $(document).height() - $(window).height()){
    alert("load appLeadershipSubView function calling");
        loadSubPage();
    }
});

function loadSubPage()
{
    alert("load appLeadershipSubView called");
        $.ajax({
        cache: false,
        url: 'appLeadershipSubView.do?count=' + count,
        async : true,
        beforeSend: function(){
        },
        success: function(html){
            alert("success event");
            $('#mainDiv').append(html);
            count++;
        },
        complete: function(){
        }
    }
    );
} 

</script> 

As you can see I'm calling the loadSubPage function to append html content in the appLeadershipSubView page into the #mainDiv. And loadSubPage is also called at the page Load event also.

The Problem is when I scroll down it makes multiple (2 sometimes 3) calls to the loadSubPage function and appends duplicate data into the div.

Since I'm new to JSP and Javascript I couldn't figure out the problem here. Can you please point me out the problem here?

like image 788
direndd Avatar asked Jul 29 '26 02:07

direndd


2 Answers

Add a Boolean to make sure there is not an active request. Check to see if it is active before you make a request.

var isActive = false;
$(window).scroll(function(){
    if  (!isActive && $(window).scrollTop() == $(document).height() - $(window).height()){
    isActive = true;

in the callback, set isActive to false

success: function(html){
    $('#mainDiv').append(html);
    isActive = false;
like image 77
epascarello Avatar answered Jul 30 '26 16:07

epascarello


I'd rather use Underscore's throttle function for that!

Much cleaner, non-hackish, and you'll focus on your app's logic rather than doing some callbacks-boolean-reset-magic.

like image 34
alexandernst Avatar answered Jul 30 '26 18:07

alexandernst



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!