Blog>
Snippets

Double-Tap Zoom Implementation

Detect double-tap gestures and apply a zoom-in effect on an element, emulating native double-tap zoom behavior.
let lastTapTime = 0;
const doubleTapDelay = 300; // Time in ms to wait for a second tap
document.addEventListener('touchstart', function(event) {
    const currentTime = new Date().getTime();
    const tapLength = currentTime - lastTapTime;
    if (tapLength < doubleTapDelay && tapLength > 0) {
        // Detected a double tap
        event.preventDefault(); // Prevent default action (like zooming)
        // Trigger zoom on the target element
        zoomElement(event.target);
    }
    lastTapTime = currentTime;
});

function zoomElement(element) {
    element.style.transform = 'scale(2)'; // Example zoom effect
    element.style.transition = 'transform 0.3s'; // Smooth transition for zoom effect
}
This code snippet detects double-tap gestures on the entire document and applies a zoom-in effect by transforming the scale of the tapped element to twice its original size. It uses a simple timing mechanism to determine if two taps occur within a short period (300ms), indicating a double-tap gesture.