5

I'm trying to set a custom data which is an HTML element on my drag event. So far I did this:

element.addEventListener('dragstart', event => {
  event.dataTransfer.setData('custom-data', document.querySelector('.the-element')
})

dropzone.addEventListener('drop', event => {
  const data = event.dataTransfer.getData('custom-data') // this is empty
})

Is there a way to do this?

I already tried to do JSON.stringify on the element before passing it to the drag event. but JSON.stringify does not work on HTMLElement object

This reference from mdn says it is possible to use custom data

bobharley
  • 662
  • 3
  • 17
  • Exactly what do you want? You want to transfer data during drag and drop? – Tan Duong Apr 17 '18 at 05:31
  • @TanDuong yes. and the data is and HTMLElement. But there is no data type for that. I tried to do `'application/json'` but I got `[object HTMLElement]` as a result – bobharley Apr 17 '18 at 05:36

1 Answers1

0

According to this MDN reference, you can specify the data type text/html and pass a well-formed HTML string. If you want to use an existing element in the DOM, you could pass its outerHTML string property.

plohm12
  • 45
  • 6
  • But I will lose reference if I use the outerHTML – bobharley Jan 17 '20 at 03:02
  • @bobharley From what I can see [on MDN](https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API/Recommended_drag_types#node), Firefox may offer the ability to drag and drop a node reference. I do not know which other browsers, if any, also support that feature. – plohm12 Jan 20 '20 at 15:55