Reputation: 9027
in this demo: http://www.netmagazine.com/files/tutorials/demos/2013/01/create-drag-and-drop-features-in-html5/demo/demo.html
you'll see that you can move items using drag and drop.
The code to do this is pretty straightforward:
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 it's doing is it stores an id of an element and then finds that id in dom and moves it by using appendChild.
The problem I experience is that I have elements that do not have Ids.
<span class=".myClass">item</span>
So, I have no way to uniquely identify an element, so I'm not sure how to move element.
Upvotes: 4
Views: 3067
Reputation: 214
In the case where you don't have id's, we can dynamically create and id for that dragabble element and after dropping that in target element, we have to remove that id value. This scenario worked for me.
taskItem.addEventListener('dragstart', function (event) {
event.target.id = "taskid";
event.dataTransfer.setData("taskItem", event.target.id);
}, false);
and drop handler is
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);
Upvotes: 0
Reputation: 16706
try to log the event in the dropUser function and search for the (event.target||event.srcElement).that is what u need.
function dropUser(target, event) {
console.log(event)
var user = event.dataTransfer.getData('User');
target.appendChild(event.target||event.srcElement);
}
Upvotes: -1
Reputation: 437574
You do not actually need an id, any identifier that can be expressed as a string will do (this is because getData
/setData
only work with string values). And if there is nothing already there you can simply make something up. Here we have an array of elements that allows associating 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);
}
This code uses Array.indexOf
which means no IE < 9, but that's a technical detail that can be easily worked around.
Upvotes: 7