Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the id of a dragged element in JavaScript

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>
like image 955
Dpk Avatar asked Oct 20 '25 03:10

Dpk


1 Answers

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.
}
like image 58
user2692837 Avatar answered Oct 21 '25 17:10

user2692837



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!