Perform ajax when html element is displayed on user screen

I have this script that makes an ajax request when the user reaches the end of the page. It is based on a scroll event. When the page loads, I only show 16 products on the user's screen, and when he scrolls down, I want to load 16 more products. My script works, but it is making more than one ajax request, which is not what I want. The idea is to show another set of 16 products. script:

$(window).scroll(function() {
    if ($(window).scrollTop() + $(window).height() > $('.made').offset().top) {
        //here I count how many products I have shown already   
        var productsshown = $(".productcell").length;
        $('.made').hide();
        $.ajax({
            type: "post",
            url: "./ajax/get_more_products.php",
            data: {
                "product": productsshown
            },
            dataType: 'json',
            cache: false,
            success: function(data) {
                $("#bcontent").html(data);
                $('.made').show();
            }
        });
    }
});

      

As you can see, I have a div that I am using as a controller, and when the user sees this div - ajax is executed. Result from ajax disappears into another div withid="content"

How to avoid scroll event to make ajax call more than once? I tried hiding my div div. And after the ajax response. I show it again so that it can be executed on 16 more products when the user navigates to it again. But ajax is always called executed more than once, which is how I want it ..

+3


source to share


4 answers


hmm, Here's a small addition to your code, adding the swiched flag as you load more items:



var _itemsLoading = false;
if ((!_itemsLoading) && ($(window).scrollTop() + $(window).height() > $('.made').offset().top)) {
    //here I count how many products I have shown already   
    var productsshown = $(".productcell").length;
    $('.made').hide();
    _itemsLoading = true;
    $.ajax({
        type: "post",
        url: "./ajax/get_more_products.php",
        data: {
            "product": productsshown
        },
        dataType: 'json',
        cache: false,
        success: function(data) {
            $("#bcontent").html(data);
            $('.made').show();
            _itemsLoading = false;
        }
    });
}

      

+2


source


Just store the timestamp, then you fire your ajax request and reset, then it will come back or 2 seconds later .... then the timestamp is set, don't fire your requests.



+1


source


I am not handling the scroll event. I am using setInterval () and I am checking if the position has changed since the previous tic.

+1


source


I just replaced

if ($(window).scrollTop() + $(window).height() > $('.made').offset().top) {

      

from:

if($(window).scrollTop() + $(window).height() == $(document).height()){

      

and used the footer of the page as an ajax controller. It works now, thanks!

+1


source







All Articles