How to Disable Scrolling on Mobile Devices
So let’s start out with setting the viewport meta in the head tags to non-scalable, like so:<meta name="viewport" content="width=device-width, user-scalable=no">
This will disable the pinch–and–zoom effect as expected, but if you swipe vertically, the viewport will scroll and you’ll end up seeing a random bar at the bottom of the HTML page. That “bar” is the color of the HTML page below your view, which is showing because of what seems like extra padding at the bottom of the HTML. I’m not sure why this happens, but it’s not an issue with your code! This undesired effect happens on both Android and iOS browsers. In addition to how bad it looks, your app or game just got moved out of the viewport slightly!
Luckily, this is an easy fix. If you’re using jQuery, you would use this snippet of code:
$(document).bind('touchmove', function(e) {
e.preventDefault();
});
Otherwise, if you’re not, here’s the javascript straight-up:
document.addEventListener('touchmove', function(e) {
e.preventDefault();
}, false);
What is the code doing?
Essentially, you are just adding an event listener for the mobile browser “touchmove” event. When the listener hears that event it fires the anonymous callback function that passes the “touchmove” event as a parameter and prevents its default action. This reasoning is the same for both the jQuery and javascript snippets above, the only differences are syntax.
Like I said, easy to fix, but painful if you are unaware of why that’s happening. It’s one of those bugs that would drive you crazy and kill way too much time if you didn’t know. I hope this little tip on how to disable scrolling on mobile devices was helpful and as always, please share your thoughts and comments below.
Comments
Post a Comment