Andrew
Andrew

Reputation: 14526

Prevent scrolling in Android browser

Is there a way to prevent scrolling of a rendered HTML page in the Android browser? The following does not appear to have any impact on page scrolling in the Android browser:

var preventDefault = function(e) {
    e.preventDefault();
    return false;
};
document.addEventListener('touchmove',preventDefault,false);
document.body.addEventListener('touchmove',preventDefault,true);
window.addEventListener('touchmove',preventDefault,true);

(I've tried with bubbling on and off.)

It looks to me like Android Webkit makes the "window" the same length as the document, so scrolling is being done on the browser itself, not on the document body or DOM window object. What's weird is that that's exactly what webkit on iOS does, but the code above still works.

Upvotes: 4

Views: 5402

Answers (2)

ColCh
ColCh

Reputation: 3063

Not works on Chrome on Android though

But preventing event on window and stopping immediate propagation helps!

Handler should be not passive to do that.

MAY BE adding an event handler on capturing phase would help too

But this snippet below is tested by me

window.addEventListener("touchmove", function(event) {
    event.preventDefault();
    event.stopImmediatePropagation();
}, { passive: false });

DEMO https://codepen.io/ColCh/full/qvLqoe

Upvotes: 0

Andrew
Andrew

Reputation: 14526

Answering my own question.

The problem ended up being that you need to capture and suppress ontouchstart as well as ontouchmove on document to stop the browser from scrolling. This is definitely different in iOS, but it still works identically on both platforms.

The actual code I ended up using looks sort of like this:

var preventDefault = function(e){
    e.preventDefault();
};
var touchstart = function(e) {
    document.addEventListener('touchstart', preventDefault,false);
    document.addEventListener('touchmove',  preventDefault,false);
    /*do other stuff*/
};
var touchend = function(e) {
    document.removeEventListener('touchstart', preventDefault,false);
    document.removeEventListener('touchmove',  preventDefault,false);
};

element.addEventListener('touchstart',  touchstart, false);
element.addEventListener('touchend',    touchend,   false);

Upvotes: 5

Related Questions