Introduction
Hammer.js adds multi-touch gesture recognition to web applications with a small footprint. It handles tap, double-tap, swipe, press, pinch, rotate, and pan events across desktop and mobile browsers with a unified API.
What Hammer.js Does
- Recognizes tap, double-tap, swipe, press, pan, pinch, and rotate gestures
- Normalizes touch and pointer events across browsers and devices
- Supports simultaneous gesture recognition with configurable priorities
- Provides velocity and direction data for each recognized gesture
- Works with mouse, touch, and pointer events out of the box
Architecture Overview
Hammer.js wraps the browser's native touch, mouse, and pointer events into a unified input layer. Recognizers run in sequence on each input cycle, evaluating whether their gesture pattern matches. When a recognizer triggers, it emits an event with computed properties like velocity, direction, distance, and scale. Multiple recognizers can run simultaneously or be configured to require failure of another before activating.
Self-Hosting & Configuration
- Install via npm or include the UMD bundle from a CDN
- Create a Manager instance on any DOM element to start listening
- Configure recognizer thresholds like
threshold,pointers, anddirection - Use
requireFailure()to set priority between competing recognizers - Set
domEvents: trueto also fire standard DOM events for delegation
Key Features
- Tiny library (~3 KB gzipped) with zero dependencies
- Built-in recognizers cover all standard touch gestures
- Custom recognizer API for defining application-specific gestures
- Per-element manager instances allow different gesture configs per component
- Velocity and direction tracking for physics-based UI interactions
Comparison with Similar Tools
- interact.js — heavier, adds drag-and-drop and resizing; Hammer.js focuses purely on gesture recognition
- ZingTouch — newer alternative with a similar API but smaller community
- AlloyFinger — lighter but fewer built-in recognizers and less configuration
- Native Pointer Events — standard API but requires manual gesture math; Hammer.js abstracts it
FAQ
Q: Does Hammer.js work with React or Vue?
A: Yes. Wrap the Manager creation in a useEffect or mounted hook, and clean up with manager.destroy() on unmount.
Q: Can I detect custom gestures?
A: Yes. Extend Hammer.AttrRecognizer or Hammer.Recognizer and register it with the manager.
Q: Is Hammer.js still maintained? A: The core library is stable and widely used. Active maintenance is community-driven since the original author stepped back.
Q: Does it support passive event listeners?
A: Hammer.js uses non-passive listeners by default for preventDefault() support. You can configure this via the inputClass option.