Disable scrolling in all mobile devices
html, body {
overflow-x: hidden;
}
body {
position: relative;
}
The position relative is important, and i just stumbled about it. Could not make it work without it.
cgvector answer didn't work for me, but this did:
document.body.addEventListener('touchstart', function(e){ e.preventDefault(); });
I wouldn't leave it just like that, a smarter logic is needed to select when to prevent the scrolling, but this is a good start.
Taken from here: Disable scrolling in an iPhone web application?
For future generations:
To prevent scrolling but keep the contextmenu, try
document.body.addEventListener('touchmove', function(e){ e.preventDefault(); });
It still prevents way more than some might like, but for most browsers the only default behaviour prevented should be scrolling.
For a more sophisticated solution that allows for scrollable elements within the nonscrollable body and prevents rubberband, have a look at my answer over here:
https://stackoverflow.com/a/20250111/1431156
I suspect most everyone really wants to disable zoom/scroll in order to put together a more app-like experience; because the answers seem to contain elements of solutions for both zooming and scrolling, but nobody's really nailed either one down.
Scrolling
To answer OP, the only thing you seem to need to do to disable scrolling is intercept the window's scroll
and touchmove
events and call preventDefault
and stopPropagation
on the events they generate; like so
window.addEventListener("scroll", preventMotion, false);
window.addEventListener("touchmove", preventMotion, false);
function preventMotion(event)
{
window.scrollTo(0, 0);
event.preventDefault();
event.stopPropagation();
}
And in your stylesheet, make sure your body
and html
tags include the following:
html:
{
overflow: hidden;
}
body
{
overflow: hidden;
position: relative;
margin: 0;
padding: 0;
}
Zooming
However, scrolling is one thing, but you probably want to disable zoom as well. Which you do with the meta tag in your markup:
<meta name="viewport" content="user-scalable=no" />
All of these put together give you an app-like experience, probably a best fit for canvas.
(Be wary of the advice of some to add attributes like initial-scale
and width
to the meta tag if you're using a canvas, because canvasses scale their contents, unlike block elements, and you'll wind up with an ugly canvas, more often than not).
Try adding
html {
overflow-x: hidden;
}
as well as
body {
overflow-x: hidden;
}