Ankit Doshi Ankit Doshi - 28 days ago 7
HTML Question

Jquery drag and drop based on data-id

I am newbie to drag and drop functionalities.

Jquery :

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

function drag(ev) {
var DataId = ev.target.parentNode.getAttribute('data-id');
alert("Data Id : "+DataId);
var selected_table =$("#rows .sim-row[data-id='"+DataId+"']");
//var main_table = selected_table.parentNode;
alert("Data Id : "+selected_table.html());
ev.dataTransfer.setData("text",selected_table);
}

function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("text");
alert("Data Id : "+data.html());
ev.target.appendChild(data.clone());
}


HTML CODE :

<div id="content" ondrop="drop(event)" ondragover="allowDrop(event)">
</div>

<div id="rows">
<table class="sim-row" data-id="1001" id="1001">
<tr>
<td class="sim-row-header1 sim-row-edit width100" data-type="title">Main Title</td>
</tr>
</table>
</div>

<div class="buttons" data-id="1001" id="1001" draggable="true" ondragstart="drag(event)" ondrop="drop(event)">
<img id="image"src="<?php echo base_url()?>assets/invoice/preview/1001.png" alt="title">Title
</div>


I want to achieve like whenever i am drag and drop image so that time full table must need to add into below div




I have multiple tables which will work like entire table will be dragabble into div.But image must not remove from place.Only its content required to clone or similar.

Right now i am getting below error.But not sure why it's showing me that error.

TypeError: data.html is not a function


How can i achieve that ?
Any ideas ? Any suggestions ?

Answer Source

Here you go with a solution https://jsfiddle.net/ed5bmth2/1/

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

drag = function(ev) {
  var DataId = ev.target.parentNode.getAttribute('data-id');
  var selected_table =$("#rows .sim-row[data-id='"+DataId+"']");
  ev.dataTransfer.setData("text",DataId);
}

drop = function(ev) {
  ev.preventDefault();
  var data = ev.dataTransfer.getData("text");
  ev.target.appendChild(document.getElementById(data));
}
#content {
  height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content" ondrop="drop(event)" ondragover="allowDrop(event)"></div>

<div id="rows">
  <table class="sim-row" data-id="1001" id="1001">
    <tr>
      <td class="sim-row-header1 sim-row-edit width100" data-type="title">Main Title</td>                         
      </tr>
   </table>
</div>  

<div class="buttons"  data-id="1001" id="1001" draggable="true" ondragstart="drag(event)" ondrop="drop(event)">
  <img id="image"src="https://www.w3schools.com/html/img_logo.gif" alt="title">Title
</div>

Hope this will help you.