interact.js

API Reference

Interaction.start(action, interactable, element)

Start an action with the given Interactable and Element as tartgets. The action must be enabled for the target Interactable and an appropriate number of pointers must be held down – 1 for drag/resize, 2 for gesture.

Use it with interactable.<action>able({ manualStart: false }) to always start actions manually

Parameters

  1. action object The action to be performed - drag, resize, etc.
  2. interactable Interactable The Interactable to target
  3. element Element The DOM Element to target

Returns: object interact

interact(target)
  .draggable({
    // disable the default drag start by down->move
    manualStart: true
  })
  // start dragging after the user holds the pointer down
  .on('hold', function (event) {
    var interaction = event.interaction;

    if (!interaction.interacting()) {
      interaction.start({ name: 'drag' },
                        event.interactable,
                        event.currentTarget);
    }
});

interact(element)

The methods of this variable can be used to set elements as interactables and also to change various default settings.

Calling it as a function and passing an element or a valid CSS selector string returns an Interactable object which has various methods to configure it.

Parameters

  1. element Element string The HTML or SVG Element to interact with or CSS selector

Returns: object An Interactable

Usage

interact(document.getElementById('draggable')).draggable(true);

var rectables = interact('rect');
rectables
    .gesturable(true)
    .on('gesturemove', function (event) {
        // something cool...
    })
    .autoScroll(true);

Interactable.draggable([options])

Gets or sets whether drag actions can be performed on the Interactable

Returns: boolean Indicates if this can be the target of drag events

var isDraggable = interact('ul li').draggable();

or

Parameters

  1. options boolean object true/false or An object with event listeners to be fired on drag events (object makes the Interactable draggable)

Returns: object This Interactable

interact(element).draggable({
    onstart: function (event) {},
    onmove : function (event) {},
    onend  : function (event) {},

    // the axis in which the first movement must be
    // for the drag sequence to start
    // 'xy' by default - any direction
    axis: 'x' || 'y' || 'xy',

    // max number of drags that can happen concurrently
    // with elements of this Interactable. Infinity by default
    max: Infinity,

    // max number of drags that can target the same element+Interactable
    // 1 by default
    maxPerElement: 2
});

Interactable.dropzone([options])

Returns or sets whether elements can be dropped onto this Interactable to trigger drop events

