Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to simulate HTML5 Drag and Drop events in javascript?

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.

like image 938
Bob Smith Avatar asked Mar 27 '13 06:03

Bob Smith


People also ask

How do you drag-and-drop elements in JavaScript?

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.

Is drag-and-drop possible using HTML5?

In HTML, any element can be dragged and dropped.

How do you set dragged data in HTML5?

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.


2 Answers

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: [] }}));
like image 66
Trav McKinney Avatar answered Sep 23 '22 09:09

Trav McKinney


You can try this one. It uses native HTML5 events, no jQuery

https://github.com/Photonios/JS-DragAndDrop-Simulator

like image 32
Oleg Abrazhaev Avatar answered Sep 22 '22 09:09

Oleg Abrazhaev