While Scrolling: if scrollTop() equals to or reach

2019-06-10 07:45发布

问题:

I'm trying to fire an event when scrolling down to a certain point/value and execute again when scroll back up and down again.

I tried:

$(window).scroll(function(){
    var sTop = $(this).scrollTop();

    if(sTop == 300){
        //execute event - failed
    }

});

The above does not fire anything with the both mousewheel and dragging the scrollbar. but when I changed the condition to greater than or equal to, the event is being executed but multiple times when scrolling further down.

if(sTop >= 300){
    //execute event - success
}

I also tried changing the condition value and some times the event is being fired.

if(sTop == 333 /* or 431, 658, etc. */){
    //execute event - sometimes success
}

Here is my test fiddle.

Could it be that scroll() function sometimes skips a value if you scroll fast?

Can someone explain the issue and help me with a workaround on how to trigger an event when the $(window).scrollTop() == 'value'. Thanks

回答1:

You're facing this issue because there are no guarantees that scrolling will be done in increments of 1. For example, some scroll wheels increment in values of 30. This means that you'd get a scroll event on 30, 60, 90, etc.

The best way to test if scrolling has reached your limit is to see if it has gone past the point you're wanting, then resetting the scroll to the precise point you're wanting. So you'd do:

if(sTop >= 300){
    $(window).scrollTop(300);
}

Here's an updated link to your JSFiddle with a working example: http://jsfiddle.net/bC3Cu/4/

If you take a look at unit of increment in scrollable areas / divs in javascript? it describes how to set it to where you can override the scroll increment. Using that method, you should be able to predict how many units the user has scrolled without preventing them from scrolling further down the page.