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>
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.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With