Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
179
rated 0 times [  184] [ 5]  / answers: 1 / hits: 30068  / 10 Years ago, wed, october 22, 2014, 12:00:00

I am fairly new to jQuery and am stuck trying to get a dragged image elements id to append to the drop target instead of the image element itself or the drop targets id. I am using the html5 native DnD. And so far I can get the element itself to append by sending through its id with the datatransfer method in the drag function and the getdata function in the drop. Whenever I try to call that id from the drop however it gets the drop target id instead of the dragged elements.



Any help would be greatly appreciated as I have searched thoroughly online and found nothing but more methods to get the target id of the drop area. Here is a snippet of my current code fiddle:



function allowDrop(ev) {
ev.preventDefault();
}

function dragStart(ev) {

ev.dataTransfer.setData('Text/html', ev.target.id); // sends the dragged images data.

//alert(ev.target.id); // alerts the correct id of the dragged image.

}


function drop(ev) {

ev.preventDefault();
var data = ev.dataTransfer.getData(text/html);//retrieves dropped images data.
ev.target.appendChild(document.getElementById(data));//this displays the dropped image.

//alert(ev.target.id); // alerts the id of the drop target(Want to get the dropped images id.)

//$(#mybillets).append(<span>+ev.target.id+ </span>); //appends the drop targets id(Want to append the dropped images id.)
}

More From » jquery

 Answers
22

In the drop method looks like ev is the event object, so ev.target will refer to the element on which the item was dropped.



So use ev.target.id to refer to the drop target id.





function allowDrop(ev) {
ev.preventDefault();
}

function drag(ev) {
ev.dataTransfer.setData('Text/html', ev.target.id);
}

function drop(ev, target) {
ev.preventDefault();
console.log(target.id, ev.target.id)

var data = ev.dataTransfer.getData(text/html);
alert(data)
}

#div1 {
width: 350px;
height: 70px;
padding: 10px;
border: 1px solid #aaaaaa;
}

<div id=div1 ondrop=drop(event, this) ondragover=allowDrop(event)></div>
<br/>
<img id=drag1 src=//placehold.it/336X69/ff0000 draggable=true ondragstart=drag(event) width=336 height=69 />




[#69050] Sunday, October 19, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mckenna

Total Points: 445
Total Questions: 109
Total Answers: 109

Location: Virgin Islands (U.S.)
Member since Sun, May 16, 2021
3 Years ago
;