Search code examples
iossafariwebkitscrolltouch

How to disable web page's default scroll effect on iOS' Safari?


On iOS' Safari's bookmarks, there's one item "iPad User Guide" or "iPad User Guid". Open it. You can see that entire page can't be scrolled. And sections in the page can be scrolled.

I need to achieve same effect. But I don't wanna use any JS plug-ins like iScroll.

I use JS codes below to disable the default scroll of entire page:

document.addEventListener('touchmove', function (event) {
    event.preventDefault();
}, false);

And then use CSS codes -webkit-overflow-scrolling: touch; to enable scroll effect to a div element.

But the issue is my CSS codes can't work if I use my JS codes. My div element can't be scrolled when users touch move.

How to resolve this problem? Thank you!


Solution

  • The problem with your code is document.addEventListener. Adding a event listener to the whole document will get you into trouble as you noted. Instead you should only add it to the elements you don't want to have iOS overflow scrolling (any formal name for this?).

    Adding -webkit-overflow-scrolling: touch; will cause the element to have inertial scroll within that element, but it only works properly on first scroll within the element. So if you hit the top or bottom of the scrollable element, and you scroll to the top again for example, it will move the whole page instead of just that element. There is no solution I am aware of for this to work properly.

    The best solution will be to add a event listener to all elements with a class with no-scroll. Like this (using jQuery to select the elements with a class for simplicity):

    $('.no-scroll').on('touchmove', function (event) {
      event.preventDefault();
    }, false);
    

    You might be able to prevent the second scroll from having any effect by putting it in another scrollable element. So instead of scrolling the whole page on double scroll, it will scroll the parent element, if this is possible at all.