0

I want to dedect if the user scrolls to the top of a webpage when he is already on the top. This means that normal scrolling shouldn't trigger a action, just if the scrollbar is on the top and the user scrolls further to the top it does something.

I have tried with the code below, but it triggers when the user arrives on top and not when he "overscroll" it. Here is the jsfiddle.

window.onscroll = function(ev) {
    if ((window.innerHeight + window.scrollY) ==window.innerHeight) {
        alert("The action");
    }
    document.getElementById('a').innerHTML= window.scrollY+";"+window.innerHeight+";"+(window.innerHeight+ + window.scrollY);
};
p{
  position: fixed;
}
<br>
<br><br>
<br>
<p id="a">sdf
</p>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>

4
  • What does it not do now? Also use console.log instead of alert to not interrupt the scrolling Commented Apr 14, 2017 at 6:33
  • When the user is on the top and scrolls up it doesn't triggers Commented Apr 14, 2017 at 7:40
  • And if you test || scrollY==0 ? Commented Apr 14, 2017 at 8:07
  • the problem is that the onscroll won't be triggered if you scroll up when you ar already on the top Commented Apr 14, 2017 at 11:54

1 Answer 1

1

If it's acceptable to ignore the top line of pixels in the window then you can set the scroll position at one pixel down. Then if the user scrolls up into this zone then good things happen.

You could try something like this fiddle:

var scrolling = false, w = $(window);
w.scrollTop(1);

w.on({
 scroll: function() {
   if(w.scrollTop() === 0){ // are we in the 'zero bufferzone'?
     $('#monitor').text('overscrolling');
   }
        
    clearTimeout(scrolling); // reset timer
    scrolling = setTimeout(function() {
        if(w.scrollTop() === 0){
           w.scrollTop(1); // shift down by a pixel
           $('#monitor').text(''); // reset
        }
    }, 250);
    }
});
body{
  height: 3000px;
}

#monitor{
  position: fixed;
  left: 1em;
  bottom: 1em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id='monitor'></div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.