How to prevent native browser default pinch to zoom behavior? - javascript

This question has been asked in a couple different flavors, but none satisfy.
The native browser (Google Chrome for Mac, for instance) supports the "pinch to zoom" gesture by default which will zoom the whole viewport. How do I disable (react to) this default behavior so I can write my own pinching/zooming logic? Google Maps https://maps.google.com/ seems to have achieved this since pinching on the map will only scale the map area, leaving the rest of the UI intact, while pinching on the left sidebar shows the default behavior.
I have tried a few approaches such as HTML "viewport" meta tag, CSS touch-action: none; and JavaScript document.addEventListener('touchmove', e => { e.preventDefault() }), but they all seem to only work on mobile.

I accidentally found a solution which works on Chrome. You basically have to preventDefault the "wheel" event. ctrlKey will be true if it is a pinch event instead of a scroll.
element.addEventListener('wheel', event => {
const { ctrlKey } = event
if (ctrlKey) {
event.preventDefault();
return
}
}, { passive: false })
I'd guess this is how Google Maps does it.
The (most) cross-browser solution is probably a combination of the techniques mentioned: user-scalable=no in the "viewport" meta tag for the browsers that do support it and this one for native Chrome.

Use this meta tag:
<meta name='viewport' content='width=device-width, height=device-height, initial-scale:1, user-scalable=no' />

Related

iOS Safari - disable pinch to zoom option

I have an issue with zooming. I want to block pinch to zoom in Mobile Safari on HTML elements. I use script to prevent default behavior of browser and it is working fine for normal pinching, but when I start scroll with one finger and later add second and pinch Safari still zooming the page...
Has anyone any idea how can I block this zooming?
I'am creating mobile game using canvas and use HTML for message windows so please don't write that it is a bad idea to block zooming for accessibility reasons.
Code to prevent zooming:
document.addEventListener("touchmove", function(event) {
event = event.originalEvent || event;
if(event.touches.length > 1 || event.scale > 1) {
event.preventDefault();
}
}, false);
UPDATE:
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
This meta tag doesn't work because Apple disable it in Mobile Safari since iOS 10 up to accessibility reasons
can you test it?
document.documentElement.addEventListener('touchmove', function (event) {
event.preventDefault();
}, false);

looking for other ways to Prevent Panning and Zooming on blackberry 10

I'm building js application on top of BlackBerry 10 WebWorks SDK and i'm looking other whys to prevent Panning and zooming behavior.
I tried the ios method by disable the default touchmove behavior but it cause other bugs that i can afford.
<script type="text/javascript">
function preventBehavior(e) {
e.preventDefault();
}
document.addEventListener('touchmove', preventBehavior, false);
</script>
other suggestion ??
If you're referring to the viewport panning/scaling/bouncing you get when not setting up your viewport have a go at this:
I generally add this in the of my index html file.
<!-- set viewport -->
<script>
var meta = document.createElement("meta");
meta.setAttribute('name','viewport');
meta.setAttribute('content','initial-scale='+ (1/window.devicePixelRatio) + ',user-scalable=no');
document.getElementsByTagName('head')[0].appendChild(meta);
</script>

Disable scrolling when touch moving certain element

