SyntaxStudy
Sign Up
jQuery Advanced 5 min read

Pinch and Multi-Touch

Multi-Touch Gestures

Handle pinch-to-zoom with the native Touch API. jQuery does not wrap multi-touch — access the touches array directly via originalEvent.

Example
let initialDist = 0;
function dist(t) {
  return Math.hypot(t[0].clientX - t[1].clientX, t[0].clientY - t[1].clientY);
}
$("#zoomable").on("touchstart", e => {
  if (e.originalEvent.touches.length === 2)
    initialDist = dist(e.originalEvent.touches);
}).on("touchmove", e => {
  if (e.originalEvent.touches.length === 2) {
    e.preventDefault();
    const scale = dist(e.originalEvent.touches) / initialDist;
    $(this).css("transform", `scale(${Math.max(0.5, Math.min(scale, 4))})`)
  }
});
Pro Tip

Call e.preventDefault() in touchmove to prevent the browser from intercepting the pinch and zooming the page.