Gehtnet
Gehtnet

Reputation: 447

Detect scrolling on top of webpage with javascript

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>

Upvotes: 0

Views: 381

Answers (1)

Sam0
Sam0

Reputation: 1459

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>

Upvotes: 1

Related Questions