I have a page with a section to sketch a drawing in. But the touchmove events, at least the vertical ones, are also scrolling the page (which degrades the sketching experience) when using it on a mobile browser. Is there a way to either a) disable & re-enable the scrolling of the page (so I can turn it off when each line is started, but turn it back on after each is done), or b) disable the default handling of touchmove events (and presumably the scrolling) that go to the canvas the sketch is drawn in (I can't just disable them completely, as the sketching uses them)?
I've used jquery-mobile vmouse handlers for the sketch, if that makes a difference.
Update: On an iPhone, if I select the canvas to be sketched in, or just hold my finger for a bit before drawing, the page doesn't scroll, and not because of anything I coded in the page.
Set the touch-action CSS property to none, which works even with passive event listeners:
touch-action: none;
Applying this property to an element will not trigger the default (scroll) behavior when the event is originating from that element.
Note: As pointed out in the comments by #nevf, this solution may no longer work (at least in Chrome) due to performance changes. The recommendation is to use touch-action which is also suggested by #JohnWeisz's answer.
Similar to the answer given by #Llepwryd, I used a combination of ontouchstart and ontouchmove to prevent scrolling when it is on a certain element.
Taken as-is from a project of mine:
window.blockMenuHeaderScroll = false;
$(window).on('touchstart', function(e)
{
if ($(e.target).closest('#mobileMenuHeader').length == 1)
{
blockMenuHeaderScroll = true;
}
});
$(window).on('touchend', function()
{
blockMenuHeaderScroll = false;
});
$(window).on('touchmove', function(e)
{
if (blockMenuHeaderScroll)
{
e.preventDefault();
}
});
Essentially, what I am doing is listening on the touch start to see whether it begins on an element that is a child of another using jQuery .closest and allowing that to turn on/off the touch movement doing scrolling. The e.target refers to the element that the touch start begins with.
You want to prevent the default on the touch move event however you also need to clear your flag for this at the end of the touch event otherwise no touch scroll events will work.
This can be accomplished without jQuery however for my usage, I already had jQuery and didn't need to code something up to find whether the element has a particular parent.
Tested in Chrome on Android and an iPod Touch as of 2013-06-18
There is a little "hack" on CSS that also allows you to disable scrolling:
.lock-screen {
height: 100%;
overflow: hidden;
width: 100%;
position: fixed;
}
Adding that class to the body will prevent scrolling.
document.addEventListener('touchstart', function(e) {e.preventDefault()}, false);
document.addEventListener('touchmove', function(e) {e.preventDefault()}, false);
This should prevent scrolling, but it will also break other touch events unless you define a custom way to handle them.
The ultimate solution would be setting overflow: hidden; on document.documentElement like so:
/* element is an HTML element You want catch the touch */
element.addEventListener('touchstart', function(e) {
document.documentElement.style.overflow = 'hidden';
});
document.addEventListener('touchend', function(e) {
document.documentElement.style.overflow = 'auto';
});
By setting overflow: hidden on start of touch it makes everything exceeding window hidden thus removing availability to scroll anything (no content to scroll).
After touchend the lock can be freed by setting overflow to auto (the default value).
It is better to append this to <html> because <body> may be used to do some styling, plus it can make children behave unexpectedly.
EDIT:
About touch-action: none; - Safari doesn't support it according to MDN.
try overflow hidden on the thing you don't want to scroll while touch event is happening. e.g set overflow hidden on Start and set it back to auto on end.
Did you try it ? I'd be interested to know if this would work.
document.addEventListener('ontouchstart', function(e) {
document.body.style.overflow = "hidden";
}, false);
document.addEventListener('ontouchmove', function(e) {
document.body.style.overflow = "auto";
}, false);
I found that ev.stopPropagation(); worked for me.
To my surprise, the "preventDefault()" method is working for me on latest Google Chrome (version 85) on iOS 13.7. It also works on Safari on the same device and also working on my Android 8.0 tablet.
I am currently implemented it for 2D view on my site here:
https://papercraft-maker.com
this worked for me on iphone
$(".owl-carousel").on('touchstart', function (e) {
e.preventDefault();
});
the modern way (2022) of doing this is using pointer events as outlined here in the mozilla docs: https://developer.mozilla.org/en-US/docs/Web/API/Pointer_events
Pointer events build on touchstart and other touch events and actually stop scroll events by default along with other improvements.

Disabled Pinch Zoom on Mac Touchpad with JavaScript

Is there anyway to disable the pinch zooming available on mac's touchpad on the desktop?
I tried adding:
<meta content='True' name='HandheldFriendly' />
<meta content='width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;' name='viewport' />
but this did nothing. Thanks!
I faced similar problem where I wanted to disable pinch-zoom gesture on windows machine, here's javascript code snippet that worked for me
window.addEventListener('wheel', (e) => {
if (e.ctrlKey) {
e.preventDefault();
}
}, {
"passive": false
});
FYI - Along with disabling the pinch-zoom functionality it also disables ctrl+mouse wheel up/down event functionality.
jsbin POC

Prevent horizontal scroll in iOS WebApp

I've encountered similar problems before and could never really understand the workarounds, and so I ended up relying on plugins like iScroll. This is such simple task that I refuse to include a plugin for it - what I want is to prevent horizontal scroll in iOS. This includes the rubber band effect for any content that might be on the page but that isn't visible.
From what I understand I need to disable the rubber band altogether first and then apply the touch scroll to a container element (which I've given the id "touch"). Not sure if this is the right approach?
$(document).bind('touchmove', function(e) {
if (!e.target == '#touch') {
e.preventDefault();
}
});
Style for #touch
-webkit-overflow-scrolling: touch;
overflow: hidden;
height: 100%;
#media only screen and (max-width: 768px) {
width: 768px;
}
This doesn't prevent the horizontal width from staying at 728px however, the user is still able to scroll and see the hidden content. Ideas?
Well, the above metas are useful as such:
<meta content="yes" name="apple-mobile-web-app-capable" />
<meta content="minimum-scale=1.0, width=device-width, maximum-scale=1, user-scalable=no" name="viewport" />
They prevent that bug in Safari that happens when the user rotates the screen. However, the most proper way to accomplish the desired functionality is:
Use a parent div with overflow hidden and make sure the height of this div is limited according to the viewport and a child div with overflow:auto or the css 3 overflow-y:scroll. So basically if the size of the content inside the child div exceeds the default size of the child, you can vertically/horizontally scroll through it. Because the parent has overflow:hidden, the content outside of the child will not be displayed, so you get a proper scroll effect. ** Also, if you use overflow: hidden and prevent default for all touchEvents, there will be no scrolling or weird browser behavior**
With the help of JavaScript, make sure that every element in the DOM is scaled according to the viewport, so avoid using static sizes for as many elements as possible.
Bind the touchStart, touchMove and touchEnd events. Safari doesn't always fire a touchEnd event unless a touchMove event is listened for as well. Even if it's just a placeholder, put it there to avoid the inconsistent behavior in Safari.
Horizontal sliding is possible in two ways: load new content in the same div after you detect the slide direction or populate that child div with all the elements and you are good to go and actually shifting the margins/position of the child inside it's parent to 'scroll'. Animation can be used for a slicker interface.
Bind your touch event listeners. I don't know what library or event management system you are using, but it doesn't matter. Just call the respective function for the respective task.
Get the slide direction(left/right):
var slideBeginX;
function touchStart(event){event.preventDefault();//always prevent default Safari actions
slideBeginX = event.targetTouches[0].pageX;
};
function touchMove(event) {
event.preventDefault();
// whatever you want to add here
};
function touchEnd(event) {
event.preventDefault();
var slideEndX = event.changedTouches[0].pageX;
// Now add a minimum slide distance so that the links on the page are still clickable
if (Math.abs(slideEndX - slideBeginX) > 200) {
if (slideEndX - slideBeginX > 0) {
// It means the user has scrolled from left to right
} else {
// It means the user has scrolled from right to left.
};
};
};
This work for me on Android, iPhone and iPad.
<!doctype html>
<html>
<head>
<meta content="yes" name="apple-mobile-web-app-capable" />
<meta content="minimum-scale=1.0, width=device-width, maximum-scale=1, user-scalable=no" name="viewport" />
<title>Main</title>
</head>
<body>
...
</body>
</html>
Following link might be useful to you, here vertical is disabled and horizontal enabled, you just need to tweak the code a little for your purpose.
jquery-tools-touch-horizontal-only-disable-vertical-touch
In case you aren't concerned about vertical sliding, you can try the following code also -
document.ontouchmove = function(e){
e.preventDefault();
}
Hope it helps.
If you dont use the meta you will always get a rubber band effect.
<meta name="viewport" content="width=device-width" />
Even if the page fitted exactly the user would still be able to stretch the page wider than it should be able to go, you must use the view port to prevent this, there is no other way...

Categories

Resources