tmartin314
tmartin314

Reputation: 4171

jQuery infinite scroll ignore browser bounce up

I have this function that is loading 5 items at time based on the page number. But what's happening is that when the user scrolls to the bottom of the page, the $.post function fires once, and then again when the browser bounce finishes, because position_bot == $(document).height() is actually true twice. Then 10 items are loaded each time.

I'm trying to find a way to ignore the browser bounce situation so the call only fires once. Any suggestions or help would be great.

$(function(){
    $('#loading').show();
    var page = 1,
        total_brands = '<?php echo $brandsCount?>',
        post_link = '<?php echo $brandsUrl?>',
        post_data = {page_num: page};

    $.post(post_link, post_data, function(data){
        $('.brandsResult').append(data);
        $('#loading').hide();
    });

    $(window).scroll(function (e) {

        var position_bot = $(window).scrollTop() + $(window).height(),
            displayed_brands = $('ul.category-list > li').length;               

        // Show loading image if near bottom
        if(position_bot > $(document).height() - 120 && displayed_brands < total_brands) {
            $('#loading').show();
        }

        // If page is at the bottom
        if(position_bot == $(document).height()) {

            // Increase page number
            page++;
            post_data = { page_num: page };
            console.log('page', page);

            // Check if all items are displayed
            if((page-1) * 5 > total_brands){
                $('#loading').hide();
            } else {    
            // Firing twice ???
                $.post(post_link, post_data, function(data){
                    $('#loading').hide();
                    $('.brandsResult').append(data);
                });

            }

        }
    });
});

Upvotes: 0

Views: 415

Answers (1)

Kai Qing
Kai Qing

Reputation: 18833

I would set a boolean to control loading state and tell the code not to do anything if true...

    var processing = false;

if(position_bot == $(document).height() && !processing) {

    if((page-1) * 5 > total_brands){
       $('#loading').hide();
       processing = false;
    } else {    
       processing = true;
       $.post(post_link, post_data, function(data){
           $('#loading').hide();
           $('.brandsResult').append(data);
           processing = false;
       });

    }
}

I believe this is happening cause $('#loading').show() is pushing the screen, acting as a change in height, which is not enough to push beyond the boundaries of your conditional. A simple boolean would (or could) prevent this. It may require some adjustments and this is just a basic and totally untested example.

Upvotes: 1

Related Questions