Dropzones can receive the following events:

  • dropactivate and dropdeactivate when an acceptable drag starts and ends
  • dragenter and dragleave when a draggable enters and leaves the dropzone
  • dragmove when a draggable that has entered the dropzone is moved
  • drop when a draggable is dropped into this dropzone
  • Use the accept option to allow only elements that match the given CSS selector or element.

    Use the overlap option to set how drops are checked for. The allowed values are:

  • 'pointer', the pointer must be over the dropzone (default)
  • 'center', the draggable element's center must be over the dropzone
  • a number from 0-1 which is the (intersection area) / (draggable area).
  • e.g. `0.5` for drop to happen when half of the area of the draggable is over the dropzone

    Parameters

    1. options boolean object null The new value to be set.
    interact('.drop').dropzone({
      accept: '.can-drop' || document.getElementById('single-drop'),
      overlap: 'pointer' || 'center' || zeroToOne
    }

    Returns: boolean object The current setting or this Interactable

    Interactable.dropChecker(…)

    DEPRECATED. Use interactable.dropzone({ checker: function... }) instead.

    Gets or sets the function used to check if a dragged element is over this Interactable.

    Parameters

    1. checker function The function that will be called when checking for a drop

    Returns: Function Interactable The checker function or this Interactable

    The checker function takes the following arguments:

    Parameters

    1. dragEvent InteractEvent The related dragmove or dragend event
    2. event TouchEvent PointerEvent MouseEvent The user move/up/end Event related to the dragEvent
    3. dropped boolean The value from the default drop checker
    4. dropzone Interactable The dropzone interactable
    5. dropElement Element The dropzone element
    6. draggable Interactable The Interactable being dragged
    7. draggableElement Element The actual element that's being dragged

    Usage:

    interact(target)
    .dropChecker(function(dragEvent,         // related dragmove or dragend event
                          event,             // TouchEvent/PointerEvent/MouseEvent
                          dropped,           // bool result of the default checker
                          dropzone,          // dropzone Interactable
                          dropElement,       // dropzone elemnt
                          draggable,         // draggable Interactable
                          draggableElement) {// draggable element
    
      return dropped && event.target.hasAttribute('allow-drop');
    }

    Interactable.accept([newValue])

    Deprecated. add an accept property to the options object passed to Interactable.dropzone instead.

    Gets or sets the Element or CSS selector match that this Interactable accepts if it is a dropzone.

    Parameters

    1. newValue Element string null

    If it is an Element, then only that element can be dropped into this dropzone. If it is a string, the element being dragged must match it as a selector. If it is null, the accept options is cleared - it accepts any element.

    Returns: string Element null Interactable The current accept option if given undefined or this Interactable

    Interactable.resizable([options])

    Gets or sets whether resize actions can be performed on the Interactable

    Returns: boolean Indicates if this can be the target of resize elements

    var isResizeable = interact('input[type=text]').resizable();

    or

    Parameters

    1. options boolean object true/false or An object with event listeners to be fired on resize events (object makes the Interactable resizable)

    Returns: object This Interactable

    interact(element).resizable({
        onstart: function (event) {},
        onmove : function (event) {},
        onend  : function (event) {},
    
        edges: {
          top   : true,       // Use pointer coords to check for resize.
          left  : false,      // Disable resizing from left edge.
          bottom: '.resize-s',// Resize if pointer target matches selector
          right : handleEl    // Resize if pointer target is the given Element
        },
    
        // Width and height can be adjusted independently. When `true`, width and
        // height are adjusted at a 1:1 ratio.
        square: false,
    
        // Width and height can be adjusted independently. When `true`, width and
        // height maintain the aspect ratio they had when resizing started.
        preserveAspectRatio: false,
    
        // a value of 'none' will limit the resize rect to a minimum of 0x0
        // 'negate' will allow the rect to have negative width/height
        // 'reposition' will keep the width/height positive by swapping
        // the top and bottom edges and/or swapping the left and right edges
        invert: 'none' || 'negate' || 'reposition'
    
        // limit multiple resizes.
        // See the explanation in the @Interactable.draggable example
        max: Infinity,
        maxPerElement: 1,
    });

    Interactable.squareResize([newValue])

    Deprecated. Add a square: true || false property to Interactable.resizable instead

    Gets or sets whether resizing is forced 1:1 aspect

    Returns: boolean Current setting

    or

    Parameters

    1. newValue boolean

    Returns: object this Interactable

    Interactable.gesturable([options])

    Gets or sets whether multitouch gestures can be performed on the Interactable's element

    Returns: boolean Indicates if this can be the target of gesture events

    var isGestureable = interact(element).gesturable();

    or

    Parameters

    1. options boolean object true/false or An object with event listeners to be fired on gesture events (makes the Interactable gesturable)

    Returns: object this Interactable

    interact(element).gesturable({
        onstart: function (event) {},
        onmove : function (event) {},
        onend  : function (event) {},
    
        // limit multiple gestures.
        // See the explanation in @Interactable.draggable example
        max: Infinity,
        maxPerElement: 1,
    });

    Interactable.autoScroll([options])

    Deprecated. Add an autoscroll property to the options object passed to Interactable.draggable or Interactable.resizable instead.

    Returns or sets whether dragging and resizing near the edges of the window/container trigger autoScroll for this Interactable

    Returns: object Object with autoScroll properties

    or

    Parameters

    1. options object boolean

    options can be:

  • an object with margin, distance and interval properties,
  • true or false to enable or disable autoScroll or
  • Returns: Interactable this Interactable

    Interactable.snap([options])

    Deprecated. Add a snap property to the options object passed to Interactable.draggable or Interactable.resizable instead.

    Returns or sets if and how action coordinates are snapped. By default, snapping is relative to the pointer coordinates. You can change this by setting the elementOrigin.

    Returns: boolean object false if snap is disabled; object with snap properties if snap is enabled

    or

    Parameters

    1. options object boolean null

    Returns: Interactable this Interactable

    Usage

    interact(document.querySelector('#thing')).snap({
        targets: [
            // snap to this specific point
            {
                x: 100,
                y: 100,
                range: 25
            },
            // give this function the x and y page coords and snap to the object returned
            function (x, y) {
                return {
                    x: x,
                    y: (75 + 50 * Math.sin(x * 0.04)),
                    range: 40
                };
            },
            // create a function that snaps to a grid
            interact.createSnapGrid({
                x: 50,
                y: 50,
                range: 10,              // optional
                offset: { x: 5, y: 10 } // optional
            })
        ],
        // do not snap during normal movement.
        // Instead, trigger only one snapped move event
        // immediately before the end event.
        endOnly: true,
    
        relativePoints: [
            { x: 0, y: 0 },  // snap relative to the top left of the element
            { x: 1, y: 1 },  // and also to the bottom right
        ],  
    
        // offset the snap target coordinates
        // can be an object with x/y or 'startCoords'
        offset: { x: 50, y: 50 }
      }
    });

    Interactable.inertia([options])

    Deprecated. Add an inertia property to the options object passed to Interactable.draggable or Interactable.resizable instead.

    Returns or sets if and how events continue to run after the pointer is released

    Returns: boolean object false if inertia is disabled; object with inertia properties if inertia is enabled

    or

    Parameters

    1. options object boolean null

    Returns: Interactable this Interactable

    Usage

    // enable and use default settings
    interact(element).inertia(true);
    
    // enable and use custom settings
    interact(element).inertia({
        // value greater than 0
        // high values slow the object down more quickly
        resistance     : 16,
    
        // the minimum launch speed (pixels per second) that results in inertia start
        minSpeed       : 200,
    
        // inertia will stop when the object slows down to this speed
        endSpeed       : 20,
    
        // boolean; should actions be resumed when the pointer goes down during inertia
        allowResume    : true,
    
        // boolean; should the jump when resuming from inertia be ignored in event.dx/dy
        zeroResumeDelta: false,
    
        // if snap/restrict are set to be endOnly and inertia is enabled, releasing
        // the pointer without triggering inertia will animate from the release
        // point to the snaped/restricted point in the given amount of time (ms)
        smoothEndDuration: 300,
    
        // an array of action types that can have inertia (no gesture)
        actions        : ['drag', 'resize']
    });
    
    // reset custom settings and use all defaults
    interact(element).inertia(null);

    Interactable.actionChecker([checker])

    Gets or sets the function used to check action to be performed on pointerDown

    Parameters

    1. checker function null A function which takes a pointer event, defaultAction string, interactable, element and interaction as parameters and returns an object with name property 'drag' 'resize' or 'gesture' and optionally an edges object with boolean 'top', 'left', 'bottom' and right props.

    Returns: Function Interactable The checker function or this Interactable

    interact('.resize-drag')
      .resizable(true)
      .draggable(true)
      .actionChecker(function (pointer, event, action, interactable, element, interaction) {
    
      if (interact.matchesSelector(event.target, '.drag-handle') {
        // force drag with handle target
        action.name = drag;
      }
      else {
        // resize from the top and right edges
        action.name  = 'resize';
        action.edges = { top: true, right: true };
      }
    
      return action;
    });

    Interactable.getRect([element])

    The default function to get an Interactables bounding rect. Can be overridden using Interactable.rectChecker.

    Parameters

    1. element Element The element to measure.

    Returns: object The object's bounding rectangle.

    1. {
      1. top : 0,
      2. left : 0,
      3. bottom: 0,
      4. right : 0,
      5. width : 0,
      6. height: 0
    2. }

    Interactable.rectChecker([checker])

    Returns or sets the function used to calculate the interactable's element's rectangle

    Parameters

    1. checker function A function which returns this Interactable's bounding rectangle. See Interactable.getRect

    Returns: function object The checker function or this Interactable

    Interactable.styleCursor([newValue])

    Returns or sets whether the action that would be performed when the mouse on the element are checked on mousemove so that the cursor may be styled appropriately

    Parameters

    1. newValue boolean

    Returns: boolean Interactable The current setting or this Interactable

    Interactable.preventDefault([newValue])

    Returns or sets whether to prevent the browser's default behaviour in response to pointer events. Can be set to:

  • 'always' to always prevent
  • 'never' to never prevent
  • 'auto' to let interact.js try to determine what would be best
  • Parameters

    1. newValue string true, false or 'auto'

    Returns: string Interactable The current setting or this Interactable

    Interactable.origin(…)

    Gets or sets the origin of the Interactable's element. The x and y of the origin will be subtracted from action event coordinates.

    Parameters

    1. origin object string An object eg. { x: 0, y: 0 } or string 'parent', 'self' or any CSS selector

    OR

    Parameters

    1. origin Element An HTML or SVG Element whose rect will be used

    Returns: object The current origin or this Interactable

    Interactable.deltaSource([newValue])

    Returns or sets the mouse coordinate types used to calculate the movement of the pointer.

    Parameters

    1. newValue string Use 'client' if you will be scrolling while interacting; Use 'page' if you want autoScroll to work

    Returns: string object The current deltaSource or this Interactable

    Interactable.restrict([options])

    Deprecated. Add a restrict property to the options object passed to Interactable.draggable, Interactable.resizable or Interactable.gesturable instead.

    Returns or sets the rectangles within which actions on this interactable (after snap calculations) are restricted. By default, restricting is relative to the pointer coordinates. You can change this by setting the elementRect.

    Parameters

    1. options object an object with keys drag, resize, and/or gesture whose values are rects, Elements, CSS selectors, or 'parent' or 'self'

    Returns: object The current restrictions object or this Interactable

    interact(element).restrict({
        // the rect will be `interact.getElementRect(element.parentNode)`
        drag: element.parentNode,
    
        // x and y are relative to the the interactable's origin
        resize: { x: 100, y: 100, width: 200, height: 200 }
    })
    
    interact('.draggable').restrict({
        // the rect will be the selected element's parent
        drag: 'parent',
    
        // do not restrict during normal movement.
        // Instead, trigger only one restricted move event
        // immediately before the end event.
        endOnly: true,
    
        // https://github.com/taye/interact.js/pull/72#issue-41813493
        elementRect: { top: 0, left: 0, bottom: 1, right: 1 }
    });

    Interactable.context()

    Gets the selector context Node of the Interactable. The default is window.document.

    Returns: Node The context Node of this Interactable

    Interactable.ignoreFrom([newValue])

    If the target of the mousedown, pointerdown or touchstart event or any of it's parents match the given CSS selector or Element, no drag/resize/gesture is started.

    Parameters

    1. newValue string Element null a CSS selector string, an Element or null to not ignore any elements

    Returns: string Element object The current ignoreFrom value or this Interactable

    interact(element, { ignoreFrom: document.getElementById('no-action') });
    // or
    interact(element).ignoreFrom('input, textarea, a');

    Interactable.allowFrom([newValue])

    A drag/resize/gesture is started only If the target of the mousedown, pointerdown or touchstart event or any of it's parents match the given CSS selector or Element.

    Parameters

    1. newValue string Element null a CSS selector string, an Element or null to allow from any element

    Returns: string Element object The current allowFrom value or this Interactable

    interact(element, { allowFrom: document.getElementById('drag-handle') });
    // or
    interact(element).allowFrom('.handle');

    Interactable.element()

    If this is not a selector Interactable, it returns the element this interactable represents

    Returns: Element HTML / SVG Element

    Interactable.fire(iEvent)

    Calls listeners for the given InteractEvent type bound globally and directly to this Interactable

    Parameters

    1. iEvent InteractEvent The InteractEvent object to be fired on this Interactable

    Returns: Interactable this Interactable

    Interactable.on(eventType, listener, [useCapture])

    Binds a listener for an InteractEvent or DOM event.

    Parameters

    1. eventType string array object The types of events to listen for
    2. listener function The function to be called on the given event(s)
    3. useCapture boolean useCapture flag for addEventListener

    Returns: object This Interactable

    Interactable.off(eventType, listener, [useCapture])

    Removes an InteractEvent or DOM event listener

    Parameters

    1. eventType string array object The types of events that were listened for
    2. listener function The listener function to be removed
    3. useCapture boolean useCapture flag for removeEventListener

    Returns: object This Interactable

    Interactable.set(options)

    Reset the options of this Interactable

    Parameters

    1. options object The new settings to apply

    Returns: object This Interactable

    Interactable.unset()

    Remove this interactable from the list of interactables and remove it's drag, drop, resize and gesture capabilities

    Returns: object interact

    interact.isSet(element)

    Check if an element has been set

    Parameters

    1. element Element The Element being searched for

    Returns: boolean Indicates if the element or CSS selector was previously passed to interact

    interact.on(type, listener, [useCapture])

    Adds a global listener for an InteractEvent or adds a DOM event to document

    Parameters

    1. type string array object The types of events to listen for
    2. listener function The function to be called on the given event(s)
    3. useCapture boolean useCapture flag for addEventListener

    Returns: object interact

    interact.off(type, listener, [useCapture])

    Removes a global InteractEvent listener or DOM event from document

    Parameters

    1. type string array object The types of events that were listened for
    2. listener function The listener function to be removed
    3. useCapture boolean useCapture flag for removeEventListener

    Returns: object interact

    interact.enableDragging([newValue])

    Deprecated.

    Returns or sets whether dragging is enabled for any Interactables

    Parameters

    1. newValue boolean true to allow the action; false to disable action for all Interactables

    Returns: boolean object The current setting or interact

    interact.enableResizing([newValue])

    Deprecated.

    Returns or sets whether resizing is enabled for any Interactables

    Parameters

    1. newValue boolean true to allow the action; false to disable action for all Interactables

    Returns: boolean object The current setting or interact

    interact.enableGesturing([newValue])

    Deprecated.

    Returns or sets whether gesturing is enabled for any Interactables

    Parameters

    1. newValue boolean true to allow the action; false to disable action for all Interactables

    Returns: boolean object The current setting or interact

    interact.debug()

    Returns debugging data

    Returns: object An object with properties that outline the current state and expose internal functions and variables

    interact.margin([newValue])

    Deprecated. Use interact(target).resizable({ margin: number }); instead. Returns or sets the margin for autocheck resizing used in Interactable.getAction. That is the distance from the bottom and right edges of an element clicking in which will start resizing

    Parameters

    1. newValue number

    Returns: number interact The current margin value or interact

    interact.supportsTouch()

    Returns: boolean Whether or not the browser supports touch input

    interact.supportsPointerEvent()

    Returns: boolean Whether or not the browser supports PointerEvents

    interact.stop(event)

    Cancels all interactions (end events are not fired)

    Parameters

    1. event Event An event on which to call preventDefault()

    Returns: object interact

    interact.dynamicDrop([newValue])

    Returns or sets whether the dimensions of dropzone elements are calculated on every dragmove or only on dragstart for the default dropChecker

    Parameters

    1. newValue boolean True to check on each move. False to check only before start

    Returns: boolean interact The current setting or interact

    interact.pointerMoveTolerance([newValue])

    Returns or sets the distance the pointer must be moved before an action sequence occurs. This also affects tolerance for tap events.

    Parameters

    1. newValue number The movement from the start position must be greater than this value

    Returns: number Interactable The current setting or interact

    interact.maxInteractions([newValue])

    Returns or sets the maximum number of concurrent interactions allowed. By default only 1 interaction is allowed at a time (for backwards compatibility). To allow multiple interactions on the same Interactables and elements, you need to enable it in the draggable, resizable and gesturable 'max' and 'maxPerElement' options.

    Parameters

    1. newValue number Any number. newValue <= 0 means no interactions.