Hammer.js Multi-touch Gestures

2.0.8 · abandoned · verified Sun Apr 19

Hammer.js is a JavaScript library designed for detecting and handling multi-touch gestures such as tap, doubletap, press, pan, swipe, pinch, and rotate in web applications. It aims to provide a unified API across touch, mouse, and pointer events, offering a lightweight solution with no external dependencies and a small footprint (7.34 kB minified + gzipped for v2.0.8). However, the main `hammerjs` package has not seen active development since its last stable release, version 2.0.8, published over 10 years ago on April 22, 2016. While it was a popular choice for gesture recognition, its maintenance status means that users often look to forks like `@egjs/hammerjs` for continued support or migrate to newer, actively maintained gesture libraries.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to initialize Hammer.js on an element, add a rotation recognizer, and listen for the 'rotate' event to dynamically transform the element. It also includes a basic tap event example.

document.addEventListener('DOMContentLoaded', () => {
  const stage = document.getElementById('stage');
  if (!stage) {
    console.error('Element with ID "stage" not found.');
    return;
  }

  // Create a manager for that element
  const mc = new Hammer.Manager(stage);

  // Create a recognizer for rotation
  const rotateRecognizer = new Hammer.Rotate();

  // Add the recognizer to the manager and enable it (pinch and rotate are often disabled by default)
  mc.add(rotateRecognizer);
  mc.get('rotate').set({ enable: true });

  // Subscribe to the rotate event
  mc.on('rotate', function(e) {
    const rotation = Math.round(e.rotation);
    stage.style.transform = `rotate(${rotation}deg)`;
    console.log(`Rotation: ${rotation} degrees`);
  });

  // Example for a simple tap recognizer
  const tapRecognizer = new Hammer.Tap();
  mc.add(tapRecognizer);
  mc.on('tap', function(e) {
    console.log('Tap detected!', e.target);
    e.target.style.backgroundColor = 'lightblue';
    setTimeout(() => e.target.style.backgroundColor = 'transparent', 200);
  });

  // Enable pinch and pan for demonstration, if desired
  mc.get('pinch').set({ enable: true });
  mc.get('pan').set({ direction: Hammer.DIRECTION_ALL });

  console.log('Hammer.js initialized on #stage.');
});

view raw JSON →