user1480019
user1480019

Reputation:

Detect pinch to zoom when 'user-scalable' is set to yes

How can I detect the scale (or distance pinched) of the pinch to zoom when the meta name="viewport" is set to user-scalable=yes?

I've tested on Android but the pinch to zoom can't be detected if the meta name="viewport" is set to user-scalable=yes. If the meta name="viewport" is set to user-scalable=no then the pinch to zoom can be detected but then I'm not able to zoom in on the document.

Here are my tests on jsFiddle:

Hammer.js: http://jsfiddle.net/pE42S/

var pziW = "test";
var viewport_width = $(window).innerWidth();
var zoom = 0;

var hammer = new Hammer(document.getElementById("touchme"));

hammer.ontransformstart = function(ev) {
    console.log("ontransformstart");
    console.log(ev);
    //pziW = $(window).innerWidth() / 2 * ev.scale;
    zoom = ev.scale;
    var msg = "ontransformstart " + pziW + " scale " + zoom;
    log(msg);
};
hammer.ontransform = function(ev) {
    console.log("ontransform");
    console.log(ev);
    zoom -= ev.scale;
    viewport_width+=viewport_width*zoom;
    zoom = ev.scale;
    pziW=viewport_width;
    //pziW = $(window).innerWidth() / 2 * ev.scale;
    jqUpdateSize();
    var msg = "ontransform " + pziW + " scale " + zoom;
    log(msg);
};
hammer.ontransformend = function(ev) {
    console.log("ontransformend");
    console.log(ev);
    var msg = "ontransformend " + pziW + " scale " + zoom;
    log(msg);
};

TouchSwipe: http://jsfiddle.net/pE42S/1/

$(function() {      
    $("#touchme").swipe( {
        pinchStatus:function(event, phase, direction, distance , duration , fingerCount, pinchZoom) {
            console.log("pinchStatus");
            console.log(event);
            pziW=viewport_width - distance;
            $("#log").text(pziW);
            jqUpdateSize();
        },
        fingers:2,  
        pinchThreshold:0  
    });
});

Somebody has an answer?

Upvotes: 7

Views: 5242

Answers (2)

Grigory
Grigory

Reputation: 43

Now you can use Visual Viewport API for this (not for all browsers). Just check window.visualViewport.scale > 1.

Upvotes: 3

Bruno
Bruno

Reputation: 719

One way to achieve this would be with a generic touchstart handler:

  • Wait until the user starts touching at least two points ( event.touches.length > 1)
  • Note the x & y start coordinates for both touches, attach touchend listeners
  • Wait until the touches end.
  • Remove touchend listeners & measure distance.

Even easier would be using gesture events and the event.scale property, see the great answers at Simplest way to detect a pinch for more details.

Upvotes: 0

Related Questions