As title, I'm trying to simulate an HTML5 drag and drop event in javascript.
I've looked into jquery.ui.simulate and also the simulate function here. Both seem to be able to be used to simluate drag and drop by simulating mousedown, mousemove, and mouseup which works with jQuery UI objects.
But the drag/drop events in pages like drag and drop demo site do not seem to be simulatable using the same methods. Triggering a mousedown doesn't seem to fire the dragstart HTML5 event.
Is there a way to either get dragstart events to be fired based on a simulating mousedown/mousemove/etc, or is there a way to simulate the dragstart (and then drop) events directly?
I've tried modifying the simulation function found on SO to add the HTML5 dragstart event so I could try something like the following on the demo page
simulate( document.querySelector('#three'), 'dragstart')
but I get an error because I'm not sure how to create the dataTransfer object on the simulated dragstart event correctly.
Basically, I'll accept any answer that would let me drag element 'three' to the 'bin' element in the demo drag and drop page either using jquery.ui.simluate (or another library) or by using a modified version of the simulate function I found on SO.
How it works: First, select the draggable element using the querySelector() . Second, attach a dragstart event handler to the draggable element. Third, define the dragStart() function to handle the dragstart event.
In HTML, any element can be dragged and dropped.
setData() The DataTransfer. setData() method sets the drag operation's drag data to the specified data and type. If data for the given type does not exist, it is added at the end of the drag data store, such that the last item in the types list will be the new type.
Your best bet is to recreate a fake event object.
In my unit tests for a drag-and-drop file upload library (Droplit, shameless plug), I have been doing this with jQuery's Event method. In my source code I set my drop event listener with element.ondrop()
like so:
element.ondrop = function(e) {
e.preventDefault();
readFiles(e.dataTransfer.files);
};
And then I can test this out by building a fake event object and passing it into the ondrop
method.
element.ondrop($.Event('drop', {dataTransfer: { files: [] }}));
You can try this one. It uses native HTML5 events, no jQuery
https://github.com/Photonios/JS-DragAndDrop-Simulator
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With