开发者

How to fire an event 300px above the end of the document

While scrolling, I want to fire an event 300px before the end of the document.

Say the height of my HTML document is 1000px and the height of the window viewport is 600px, on scrolling 100px down, the event should be fired.

I've this code

$(window).scroll(function(){
    if ($(window).scrollTop() == $(document).height() - $(window).height() ){
        callFunction();
    }
});

This fires the event when the scroll has reached the bottom. So I modified it as

$(window).scroll(function(){
    var height = $(window).height() + 300;
    if ($(window).scrollTop() == $(document).height() - height ){
        callFunction();
    }
}开发者_如何学运维);

But obviously, it seems to be wrong since it doesn't work. Please Help.


var down = $(window).height() + 300;
if ($(window).scrollTop() > $(document).height() - down){

try this one

Working demo


I think the problem you are having is that the scrollTop will never have exactly the right pixel value you are looking for. Your math is correct but use a > instead of == and you should be more successful.

$(window).scroll(function(){
    var height = $(window).height() + 300;
    if ($(window).scrollTop() > $(document).height() - height ){
        callFunction();
    }
});


I had to modify your script a bit but here is an example:

var invoked = false;
var height = $(document).height() - 300 - $(window).height();
$(window).scroll(function(){
    if ($(window).scrollTop() >= height && !invoked ){
        invoked = true; // don't call this twice
        alert('foo');
        callFunction();
    }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