Search code examples
javascripthtmlcssjquery-mobilescroll

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


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?


Solution

  • Finally, I got it to work. Really simple:

    var $layer = $("#layer");
    $layer.bind('touchstart', function (ev) {
        var $this = $(this);
        var layer = $layer.get(0);
    
        if ($this.scrollTop() === 0) $this.scrollTop(1);
        var scrollTop = layer.scrollTop;
        var scrollHeight = layer.scrollHeight;
        var offsetHeight = layer.offsetHeight;
        var contentHeight = scrollHeight - offsetHeight;
        if (contentHeight == scrollTop) $this.scrollTop(scrollTop-1);
    });