Html drag and drop without id

in this demo: http://www.netmagazine.com/files/tutorials/demos/2013/01/create-drag-and-drop-features-in-html5/demo/demo.html
You will see that you can move items using drag and drop.
The code for this is quite simple:

function dragUser(user, event) { event.dataTransfer.setData('User', user.id); } function dropUser(target, event) { var user = event.dataTransfer.getData('User'); target.appendChild(document.getElementById(user)); } 

What he does is he stores the identifier of the element and then finds that id in dom and moves it using appendChild.
The problem I'm experiencing is that I have elements that don't have identifiers.

 <span class=".myClass">item</span> 

So, I have no way to uniquely identify the element, so I'm not sure how to move the element.

+4
source share
3 answers

You really don't need an identifier, any identifier that can be expressed as a string will do (this is because getData / setData only works with string values). And if there’s nothing there already, you can just do something. Here we have an array of elements that allows you to associate an element (which cannot be represented as a string) with its index in the array (which can):

 var elements = []; function dragUser(element, event) { var index = elements.indexOf(element); if (index == -1) { // not already existing in the array, add it now elements.push(element); index = elements.length - 1; } event.dataTransfer.setData('index', index); } function dropUser(target, event) { var element = elements[event.dataTransfer.getData('index')]; target.appendChild(element); } 

Look at the action .

This code uses Array.indexOf , which means no IE <9, but this is a technical detail that can be easily circumvented.

+6
source

try to register the event in the dropUser function and search (event.target || event.srcElement). That's what you need.

  function dropUser(target, event) { console.log(event) var user = event.dataTransfer.getData('User'); target.appendChild(event.target||event.srcElement); } 
0
source

In the case when you do not have an identifier, we can dynamically create an id for this dragabble element, and after removing this in the target element, we need to delete this id value. This script worked for me.

 taskItem.addEventListener('dragstart', function (event) { event.target.id = "taskid"; event.dataTransfer.setData("taskItem", event.target.id); 

}, false);

and drop handler

 taskView.addEventListener('drop', function (event) { event.preventDefault(); var data = event.dataTransfer.getData("taskItem"); var element = document.getElementById(data); event.target.appendChild(element); element.removeAttribute('id'); }, false); 
0
source

Source: https://habr.com/ru/post/1484268/


All Articles