javascript - Html5 dragging items across and within table cells -
i'm using html5 draggable drag items different table cells:
http://jsfiddle.net/d1wnk1bg/6/
<table border="1"> <tr> <th>column 1</th> <th>column 2</th> <th>column 3</th> </tr> <tr> <td><span class="event" id="item1" draggable="true">item 1</span> </td> <td><span class="event" id="item2" draggable="true">item 2</span> <span class="event" id="item3" draggable="true">item 3</span> </td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> </tr> </table> $(document).ready(function(){ $('.event').on("dragstart", function (event) { var dt = event.originalevent.datatransfer; dt.setdata('text', $(this).attr('id')); }); $('table td').on("dragenter dragover drop", function (event) { event.preventdefault(); if (event.type === 'drop') { var data = event.originalevent.datatransfer.getdata('text',$(this).attr('id')); de=$('#'+data).detach(); de.appendto($(this)); }; }); })
the problem approach if drag 'item 1' cell 'item 2' , 'item 3' are, item 1 gets appended end.
how can modify 'item 1' can added before 'item 2' or between 'item 2' , 'item 3'. tried going down rabbit hole of nested draggables gave pretty quickly, hoping there's easier way!
i forked fiddle , adjusted code bit:
http://jsfiddle.net/gl88q17m/1/
$(document).ready(function () { $('.event').on("dragstart", function (event) { var dt = event.originalevent.datatransfer; dt.setdata('text', $(this).attr('id')); }); $('table td').on("dragenter dragover drop", function (event) { event.preventdefault(); if (event.type === 'drop') { var data = event.originalevent.datatransfer.getdata('text', $(this).attr('id')); de = $('#' + data).detach(); if (event.originalevent.target.tagname === "span") { de.insertbefore($(event.originalevent.target)); } else { de.appendto($(this)); } }; }); })
what did checking whether item dropped directly td in case dropped element inserted after other entries or if dropped on top of item in case item inserted before item dropped item dropped on.
adding padding td makes easier drop item directly td if there 3 items inside.
table th, table td { width: 200px; height:70px; padding: 5px; } table span { display:block; background-color: #ccc; border: 1px solid black; color: fff; height: 30px; width: 100%; }
Comments
Post a Comment