Reputation: 63
I want to get the id
of a dragged element in JavaScript in the drop event handler.
The green div
with the id
of place5
is draggable and the drop location is another div
with the id
of dropArea
(with a red border).
How do I get the id
of the place5
div
in the drop event handler?
function dragEventHandler(theEvent) {
theEvent.dataTransfer.setData("Text", theEvent.target.id);
// some code here.
}
function dropEventHandler(theEvent) {
// how to get the id of div with id "place5" here?
}
.mainArea {
width: 200px;
height: 100px;
border-color: red;
border-style: solid;
border-width: 5px;
}
#place5 {
background: green;
height: 20px;
width: 100px;
}
<div id="dropArea" class="mainArea" ondrop="dropEventHandler(event);" ondragover="event.preventDefault();">
</div>
<div id="place5" draggable="true" ondragstart="dragEventHandler(event);">
</div>
Upvotes: 4
Views: 9806
Reputation: 92
Perform the reverse of what you did during the drag start event.
So on dragstart you have:
function dragEventHandler(theEvent) {
theEvent.dataTransfer.setData("Text", theEvent.target.id);
//Some code here.
}
Thus on drop you would have:
function dropEventHandler(theEvent) {
var id = theEvent.dataTransfer.getData("Text");
//Other code here.
}
Upvotes: 5