Hammer.js

repository·master·Indexed 12 days ago

https://github.com/hammerjs/hammer.js

A lightweight JavaScript library for detecting multi-touch gestures on mobile and desktop devices. Version 2.0.8 provides built-in recognizers for tap, doubletap, press, pan, pinch, rotate, and swipe, as well as the Hammer.Manager class for creating custom gestures.

Tokens
4.2K
Snippets
18
Records
25
Agent score
96%

What's inside Hammer.js

  1. How to create custom gestures with Hammer.Manager

    master

    To recognize custom gestures (for example, a tripletap), you must use Hammer.Manager instead of the standard Hammer constructor. This involves three steps:

    1. Create a Hammer.Manager instance for your element.
    2. Create a specific recognizer (e.g., Hammer.Tap) with custom configuration.
    3. Add the recognizer to the manager and subscribe to the custom event.
    // Get a reference to an element.
    var square = document.querySelector('.square');
    
    // Create a manager to manage the element.
    var manager = new Hammer.Manager(square);
    
    // Create a recognizer.
    var TripleTap = new Hammer.Tap({
      event: 'tripletap',
      taps: 3
    });
    
    // Add the recognizer to the manager.
    manager.add(TripleTap);
    
    // Subscribe to the event.
    manager.on('tripletap', function(e) {
      e.target.classList.toggle('expand');
      console.log("You're triple tapping me!");
      console.log(e);
    });
    // Get a reference to an element.
    var square = document.querySelector('.square');
    
    // Create a manager to manage the element.
    var manager = new Hammer.Manager(square);
    
    // Create a recognizer.
    var TripleTap = new Hammer.Tap({
      event: 'tripletap',
      taps: 3
    });
    
    // Add the recognizer to the manager.
    manager.add(TripleTap);
    
    // Subscribe to the event.
    manager.on('tripletap', function(e) {
      e.target.classList.toggle('expand');
      console.log("You're triple tapping me!");
      console.log(e);
    });
  2. How recognizers work in Hammer.js

    master

    A Recognizer is the base class for all gesture detection logic. Every recognizer follows a specific lifecycle during an input session (from the first input to the last):

    1. POSSIBLE: The initial state when an input session starts.
    2. BEGAN: The gesture has started to meet the criteria.
    3. CHANGED: The gesture criteria are being met continuously (e.g., during a pan).
    4. ENDED / RECOGNIZED: The gesture has been successfully completed.
    5. CANCELLED: The gesture was interrupted.
    6. FAILED: The input did not meet the recognizer's criteria.

    Recognizers can be configured to work together using recognizeWith (to allow simultaneous gestures) or requireFailure (to only trigger if another gesture fails).

  3. Initialize a Hammer Manager

    master

    To use Hammer.js, create a new Manager instance by passing the DOM element you want to monitor for gestures. You can also provide an optional options object to configure the manager's behavior, such as specifying which recognizers to use or setting the touchAction property.

    By default, the Manager will automatically detect the best input type (Pointer, Touch, or Mouse) based on browser support.

    // Basic initialization
    var manager = new Hammer(element, { 
      // options here
    });
  4. Use hammer.js quick start for standard gestures

    master

    For standard gestures that hammer.js already recognizes (such as press, tap, or doubletap), you can create a simple Hammer instance directly on a DOM element and subscribe to events using .on().

    // Get a reference to an element.
    var square = document.querySelector('.square');
    
    // Create an instance of Hammer with the reference.
    var hammer = new Hammer(square);
    
    // Subscribe to a quick start event: press, tap, or doubletap.
    hammer.on('press', function(e) {
      e.target.classList.toggle('expand');
      console.log("You're pressing me!");
      console.log(e);
    });
    // Get a reference to an element.
    var square = document.querySelector('.square');
    
    // Create an instance of Hammer with the reference.
    var hammer = new Hammer(square);
    
    // Subscribe to a quick start event: press, tap, or doubletap.
    hammer.on('press', function(e) {
      e.target.classList.toggle('expand');
      console.log("You're pressing me!");
      console.log(e);
    });
  5. Configure Hammer.js default settings

    master

    Hammer.js provides several default configuration options via Hammer.defaults. These can be used to customize the behavior of the Manager or the Hammer constructor.

    Key configuration options include:

    • domEvents (Boolean): If true, Hammer will trigger actual DOM events. This is slower and disabled by default.
    • touchAction (String): Controls the touch-action CSS property. Setting it to compute (default) allows Hammer to automatically set the correct value based on active recognizers.
    • enable (Boolean): Whether the manager is enabled.
    • inputTarget (Null|EventTarget): Allows changing the parent input target element.
    • inputClass (Null|Function): Forces a specific input class.
    • preset (Array): The default array of recognizers used when calling the Hammer() constructor.
    • cssProps (Object): A collection of CSS properties (like userSelect, touchCallout, tapHighlightColor) that Hammer applies to the element to improve gesture recognition and prevent default browser behaviors.
    // Example of accessing defaults
    console.log(Hammer.defaults.touchAction); // 'compute'
  6. Configure Touch Action to prevent browser interference

    master

    Hammer.js can manage the CSS touch-action property to prevent the browser from handling certain gestures (like scrolling) that might interfere with your custom recognizers. This is controlled via the touchAction option in the Manager configuration or by calling manager.touchAction.set(value).

    Common values include:

    • none: Disables all browser touch actions.
    • pan-x: Allows only horizontal panning.
    • pan-y: Allows only vertical panning.
    • manipulation: Allows only non-emulation gestures (like zooming).
    • auto: Default browser behavior.
  7. Configure the TapRecognizer

    master

    The TapRecognizer detects quick taps or multi-taps. It can distinguish between single taps and multiple taps within a specific time interval.

    Default Options:

    • event: 'tap'
    • pointers: 1
    • taps: 1 (number of taps required to trigger the event)
    • interval: 300 (max time between taps for multi-taps)
    • time: 250 (max duration the pointer can be down)
    • threshold: 9 (max movement allowed during a tap)
    • posThreshold: 10 (max distance between taps for multi-taps)
    // Example: Double tap
    const doubleTap = new TapRecognizer({ taps: 2 });
  8. Configure the PanRecognizer

    master

    The PanRecognizer detects when a pointer is moved in a specific direction. You can constrain the direction using bitwise flags.

    Default Options:

    • event: 'pan'
    • threshold: 10 (minimum distance to trigger)
    • pointers: 1
    • direction: DIRECTION_ALL (horizontal and vertical)

    Direction Constants:

    • DIRECTION_LEFT: 2
    • DIRECTION_RIGHT: 4
    • DIRECTION_UP: 8
    • DIRECTION_DOWN: 16
    • DIRECTION_HORIZONTAL: DIRECTION_LEFT | DIRECTION_RIGHT
    • DIRECTION_VERTICAL: DIRECTION_UP | DIRECTION_DOWN
    • DIRECTION_ALL: DIRECTION_HORIZONTAL | DIRECTION_VERTICAL
    // Example: Pan only horizontally
    const pan = new PanRecognizer({ direction: DIRECTION_HORIZONTAL });
  9. Initialize Hammer.js with the Hammer class

    master

    The Hammer class is the primary entry point for the library. It is used to create instances that manage input events and gesture recognition for specific DOM elements. When initialized, it provides access to various recognizers and input types.

    import Hammer from 'hammerjs';
    
    const mc = new Hammer(element);
  10. Configure the SwipeRecognizer

    master

    The SwipeRecognizer detects fast movements (high velocity) in a specific direction.

    Default Options:

    • event: 'swipe'
    • threshold: 10
    • velocity: 0.3
    • direction: DIRECTION_HORIZONTAL | DIRECTION_VERTICAL
    • pointers: 1