Search code examples
jqueryweb-applicationsrubber-band

How to disable rubber band in iOS web apps?


This:

$('body').on('touchmove', function(e) { e.preventDefault(); });

Works, but will disable scrolling throughout the whole page, which is far from ideal.

This:

$('*').on('touchstart', function(e){
    var element = $(this).get(0);

    if ( element.scrollTop <= 0 )                                           element.scrollTop = 1;
    if ( element.scrollTop + element.offsetHeight >= element.scrollHeight ) element.scrollTop = element.scrollHeight - element.offsetHeight - 1;
});

Works on pages that have a scrolling area. However when there is nothing to scroll it will again show the rubber-band.

So my question:

How can you disable the rubber band effect and still keep the -webkit-overflow-scrolling areas scrollable?

[Update]

Best Solution

Disable scrolling on all non-scrollable elements such as a tab bar or a navigation bar.

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

Attach a scroll handler to the scrollable elements such as the main content.

anElement.addEventListener('touchstart', function( event ){
        if( this.scrollTop === 0 ) {
            this.scrollTop += 1;
        } else if( this.scrollTop + this.offsetHeight >= this.scrollHeight ) {
            this.scrollTop -= 1;
        }
}

Solution

  • Now there is actually a simple modern CSS way to handle this, no JavaScript needed. And it is supported on all modern browser, including Safari on iOS.

    html, body {
        overscroll-behavior: none;
    }
    

    caniuse.com says it is the baseline since 2022.