9


I am trying to create a dragEvent and fire it programmatically using this code on Chrome:

var ev = document.createEvent("MouseEvents");
ev.initEvent("dragstart");

and then fire it this way:

element.dispatchEvent(ev);

The element has draggable attribute.

The event was dispatched successfully. However on the event being fired - the dataTransfer object is null. Even when I try to set it manually to a working dataTransfer object - it still stays null.

Any ideas?
Thanks

Assaf
  • 788
  • 2
  • 9
  • 23
  • found another thread relevant: https://stackoverflow.com/questions/61376278/simulate-a-3-pixel-drag-on-draggable-elem – shailendra Jan 07 '21 at 20:30

2 Answers2

6

Unfortunately, it seems that there is no such a way to create a DataTransfer object programmatically at the moment. The description of HTML5 drag and drop interface says:

Although, for consistency with other event interfaces, the DragEvent interface has a constructor, it is not particularly useful. In particular, there's no way to create a useful DataTransfer object from script, as DataTransfer objects have a processing and security model that is coordinated by the browser during drag-and-drops

Please check more details here: http://www.whatwg.org/specs/web-apps/current-work/multipage/dnd.html#the-dragevent-and-datatransfer-interfaces

gustavohenke
  • 40,997
  • 14
  • 121
  • 129
Olga Gnatenko
  • 790
  • 1
  • 11
  • 14
2

Looks like it can work like this:

const dataTransfer = new DataTransfer;
dataTransfer.setData("data", '1');
cell.dispatchEvent(new DragEvent('drop', { dataTransfer: dataTransfer }));
Oleg V
  • 275
  • 2
  • 12