Reputation: 201
Is there a way in native HTML5 drag and drop to get the id of the element with the attribut draggable="true"
?
At first i thought it's standard that you get the id from the draggable container but actually it is always the id from the children element you start dragging on which is very annoying.
Here is an fiddle: https://jsfiddle.net/chickberger/2ujhodeh/2/
I need the id from the div ('correctid') instead of the image.
Any help is appreciated. :)
Upvotes: 4
Views: 3056
Reputation: 1177
The 'ev.target' is an image. You can fix this by using the parentNode:
function drag(ev) {
ev.dataTransfer.setData("text", ev.target.parentNode.id);
alert(ev.target.parentNode.id);
}
Upvotes: 0
Reputation: 241278
You can get a reference to that element by accessing the currentTarget
property instead of the target
property on the event
object.
In your case, event.target
was referring to the innermost element that was being targeted.
You want the currentTarget
property since it refers to the element that the event listener is attached to (which would be the element with the ondragstart
attribute).
function drag(ev) {
ev.dataTransfer.setData("text", ev.currentTarget.id);
alert(ev.currentTarget.id);
}
Upvotes: 6