1

My problem is, that after fast scrolling down with the touchpad, the window is correctly jumping to the top after 300px, but after that, the browser is stil scrolling down.

Here is a example of my problem https://codepen.io/anon/pen/XoMExW

I´ve tried this, but it didn´t work

How to disable scrolling temporarily?

$(window).scroll(function(){
if( $(window).scrollTop() >= 300 ){
   $(window).scrollTop(0);
}
});
RainPara
  • 19
  • 2
  • 1
    When you make a fast scroll, the window scrolls `300px` down then moves up to `0px`. But the scroll is still there. So the scroll handler is fired again. So there won't be this issue if your scroll is real quick and short. – Elish Dec 22 '18 at 02:45

1 Answers1

2

What you could do is after each scroll event, add a setTimeout. For every scroll event, you will first clear the one you created in the previous event and recreate a new one right after. This will keep running until you reach the last scroll event, then during this last scroll event, the callback of the setTimeout will be triggered and it will run your code:

var isScrolling;

$(window).scroll(function() {
    window.clearTimeout(isScrolling);
    isScrolling = setTimeout(function() {
        if ($(window).scrollTop() >= 300) {
            $(window).scrollTop(0);
        }
    }, 100);
});
Pingolin
  • 3,161
  • 6
  • 25
  • 40
  • 1
    Thank you, i´ve tried this before, but the problem is still remaining, because sometimes the browser scrolling lasts longer than 2 seconds and if i would increase the timer > 2 seconds, this would be a too long time in which the user can´t scroll again. – RainPara Dec 21 '18 at 21:09
  • 1
    I am not sure I understand what you mean with the 2 seconds? – Pingolin Dec 21 '18 at 22:03
  • 1
    It is important to me that the user can scroll directly after the last scroll he made. In your code the timer has 100ms, but if the user scrolls fast enaugh, it is possible, that the scrolling takes about 2 seconds to stop after releasing the touchpad. That means, that i would need to set the timer to over 2 seconds, but then in this 2 seconds the user could not make a new scroll interaction. – RainPara Dec 22 '18 at 00:10