Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent page scroll on drag in IOS and Android

I'm working on a html5 canvas game, but I don't know how to handle touch events. When a user touch the screen, and drag, then the browser will scroll the page. I would like to prevent it, and get the touch start, and touch end position. Is it possible?

Thanks in advance

like image 681
Danny Fox Avatar asked Sep 02 '25 05:09

Danny Fox


2 Answers

You need to override the default touch behaviour to stop touchevents dragging the page. Clearly, you'll need to handle them again if your page becomes larger than the available area, but as you're making a game, going to assume you're doing 100%/100% layout.

function preventBehavior(e) {
    e.preventDefault(); 
};

document.addEventListener("touchmove", preventBehavior, {passive: false});

Edit: here's the W3C recommendation talking about touch events, which might be handy for you.

like image 69
dmp Avatar answered Sep 04 '25 20:09

dmp


Due to breaking changes made in recent versions of Chrome, the above answers are no longer correct. Attaching a touch event listener to the document or body elements will cause the event listener to be registered in "passive" mode, which causes calls to preventDefault to be ignored.

There are two solutions:

  • The preferred solution is to use the CSS style touch-action to specify that no scrolling should happen (e.g. with the value "none")

  • In cases where this is not appropriate (e.g. if the type of interaction should change dynamically in a way that cannot be determined before the gesture begins) then the event listener must be registered with the third parameter set to { passive: false } (you should perform browser detection to ensure that this style is supported first, though).

like image 37
Jules Avatar answered Sep 04 '25 18:09

Jules