How to prevent document scrolling but allow scrolling inside div elements on websites for iOS and Android?

Timo picture Timo · Feb 28, 2013 · Viewed 89.7k times · Source

I created a website with jQueryMobile for iOS and Android.

I don't want the document itself to scroll. Instead, just an area (a <div> element) should be scrollable (via css property overflow-y:scroll).

So I disabled document scrolling via:

$(document).bind("touchstart", function(e){
    e.preventDefault();
});

$(document).bind("touchmove", function(e){
    e.preventDefault();
});

But that will also disable scrolling for all other elements in the document, no matter if overflow:scroll is set or not.

How can I solve this?

Answer

Volker E. picture Volker E. · Feb 28, 2013

How about this CSS only solution:

https://jsfiddle.net/Volker_E/jwGBy/24/

body gets position: fixed; and every other element you wish an overflow: scroll;. Works on mobile Chrome (WebKit)/Firefox 19/Opera 12.

You'll also see my various attempts towards a jQuery solution. But as soon as you're binding touchmove/touchstart to document, it hinders scrolling in the child div no matter if unbinded or not.

Disclaimer: Solutions to this problem are in many ways basically not very nice UX-wise! You'll never know how big the viewport of your visitors exactly is or which font-size they are using (client user-agent style like), therefore it could easily be, that important content is hidden to them in your document.