Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it Possible to Trigger Drag Events Programmatically?

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.

like image 649
Levi Hackwith Avatar asked May 16 '14 21:05

Levi Hackwith


1 Answers

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);
like image 149
PCJ Avatar answered Oct 06 '22 20:10

PCJ