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>
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>
Share
Improve this question
edited Sep 19, 2022 at 20:54
peejay
1,3553 gold badges12 silver badges21 bronze badges
asked Feb 22, 2014 at 5:46
DpkDpk
631 silver badge9 bronze badges
0
1 Answer
Reset to default 5Perform 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.
}