scrolling to bottom of page run function - functio

2019-07-27 09:05发布

i am trying to build a function that when you scroll to the bottom of the page it runs a function to load in more items on a page.

I started by putting in a div with no content

<div id="loadMore"></div>

and then i found on here another function that looks at the scroll

function isScrolledIntoView(elem)
{
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();
    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();

    console.log(docViewTop, docViewBottom, elemTop, elemBottom);
    return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom) && (elemBottom <= docViewBottom) && (elemTop >= docViewTop));

}

$(window).scroll(function() {   

    if(isScrolledIntoView($('#loadMore')))
    {
        alert("reached");
        return false;

    }    
});

one problem is it seems to alert reached too soon and the other main problem is that it alerts "reached" back to the screen so many times - this is obviously bad because I would only want the function to run once...

then it would load in the other content and if the bottom of the page was reached again then the function (alert in eg) would run again

am i going about this the best way? and can anyone help?

thanks

2条回答
Juvenile、少年°
2楼-- · 2019-07-27 09:36

When working with the scroll function you need to be careful as the event is triggered once for every pixel scrolled. Therefore you need to use a timeout to only call the function when scrolling has stopped. Try this:

var timer;
$(window).scroll(function () {
    clearTimeout(timer);
    timer = setTimeout(function() {
        if (isScrolledIntoView($('#loadMore'))) {
            alert("reached");
            return false;
        }
    }, 50);
});

Example fiddle

查看更多
爷、活的狠高调
3楼-- · 2019-07-27 09:44

you should bind your function only once. after adding new items to the page u can check if more items are available and rebind this function again.

var addNewContent = function () {
    // get new data
    // append new data
    $('#content').prepend($('<div style="height: 1000px;">some content</div>'));

    // rebind the event, if still more data is available
    $('#content').one( 'endofcontent', addNewContent);
};

$('#content').one("endofcontent", addNewContent);

$(window,document).scroll(function() {

    if(isScrolledIntoView($('#loadMore'))) {
        $('#content').trigger("endofcontent");
        return false;
    }
});

test it: http://fiddle.jshell.net/d5CSd/

查看更多
登录 后发表回答