Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading content scrolling bottom

I am using the below functions to load more results when scrolling to the bottom.

Everything is working well; the only problem is that when some content is loaded, the window scrolls back to the top instead, as if to keep the same position that it had before rather than loading new results. Actually, it does not go back completely to the top, instead it goes back to the height of the first loaded result. Therefore, to see the content that was just loaded, you must scroll back to the bottom. This is where this 'cycle' will start over again...

$(window).scroll(function () {
    if ($(document).height() <= $(window).scrollTop() + $(window).height()) {
        document.getElementById("loader_bar").style.display = 'block';
        load_result();
    }
});

function load_result() {
    counter = check_counter();
    type = $("#search_type").html();
    key = $("#search_key").html();

    $("#load_result").html("<p id='loader_bar' style='width:100%; height:32px'></p>");

    var par = "key=" + key + "&type=" + type + "&counter=" + counter;

    $.ajax({
        url: "ajax/search-columns-result.php",
        success: show_result,
        data: par,
        type: "POST"        
    });

    function show_result(rs) {
        if (rs != '') {
            $("#load_result").html(rs);
            $('#loader_bar').css('display',"none");
        } 
    }
}

function check_counter() {
    if( typeof check_counter.counter == 'undefined' ) { 
        check_counter.counter = 3;
    }
    return check_counter.counter++;
}
like image 366
supadema Avatar asked Jan 24 '26 01:01

supadema


1 Answers

It looks to me like each time you call show_results, you are overwriting any previous results from the auto load:

$("#load_result").html(rs);

This would cause your the elements to be removed and then the window would scroll up (because the height of the entire document is now shorter).

I think you instead want to call

$("#load_result").append(rs);

You would also need to change how you are creating/showing your loader. Instead of:

$("#load_result").html("<p id='loader_bar' style='width:100%; height:32px'></p>");

You would have a the #loader_bar in the DOM after the #load_result element, and simply toggle display: block/display: none

Demo of your code (slightly modified to get it to render, not sure what your DOM structure is like).

Demo of fix

like image 138
Lenny Sirivong Avatar answered Jan 26 '26 16:01

Lenny Sirivong