10

I'm currently using the library Draggabilly to add drag and drop functionality to my application. What I'm trying to do, is trigger the drop event (the HTML5 native one) on an instance of the CKEditor and then perform a task. Here's what I've figured out so far:

  1. The CKEditor will only listen to native HTML5 events like dragover and drop.
  2. Dragabilly does not trigger the native drag and drop events. Instead it uses mousedown and mouseup.

My question is, is there a way to use dispatchEvent or some similar method to simulate the dragstart, drag and drop events?

If there's a better solution to this problem other than the one I've mentioned, please let me know.

Thanks.

Levi Hackwith
  • 9,232
  • 18
  • 64
  • 115

1 Answers1

7

I have done a function for that, based on some code in stackoverflow, also I read
in MDN that the form I'm doing the object is deprecated but it works to me, I'll correct that in the future but for now this can help you

function fireCustomEvent(eventName, element, data) {
    'use strict';
    var event;
    data = data || {};
    if (document.createEvent) {
        event = document.createEvent("HTMLEvents");
        event.initEvent(eventName, true, true);
    } else {
        event = document.createEventObject();
        event.eventType = eventName;
    }

    event.eventName = eventName;
    event = $.extend(event, data);

    if (document.createEvent) {
        element.dispatchEvent(event);
    } else {
        element.fireEvent("on" + event.eventType, event);
    }
}

and how to use it for events for which you are asking

    fireCustomEvent('dragover', someDomObject);
    fireCustomEvent('drop', someDomObject, {dataTransfer: {files: [mockedfile]}});
    fireCustomEvent('dragend', someDomObject);
allenhwkim
  • 27,270
  • 18
  • 89
  • 122
PCJ
  • 580
  • 1
  • 4
  • 13
  • MDN indicates that `createEvent()` has many deprecated methods and `ConstructEvent()` should be used instead: https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent, https://developer.mozilla.org/en-US/docs/Web/API/Document/createEvent – Ben Mar 13 '17 at 18:21
  • 1
    On chrome the drop event fires but the dataTransfer property is always missing :( – travisjayday Jul 31 '19 at 18:13