Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing elastic scrolling on OS X Chrome and Safari

I'm looking for a way to prevent the elastic scrolling that occurs on OS X in both Chrome and Safari.

If you don't understand what I mean, it's when you scroll up while the page is at the top, or down when the page is at the bottom, and it shows a gray background behind the page.

There is a css solution for single page apps where you just add overflow:hidden to the html or body

However, I need to be able to scroll.

I've come up with a solution using Javascript (JQuery), but it's only for scrolling passed the top, and only works for chrome. Also, it's a bit buggy in Safari.

$(window).on('scroll', function(e){
   scrollAmount = $(this).scrollTop();
   if(scrollAmount < 1){
      $(this).scrollTop(1);
   }
});

So that's just checking of the user scrolls below 1 meaning they try to scroll up passed where the page ends. I tried 0 but that didn't work. I haven't been able to find a way to check if the user scrolls passed the bottom of the page.

So any thoughts?

Edit:

$(window).on('scroll', function(e){
   scrollAmount = $(this).scrollTop();
   if(scrollAmount < 1){
      $(this).scrollTop(1);
   }
   if(scrollAmount > $(document).height() - $(window).height()){
      $(this).scrollTop($(window).height());
   }
});

Now I've added a check for if we scroll passed the bottom of the page. This method is not working though, it's bouncing around very ungracefully.

like image 510
Kolby Avatar asked Feb 21 '13 02:02

Kolby


2 Answers

When you quickly scroll up to the top, the elastic browser causes the scroll top to become negative. Using the st <= 0, will make sure no action is taken when this happens.

$(window).on('scroll',function(){
    var dh = $(document).height(),
        wh = $(window).height(),
        st = $(window).scrollTop();
    if (st <= 0) {
        $(this).scrollTop(0);
    } else if (st + wh >= dh) {
        $(this).scrollTop(dh);
    }
});
like image 117
user943846 Avatar answered Sep 24 '22 17:09

user943846


You can now use overscroll-behavior:

html, body {
  overscroll-behavior: none;
}
like image 38
Yoann Avatar answered Sep 25 '22 17:09

Yoann