leofontes leofontes - 7 months ago 11
Javascript Question

HTML5 Drag and Drop access Attribute

I was studying Drag and Drop to implement on a project, got it to work using HTML5 as you can see on this CodePen but I need it to be more complex to use on my project, specially to be able to access the data-property of the dragged object.

This is the HTML

<section class="sectionOne">

<div draggable="true" class="sec-one-div" ondrag="dragCheck(event);" ondragstart="dragStart(event);" data-somedata="300">
<p>This is section one</p>
</div>

</section>
<section class="sectionTwo" ondrop="drop(event);" ondragover="dragover(event);" id="secTwo">

<p>This is section two</p>

</section>
<section class="sectionThree" >

<p>This is section three</p>

</section>


The JS

function dragCheck(ev) {
console.log("im dragging");
}

function dragStart(ev) {
console.log('drag start');
ev.dataTransfer.setData("text", "this is some text");
}

function dragover(ev) {
ev.preventDefault();
// Set the dropEffect to move
ev.dataTransfer.dropEffect = "move"
}

function drop(ev) {
ev.preventDefault();
console.log('drop');
var data = ev.dataTransfer.getData('text');
$('#secTwo').append('hahaaha');
}


I need to access the 'data-somedata' attribute of the div that was dragged (on my project I'll need 5 of them but for now 1 will do) so that I can append the correct values on another element. How can I do that?

The documentation wasn't clear to me what I should use to obtain this result, all help is appreciated. If more information is necessary, please let me know.

Answer

The event contains the target dragged element, so you can get the attribute for that element using:

function dragCheck(ev) {
  console.log("im dragging");
  console.log(ev.target.getAttribute("data-someinfo"));
}

or with jQuery:

function dragCheck(ev) {
  console.log("im dragging");
  console.log($(ev.target).attr('data-someinfo'));
}
Comments