Prevent page scroll on drag in IOS and Android

Danny Fox picture Danny Fox · Feb 12, 2012 · Viewed 38.5k times · Source

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

Answer

dmp picture dmp · Feb 12, 2012

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.