taye / interact.js

JavaScript drag and drop, resizing and multi-touch gestures with inertia and snapping for modern browsers (and also IE9+)

Home Page:http://interactjs.io/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Change modifier while dragging - add/remove snap targets while dragging

emmernme opened this issue · comments

While dragging, attempting to change snap targets when entering a dropzone does not take effect until the next time the draggable is dragged.

interact(e).dropzone({
    ondragenter: (event) => {
        interact(event.relatedTarget).draggable({
          modifiers: [
            interact.modifiers.snap({
              targets: [ /****/ ]
            })
          ]
        });
      }
    }
);

Is there a way to change the snapping targets while a draggable is being dragged, and have it take effect immediately?

I solved this by setting the snap targets to functions, and referencing a dynamic array.

Draggable:

interact.modifiers.snap({
  targets: [
    () => { // Original position
      if (this.snapTargets.length > 0) {
        return this.snapTargets[0];
      }
    },
    () => {
      if (this.snapTargets.length == 2) {
        return this.snapTargets[1];
      }
    }
  ],
  endOnly: true,
  range: Infinity,
  relativePoints: [
    { x: 0.5, y: 0.5 }, // to the center
  ],
})

Dropzone:

ondragenter: (event) => {
  if (hotspot_id == dropzone_id) {
    this.snapTargets[1] = {
      x: zone.getRect(e).left + zone.getRect(e).width / 2,
      y: zone.getRect(e).top + zone.getRect(e).height / 2,
    };
  }
}