Draggable: Cancel dragging on ESC key up

Created on 6 Apr 2018  路  5Comments  路  Source: Shopify/draggable

Hello,

we are using draggable and are trying to cancel dragging of an item and its mirror by pressing ESC key. The solution I came up with is adding an event listener to the document on drag:start, that listens for ESC keyup event and removing it on drag:stop. The event listener simulates a dummy mouseup event and then dispatches it on document element.

  const triggerMouseUpOnESC = (evt) => {
    if (evt.which === ESC_KEY_CODE) {
      const clickEvent = document.createEvent("MouseEvents");
      clickEvent.initEvent("mouseup", true, true);
      document.dispatchEvent(clickEvent);
    }
  };

  draggable.on("drag:start", (evt) => {
    ...
    document.addEventListener("keyup", triggerMouseUpOnESC);
  });

  draggable.on("drag:stop", () => {
    ...
    document.removeEventListener("keyup", triggerMouseUpOnESC);
  });

I've been wondering whether there is any API from your side for this behaviour, I tried to search but couldn't find any. If that's the case is this a proper solution?

feature-request

Most helpful comment

+1 for this feature request, would be awesome to be able to cancel dragging. Is this still planned?

All 5 comments

@xmatusk3 thanks for bringing this up! Currently there is no API for canceling the current drag operation, I've been planning to add Draggable#cancel() for a while. That way we can trigger the drag:stop in a none-sensor specific way (e.g. not just mouse specific).
Your example would still have to work the same way though:

  const triggerMouseUpOnESC = (evt) => {
    if (evt.which === ESC_KEY_CODE) {
      draggable.cancel();
    }
  };

  draggable.on("drag:start", (evt) => {
    ...
    document.addEventListener("keyup", triggerMouseUpOnESC);
  });

  draggable.on("drag:stop", () => {
    ...
    document.removeEventListener("keyup", triggerMouseUpOnESC);
  });

Hope this helps, I'll try and get something together for this 馃憤

Thank you for fast response!

+1 for this feature request, would be awesome to be able to cancel dragging. Is this still planned?

up?

@bahung1221 I just added this feature to this commit and opened a PR. Do you have a chance to give some feedback?

Was this page helpful?
0 / 5 - 0 ratings