Setting application/json as the data during the dragstart in HTML5 DND

Viewed 240

I observed the setting the JSON data in HTML5DND will be converted into string. Are there any alternatives and best practices for passing JSON Data other than stringifying.

// During drag enter
event.dataTransfer.setData('application/json', {
  id: 1
});


// During Drop data is printing as object
let data = event.dataTransfer.getData('application/json');
// printing [object Object]

2 Answers

In case my other answer does not answer your question, try dragging/dropping the object avatars into the textarea.

const object_1 = {id: 1}
const object_2 = {id: 2}
const p_1 = document.body.appendChild(document.createElement("p"))
const p_2 = document.body.appendChild(document.createElement("p"))
p_1.innerText = "object_1"
p_1.draggable = true
p_2.innerText = "object_2"
p_2.draggable = true
p_1.ondragstart = function () {
    event.dataTransfer.setData("text", "object_1")
}
p_2.ondragstart = function () {
    event.dataTransfer.setData("text", "object_2")
}
const textarea = document.body.appendChild(document.createElement("textarea"))
textarea.ondrop = function() {
    event.preventDefault()
    this.innerText = eval(event.dataTransfer.getData("text")).id
}

Related